提交 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.
- 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
......@@ -72,7 +72,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//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)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
......@@ -81,7 +81,7 @@ export default function abilityTest() {
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
done();
})
......@@ -119,7 +119,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//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)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
......@@ -128,7 +128,7 @@ export default function abilityTest() {
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
//ui test code
//init uidriver
......@@ -154,20 +154,173 @@ export default function abilityTest() {
## Running the Test Script
### In DevEco Studio
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.
- 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.
1. Test package level: All test cases in the test package are 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)
## 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.
![](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 About Unit Test Cases
......@@ -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.
**Solution**
**Solution**
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
**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.
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**
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.
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
#### The failure log contains "Get windows failed/GetRootByWindow failed"
......
# 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.
## 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**
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**
......@@ -24,9 +24,9 @@ You do not need to care about the implementation of the database locking mechani
## 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)
......@@ -38,6 +38,6 @@ The RDB provides common operation APIs for external systems. It uses the SQLite
## 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.
......@@ -71,11 +71,14 @@ 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.
```
import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts';
private requestPermissions() {
let permissionList: Array<string> = [
"ohos.permission.READ_MEDIA"
];
this.context.requestPermissionsFromUser(permissionList)
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, permissionList)
.then(data => {
console.info(`request permission data result = ${data.authResults}`)
})
......
......@@ -42,8 +42,8 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE)
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE);
// 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) => {
if (fileAsset != undefined) {
......@@ -80,7 +80,7 @@ async function example() {
selectionArgs: [],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0];
album.albumName = 'newAlbum';
......@@ -88,7 +88,7 @@ async function example() {
album.commitModify().then(function() {
console.info("albumRename successfully");
}).catch(function(err){
console.info("albumRename failed with error:"+ err);
console.info("albumRename failed with error: " + err);
});
}
```
......@@ -38,7 +38,7 @@ The following describes how to obtain the public directory that stores camera fi
```ts
async function example(){
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') {
......@@ -69,7 +69,7 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o
**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.
3. Call **fileio.open** to open the file in the sandbox.
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
```ts
async function copyPublic2Sandbox() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir;
let fileKeyObj = mediaLibrary.FileKey
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
......@@ -108,7 +108,7 @@ async function copyPublic2Sandbox() {
```ts
async function copySandbox2Public() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
......@@ -120,26 +120,26 @@ async function copySandbox2Public() {
console.info('createFile failed, message = ' + err);
}
try {
let fileKeyObj = mediaLibrary.FileKey
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject();
} catch (err) {
console.info('file asset get failed, message = ', err)
console.info('file asset get failed, message = ' + err);
}
var fdPub = await fileAsset.open('rw');
var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2);
let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2);
await fileio.copyFile(fdSand, fdPub);
await fileio.close(fdPub);
await fileio.close(fdSand);
let fdPubRead = await fileAsset.open('rw');
try {
var arrayBuffer = new ArrayBuffer(4096);
let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer));
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead);
} catch (err) {
console.log('read text failed, message = ', err);
......@@ -167,12 +167,12 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
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){
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
```ts
async function writeOnlyPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
......@@ -218,8 +218,8 @@ async function writeOnlyPromise() {
```ts
async function readOnlyPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'],
......@@ -233,7 +233,7 @@ async function readOnlyPromise() {
let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent
globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent);
await fileAsset.close(fd);
......
......@@ -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).
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:
......@@ -43,7 +43,7 @@ An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrar
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
```
## Requesting Permissions
......@@ -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.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**.
......@@ -73,7 +73,7 @@ After configuring the permissions in the **module.json5** file, the application
"reason": "$string:reason",
"usedScene": {
"abilities": [
"MainAbility"
"EntryAbility"
],
"when": "always"
}
......@@ -83,7 +83,7 @@ After configuring the permissions in the **module.json5** file, the application
"reason": "$string:reason",
"usedScene": {
"abilities": [
"MainAbility"
"EntryAbility"
],
"when": "always"
}
......@@ -93,7 +93,7 @@ After configuring the permissions in the **module.json5** file, the application
"reason": "$string:reason",
"usedScene": {
"abilities": [
"MainAbility"
"EntryAbility"
],
"when": "always"
}
......@@ -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
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) {
var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA']
var permissionRequestResult;
this.context.requestPermissionsFromUser(permissions,(err,result) => {
if(err){
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err));
}else{
} else {
permissionRequestResult=result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
}
......@@ -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
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -64,13 +64,13 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileKeyObj = mediaLibrary.FileKey;
let option = {
selections: fileKeyObj.DATE_ADDED + '= ?',
selectionArgs: ['2022-8-5'],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -92,15 +92,15 @@ To sort files in descending order by the date when they are added, set **order**
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -124,14 +124,14 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs: ['myAlbum'],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -189,7 +189,7 @@ Complete sample code:
```ts
async function getCameraImagePromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
......@@ -236,7 +236,7 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir
```ts
async function getFirstThumbnailPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
......@@ -280,7 +280,7 @@ async function example() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((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
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.FILE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
console.error('asset not exist')
return
console.error('asset not exist');
return;
}
// Void callback.
asset.trash(true).then(() => {
console.info("trash successfully");
}).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
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.FILE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
console.error('asset not exist')
return
console.error('asset not exist');
return;
}
asset.displayName = 'newImage.jpg';
// Void callback.
......@@ -380,6 +380,6 @@ async function example() {
return;
}
console.log('fileRename successful.');
})
});
}
```
......@@ -108,7 +108,7 @@
- [MissionListener](js-apis-inner-application-missionListener.md)
- [MissionParameter](js-apis-inner-application-missionParameter.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)
- [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md)
- [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)
......@@ -242,19 +242,19 @@
- [@ohos.net.webSocket](js-apis-webSocket.md)
- [@ohos.request](js-apis-request.md)
- Connectivity
- [@ohos.bluetooth](js-apis-bluetooth.md)
- [@ohos.connectedTag](js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md)
- [@ohos.nfc.controller](js-apis-nfcController.md)
- [@ohos.nfc.tag](js-apis-nfcTag.md)
- [@ohos.rpc](js-apis-rpc.md)
- [@ohos.bluetooth (Bluetooth)](js-apis-bluetooth.md)
- [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](js-apis-cardEmulation.md)
- [@ohos.nfc.controller (Standard NFC)](js-apis-nfcController.md)
- [@ohos.nfc.tag (Standard NFC Tags)](js-apis-nfcTag.md)
- [@ohos.rpc (RPC)](js-apis-rpc.md)
- [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md)
- [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md)
- [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md)
- [@ohos.wifiManagerExt (WLAN Extension)](js-apis-wifiManagerExt.md)
- [@ohos.wifi (To Be Deprecated)](js-apis-wifi.md)
- [@ohos.wifiext (To Be Deprecated)](js-apis-wifiext.md)
- tag
- [nfctech](js-apis-nfctech.md)
- [tagSession](js-apis-tagSession.md)
- [nfctech (Standard NFC Technologies)](js-apis-nfctech.md)
- [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md)
- Basic Features
- [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md)
......@@ -314,9 +314,9 @@
- [@ohos.usb](js-apis-usb.md)
- [@ohos.vibrator](js-apis-vibrator.md)
- Account Management
- [@ohos.account.appAccount](js-apis-appAccount.md)
- [@ohos.account.distributedAccount](js-apis-distributed-account.md)
- [@ohos.account.osAccount](js-apis-osAccount.md)
- [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md)
- [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md)
- [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
- Custom Management
- [@ohos.configPolicy](js-apis-configPolicy.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.
......@@ -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. |
| 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
......@@ -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. |
| 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
......
# @ohos.application.DataShareExtensionAbility
# @ohos.application.DataShareExtensionAbility (DataShare Extension Ability)
The **DataShareExtensionAbility** module provides data share services based on the Extension ability.
......@@ -22,7 +22,6 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili
The URIs are in the following format:
**Scheme://authority/path**
- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module.
- *authority*: [userinfo@]host[:port]
- *userinfo*: login information, which can be left unspecified.
......@@ -76,7 +75,8 @@ let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
onCreate(want, callback) {
rdb.getRdbStore(this.context, {
name: DB_NAME
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
console.log('getRdbStore done, data : ' + data);
rdbStore = data;
......
# @ohos.bluetooth
# @ohos.bluetooth (Bluetooth)
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).
......@@ -16,7 +16,11 @@ import cardEmulation from '@ohos.nfc.cardEmulation';
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|
| -------- | -------- | -------- |
......@@ -24,13 +28,28 @@ Enumerates the NFC card emulation types.
| UICC | 1 | Subscriber identity module (SIM) card emulation.|
| ESE | 2 | embedded Secure Element (eSE) emulation.|
## cardEmulation.isSupported
## CardType<sup>9+</sup>
Enumerates the types of services used by the card emulation application.
**System capability**: SystemCapability.Communication.NFC.CardEmulation
| Name| Value| Description|
| -------- | -------- | -------- |
| PAYMENT | "payment" | Payment type.|
| OTHER | "other" | Other types.|
## isSupported
isSupported(feature: number): boolean
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**
......@@ -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.|
## HceService<sup>8+</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.
## hasHceCapability<sup>9+</sup>
### 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
**System capability**: SystemCapability.Communication.NFC.Core
**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.
**Return value**
**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
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------- |
| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. |
| callback | AsyncCallback<number[]> | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.|
### 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
| ------- | -------- | ---- | ----------------------- |
| elementName | [ElementName](js-apis-bundleManager-elementName.md#elementname) | Yes| Application description, which consists of the bundle name and component name.|
| type | [CardType](#cardtype9) | Yes| Card emulation service type.|
**Parameters**
**Return value**
| Name | Type | Mandatory| 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**.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.|
**Example**
......@@ -118,23 +113,16 @@ if (!isHceSupported) {
return;
}
// The device supports HCE and transimits APDUs with the remote NFC reader.
var hceService = new cardEmulation.HceService();
hceService.startHCE([
"F0010203040506", "A0000000041010"
]);
hceService.on("hceCmd", (err, res) => {
if(err.data === 0) {
console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res));
hceService.sendResponse([0x00,0xa4,0x04,0x00,
0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44,
0x46,0x30,0x31,0x00]);
} else {
console.log('callback => Operation hceCmd failed. Cause: ' + err.data);
}
})
// Stop HCE when the application exits the NFC card emulation.
hceService.stopHCE();
var hasHceCap = cardEmulation.hasHceCapability();
if (!hasHceCap) {
console.log('this device hasHceCapability false, ignore it.');
return;
}
var elementName = {
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
};
var isDefaultService = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT);
console.log('is the app is default service for this card type: ' + isDefaultService);
```
# @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.
......@@ -129,7 +129,7 @@ Writes data to this active tag. This API uses a promise to return the result.
```js
import connectedTag from '@ohos.connectedTag';
var rawData = "010203"; // change it tobe correct.
var rawData = "010203"; // Set it as required.
connectedTag.writeNdefTag(rawData).then(() => {
console.log("connectedTag writeNdefTag Promise success.");
}).catch((err)=> {
......@@ -159,7 +159,7 @@ Writes data to this active tag. This API uses an asynchronous callback to return
```js
import connectedTag from '@ohos.connectedTag';
var rawData = "010203"; // change it tobe correct.
var rawData = "010203"; // Set it as required.
connectedTag.writeNdefTag(rawData, (err)=> {
if (err) {
console.log("connectedTag writeNdefTag AsyncCallback err: " + err);
......@@ -220,7 +220,7 @@ connectedTag.on("notify", (err, rfState)=> {
var initStatus = connectedTag.init();
console.log("connectedTag init status: " + initStatus);
// Add nfc connecected tag business oprations here...
// Add NFC connected tag business operations here.
// connectedTag.writeNdefTag(rawData)
// 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.
......@@ -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
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**
>
......
# 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.
> **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.
## **Modules to Import**
```
```js
import controller from '@ohos.nfc.controller';
```
......@@ -18,7 +18,7 @@ Enumerates the NFC states.
**System capability**: SystemCapability.Communication.NFC.Core
| Name| Default Value| Description|
| Name| Value| Description|
| -------- | -------- | -------- |
| STATE_OFF | 1 | NFC is closed (OFF).|
| STATE_TURNING_ON | 2 | NFC is turning on.|
......@@ -31,6 +31,10 @@ isNfcAvailable(): boolean
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
**Return value**
......@@ -46,6 +50,10 @@ openNfc(): boolean
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
**System capability**: SystemCapability.Communication.NFC.Core
......@@ -56,12 +64,34 @@ Opens NFC.
| -------- | -------- |
| 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
closeNfc(): boolean
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
**System capability**: SystemCapability.Communication.NFC.Core
......@@ -72,6 +102,24 @@ Closes NFC.
| -------- | ------------------------------------------- |
| 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
isNfcOpen(): boolean
......@@ -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
**Parameter**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| 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.|
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| 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.|
## controller.off('nfcStateChange')
......@@ -125,42 +171,55 @@ Unsubscribes from the NFC state changes. The subscriber will not receive NFC sta
**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**.|
| callback | Callback&lt;[NfcState](#nfcstate)&gt; | No| Callback for the NFC state changes. This parameter can be left blank.|
**Example**
```js
import controller from '@ohos.nfc.controller';
// Define a callback key.
var NFC_STATE_CALLBACK_KEY = "nfcStateChange";
```js
import controller from '@ohos.nfc.controller';
// Register the callback to receive NFC state change notifications.
controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> {
// Register a callback to receive the NFC state change notification.
controller.on("nfcStateChange", (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()) {
// Open NFC. The ohos.permission.MANAGE_SECURE_SETTINGS permission is required.
if (!controller.isNfcOpen()) {
var ret = controller.openNfc();
console.log("controller openNfc ret: " + ret);
}
// Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS.
if (controller.isNfcOpen()) {
}
// 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);
}
// Unregister the callback.
controller.off(NFC_STATE_CALLBACK_KEY);
```
}
// 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");
```
# nfctech
# nfctech (Standard 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
Obtains the SAK value of this NFC-A tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -52,9 +50,7 @@ getAtqa(): number[]
Obtains the ATQA value of this NFC-A tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -86,9 +82,7 @@ getRespAppData(): number[]
Obtains the application data of this NFC-B tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -112,9 +106,7 @@ getRespProtocol(): number[]
Obtains the protocol information of this NFC-B tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -146,9 +138,7 @@ getSystemCode(): number[]
Obtains the system code from this NFC-F tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -172,9 +162,7 @@ getPmm(): number[]
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.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -206,9 +194,7 @@ getResponseFlags(): number
Obtains the response flags from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -232,9 +218,7 @@ getDsfId(): number
Obtains the data storage format identifier (DSFID) from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -316,7 +300,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -367,7 +351,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -419,7 +403,7 @@ getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[]
Obtains all NDEF records.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -454,7 +438,7 @@ getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)
Obtains the NDEF tag type.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -478,7 +462,7 @@ getNdefMessage(): [NdefMessage](#ndefmessage9)
Obtains the NDEF message from this NDEF tag.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -577,7 +561,7 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -738,7 +722,7 @@ Checks whether this NDEF tag can be set to read-only.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Error codes**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| 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**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1243,7 +1227,7 @@ Increments a block with data. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1296,7 +1280,7 @@ Increments a block with data. This API uses an asynchronous callback to return t
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1352,7 +1336,7 @@ Decrements a block. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1405,7 +1389,7 @@ Decrements a block. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1512,7 +1496,7 @@ Transfers data from the temporary register to a block. This API uses an asynchro
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1617,7 +1601,7 @@ Restores data in the temporary register from a block. This API uses an asynchron
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1669,7 +1653,7 @@ getSectorCount(): number
Obtains the number of sectors in this MIFARE Classic tag.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -1693,7 +1677,7 @@ getBlockCountInSector(sectorIndex: number): number
Obtains the number of blocks in a sector.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1729,7 +1713,7 @@ getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9)
Obtains the type of this MIFARE Classic tag.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -1753,7 +1737,7 @@ getTagSize(): number
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**
......@@ -1777,7 +1761,7 @@ isEmulatedTag(): boolean
Checks whether it is an emulated tag.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -1801,7 +1785,7 @@ getBlockIndex(sectorIndex: number): number
Obtains the index of the first block in a sector.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -1835,9 +1819,9 @@ try {
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**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -2102,7 +2086,7 @@ getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)
Obtains the type of this MIFARE Ultralight tag.
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**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.
......@@ -155,7 +155,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous
| 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**
......@@ -192,7 +192,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
| 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**
......@@ -483,7 +483,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous
| 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**
......@@ -1690,7 +1690,7 @@ Creates an OS account and associates it with the specified domain account. This
| 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**
......@@ -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));
}
```
### isMultiOsAccountEnable<sup>(deprecated)</sup>
isMultiOsAccountEnable(callback: AsyncCallback&lt;boolean&gt;): void
......@@ -2725,7 +2726,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous
| 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**
......@@ -2756,7 +2757,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
| 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**
......@@ -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;
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**
>
......@@ -4360,7 +4361,7 @@ Register a credential inputer.
let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]);
try {
InputerMgr.registerInputer(authType, {
inputerMgr.registerInputer(authType, {
onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password);
}
......
# tagSession
# tagSession (Standard NFC Tag Session)
The **tagSession** module provides common APIs for establishing connections and transferring data.
......@@ -26,9 +26,12 @@ getTagInfo(): tag.TagInfo
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -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.
> **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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -76,15 +82,52 @@ let connectStatus = tag.getIsoDep(tagInfo).connectTag();
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()
reset(): void
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Example**
......@@ -97,15 +140,52 @@ import tag from '@ohos.nfc.tag';
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
isTagConnected(): boolean
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -125,15 +205,50 @@ let isTagConnected = tag.getIsoDep(tagInfo).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
getMaxSendLength(): number
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -152,15 +267,57 @@ let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength();
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
getSendDataTimeout(): number
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
......@@ -180,15 +337,58 @@ let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout();
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
setSendDataTimeout(timeout: number): boolean
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -215,15 +415,59 @@ let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs);
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
sendData(data: number[]): Promise<number[]>
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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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.
> **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
**System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
......@@ -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
**Example**
```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);
let mgr = userFileManager.getUserFileMgr(context);
```
......@@ -127,7 +128,7 @@ async function example() {
predicates: predicates
};
try {
var fetchResult = await mgr.getPhotoAssets(fetchOptions);
let fetchResult = await mgr.getPhotoAssets(fetchOptions);
if (fetchResult != undefined) {
console.info('fetchResult success');
let fileAsset = await fetchResult.getFirstObject();
......@@ -410,7 +411,7 @@ Obtains the system album. This API uses a promise to return the result.
async function example() {
console.info('getPrivateAlbumDemo');
try {
var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let trashAlbum = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + trashAlbum.albumName);
} catch (err) {
......
......@@ -179,7 +179,7 @@ try {
case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
// Do something;
case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
// Do something;
// Do something.
default:
// Do others.
}
......
......@@ -263,7 +263,7 @@ Represents the WLAN configuration.
## IpType<sup>7+</sup>
Enumerate the IP address types.
Enumerates the IP address types.
**System API**: This is a system API.
......
# 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**
......@@ -1038,7 +1037,7 @@ Removes the specified network configuration.
| **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**
......@@ -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
......
# WLAN Extension Interface
This **wifiext** module provides WLAN extension interfaces for non-universal products.
> **NOTE**
......@@ -26,9 +25,9 @@ Enables the WLAN hotspot.
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.disableHotspot
......@@ -43,9 +42,9 @@ Disables the WLAN hotspot.
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.getSupportedPowerModel
......@@ -60,9 +59,9 @@ Obtains the supported power models. This API uses a promise to return the result
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
## PowerModel
......@@ -90,9 +89,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re
**Parameters**
| 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.|
| 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.|
## wifiext.getPowerModel
......@@ -107,9 +106,9 @@ Obtains the power model. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
## wifiext.getPowerModel
......@@ -124,16 +123,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re
**Parameters**
| 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.|
| 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.|
## wifiext.setPowerModel
setPowerModel(model: PowerModel) : boolean;
Sets the power model.
Sets the power model.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
......@@ -141,12 +140,12 @@ setPowerModel(model: PowerModel) : boolean;
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| 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.
......@@ -26,9 +26,9 @@ Enables the WLAN hotspot.
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.disableHotspot
......@@ -43,9 +43,9 @@ Disables the WLAN hotspot.
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.getSupportedPowerModel
......@@ -60,9 +60,9 @@ Obtains the supported power models. This API uses a promise to return the result
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
## PowerModel
......@@ -90,9 +90,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re
**Parameters**
| 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.|
| 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.|
## wifiext.getPowerModel
......@@ -107,9 +107,9 @@ Obtains the power model. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
## wifiext.getPowerModel
......@@ -124,16 +124,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re
**Parameters**
| 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.|
| 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.|
## wifiext.setPowerModel
setPowerModel(model: PowerModel) : boolean;
Sets the power model.
Sets the power model.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
......@@ -141,12 +141,12 @@ setPowerModel(model: PowerModel) : boolean;
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
......@@ -4,7 +4,7 @@
**Error Message**
NFC opening or closing state is abnormal in service.
NFC state is abnormal in service.
**Description**
......@@ -12,11 +12,13 @@ The NFC service fails to enable or disable NFC.
**Possible Causes**
Communication with the NFC service failed.
1. Communication with the NFC service failed.
2. The NFC chip communication is abnormal.
**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
......
......@@ -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).
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.
3. Pass in the key alias and key parameter set to generate a key.
> **NOTE**
>
> The key alias cannot exceed 64 bytes.
......@@ -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)
......@@ -225,9 +229,9 @@ You need to use the APIs for generating a key, exporting a public key, importing
| API | Description |
| -------------------------------------- | ----------------------------|
|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.|
|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.|
|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.|
|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.
......@@ -2081,55 +2085,57 @@ If secondary user identity authentication is enabled for a key, initialize the k
| Name | Value | Description |
| ------------------------------- |---|------------------------ |
| HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication. |
| HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication. |
| HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication. |
| HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication.|
| HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication. |
> **NOTE**
>
> 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 |
| --------------------------------------- | ----- | ------------------------------------------------------------ |
| 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. |
| | | |
| Name | Value | Description |
| --------------------------------------- | ---- | ------------------------------------------------ |
| 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.|
> **NOTE**
> **NOTE**
>
> **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 |
| ------------------------------- | ---- | ------------------------------ |
| 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_NONE | 2 | No challenge is required during user authentication.|
| 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_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.|
> **NOTICE**
>
> 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.
> **NOTICE**
>
> 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.
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.|
| 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**
1. Generate a key and specify user authentication attributes.
```ts
import huks from '@ohos.security.huks';
......
......@@ -76,7 +76,7 @@ Allows an application to read telephony information.
## ohos.permission.REQUIRE_FORM
Allows an application to obtain widgets.
Allows an application to obtain the Ability Form.
**Permission level**: system_basic
......@@ -166,7 +166,7 @@ Allows an application to set the system time zone.
## ohos.permission.DOWNLOAD_SESSION_MANAGER
Allows an application to manage download sessions.
Allows an application to manage the download sessions.
**Permission level**: system_core
......@@ -436,7 +436,7 @@ Allows an application to obtain the sensitive permissions that have been granted
## 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
......@@ -606,7 +606,7 @@ Allows an application to use agent-powered reminders.
## 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
......@@ -924,6 +924,16 @@ Allows the device administrator application to obtain device information.
**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
Allows an application to read NFC tag information.
......@@ -1156,7 +1166,7 @@ Allows an application to obtain the approximate location information of a device
## 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
......@@ -1603,3 +1613,13 @@ Allows an application to publish system common events.
**Authorization mode**: system_grant
**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
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
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
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
- OpenHarmony only supports facial recognition and local authentication, and does not support an authentication UI.
- To use biometric recognition, a device must have a camera with a face image pixel greater than 100x100.
- The device must have a TEE, where encrypted facial characteristics are 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.
- Only facial and fingerprint recognition is currently available and can only be executed on a local device. Moreover, no authentication UI is provided.
- 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 biometrics information is stored.
- 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 @@
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
......@@ -21,7 +21,7 @@ The identity authentication consists of User_auth and basic authentication servi
- 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
......@@ -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.
- 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
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
### 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
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| ----------------------------------- | ---------------------------------- |
| 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.|
| 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.|
| 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. |
| 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. |
| Cancel(uint64_t scheduleId) | Cancels a face enrolling, authentication, or identification operation based on the **scheduleId**. |
| Delete(const std::vector<uint64_t>& templateIdList) | Deletes a face image. |
| 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. |
**Table 2** Callbacks
......@@ -103,11 +123,11 @@ The following uses the Hi3516D V300 development board as an example to demonstra
```undefined
// drivers/peripheral/face_auth
├── BUILD.gn # Build script
├── bundle.json # Module description file
├── bundle.json # Component description file
└── hdi_service # Face_auth driver implementation
├── BUILD.gn # Build script
├── include # Header files
└── src
└── src # Source files
├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── face_auth_interface_driver.cpp # Face_auth driver entry
└── face_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list
......@@ -214,7 +234,7 @@ The development procedure is as follows:
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++
// Executor implementation class
......@@ -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++
// Obtain the executor information.
......@@ -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:
```js
// API version 8
import userIAM_userAuth from '@ohos.userIAM.userAuth';
let auth = new userIAM_userAuth.UserAuth();
export default {
getVersion() {
console.info("start to get version");
let version = this.auth.getVersion();
console.info("auth version = " + version);
},
startAuth() {
console.info("start auth");
this.auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
```js
// API version 9
import userIAM_userAuth from '@ohos.userIAM.userAuth';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
// Obtain an authentication object.
let auth;
try {
console.info("auth onResult result = " + result);
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
if (result == userIAM_userAuth.ResultCode.SUCCESS) {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
console.log("get auth instance success");
} catch (error) {
console.log("get auth instance failed" + error);
}
} catch (e) {
console.info("auth onResult error = " + e);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
// Subscribe to the authentication result.
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);
}
auth.on("result", {
callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.log("authV9 result " + result.result);
console.log("authV9 token " + result.token);
console.log("authV9 remainAttempts " + result.remainAttempts);
console.log("authV9 lockoutDuration " + result.lockoutDuration);
}
});
},
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);
},
console.log("subscribe authentication event success");
} catch (error) {
console.log("subscribe authentication event failed " + error);
}
onAcquireInfo: (module, acquire, extraInfo) => {
console.info("auth onAcquireInfo module = " + module);
// Start user authentication.
try {
auth.start();
console.info("authV9 start auth success");
} catch (error) {
console.info("authV9 start auth failed, error = " + error);
}
});
let cancelCode = this.auth.cancel(contextId);
if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) {
// Cancel the authentication.
try {
auth.cancel();
console.info("Authentication canceled successfully");
} else {
console.error("failed to cancel authentication");
} 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
- 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
......@@ -53,23 +53,23 @@ The identity authentication consists of the User_auth framework and basic authen
- 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
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
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.
**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
### 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
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| -------------------------------- | ----------------------------------- |
| 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.|
| 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.|
| Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Enrolls 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 template. |
| Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Identifies a fingerprint template. |
| Delete(const std::vector<uint64_t>& templateIdList) | Deletes a fingerprint template. |
| Cancel(uint64_t scheduleId) | Cancels a fingerprint enrolling, authentication, or identification operation based on the **scheduleId**. |
| 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. |
| 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. |
| 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. |
**Table 2** Callbacks
......@@ -117,11 +120,11 @@ The following uses the Hi3516D V300 development board as an example to demonstra
```undefined
// drivers/peripheral/fingerprint_auth
├── BUILD.gn # Build script
├── bundle.json # Module description file
├── bundle.json # Component description file
└── hdi_service # Fingerprint_auth driver implementation
├── BUILD.gn # Build script
├── include # Header files
└── src
└── src # Source files
├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── fingerprint_auth_interface_driver.cpp # Fingerprint_auth driver entry
└── fingerprint_auth_interface_service.cpp # Implementation of the API for obtaining the executor list
......@@ -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++
// Obtain the executor information.
......@@ -364,7 +367,7 @@ The development procedure is as follows:
return HDF_SUCCESS;
}
// Delete a fingerprint template.
// Delete fingerprints.
int32_t Delete(const std::vector<uint64_t>& templateIdList)
{
IAM_LOGI("interface mock start");
......@@ -435,50 +438,61 @@ The development procedure is as follows:
### 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
import userIAM_userAuth from '@ohos.userIAM.userAuth';
```js
// API version 8
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]);
let authType = userIAM_userAuth.UserAuthType.FINGERPRINT;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
export default {
getVersion() {
console.info("start to get version");
let version = this.auth.getVersion();
console.info("auth version = " + version);
},
// Obtain an authentication object.
let auth;
try {
auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
console.log("get auth instance success");
} catch (error) {
console.log("get auth instance failed" + error);
}
startAuth() {
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, {
onResult: (result, extraInfo) => {
// Subscribe to the authentication result.
try {
console.info("auth onResult result = " + result);
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
if (result == userIAM_userAuth.ResultCode.SUCCESS) {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
auth.on("result", {
callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.log("authV9 result " + result.result);
console.log("authV9 token " + result.token);
console.log("authV9 remainAttempts " + result.remainAttempts);
console.log("authV9 lockoutDuration " + result.lockoutDuration);
}
} catch (e) {
console.info("auth onResult error = " + e);
});
console.log("subscribe authentication event success");
} catch (error) {
console.log("subscribe authentication event failed " + error);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
// Start user authentication.
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);
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
- 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
......@@ -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.
- 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
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
![image](figures/pin_auth_service_and_driver_interaction.png "interaction between the pin_auth service and driver")
### 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
### When to Use
......@@ -69,15 +82,18 @@ The Pin_auth driver provides basic PIN authentication capabilities for the User_
### 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
| 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. |
| 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.|
| 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. |
| 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. |
......@@ -93,14 +109,12 @@ The Pin_auth driver provides basic PIN authentication capabilities for the User_
### How to Develop
The following uses the RK3568 platform as an example to demonstrate how to develop the Pin_auth driver.
The directory structure is as follows:
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:
```text
// drivers/peripheral/pin_auth
├── BUILD.gn # Build script
├── bundle.json # Module description file
├── bundle.json # Component description file
├── test # Test cases
└── hdi_service # Pin_auth driver implementation
├── BUILD.gn # Build script
......@@ -110,7 +124,7 @@ The directory structure is as follows:
├── main # Entry for implementing PIN-related functions
└── service # Entry for implementing the Pin_auth driver
├── inc # Header files
└── src
└── src # Source files
├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── pin_auth_interface_driver.cpp # Pin_auth driver entry
└── pin_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list
......@@ -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++
// Obtain executor information (example only).
......
......@@ -21,7 +21,7 @@ The identity authentication consists of the User_auth framework and basic authen
- 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
......@@ -29,11 +29,11 @@ The identity authentication consists of the User_auth framework and basic authen
- 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
......@@ -41,7 +41,7 @@ The identity authentication consists of the User_auth framework and basic authen
- 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
......@@ -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.
- 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
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,10 +109,13 @@ The User_auth driver provides stable user credential management, authentication
### 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
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| --------------------------- | --------------------------- |
| 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. |
| DeleteExecutor(uint64_t index) | Deletes an executor. |
......@@ -130,7 +145,7 @@ The following uses the Hi3516D V300 development board as an example to demonstra
```undefined
// drivers/peripheral/user_auth
├── BUILD.gn # Build script
├── bundle.json # Module description file
├── bundle.json # Component description file
└── hdi_service # User_auth driver implementation
├── BUILD.gn # Build script
├── module # Implementation of functionalities
......@@ -397,7 +412,7 @@ The development procedure is as follows:
{
IAM_LOGI("start");
if (param.challenge.size() != sizeof(uint64_t)) {
IAM_LOGE("challenge copy failed");
IAM_LOGE("Failed to copy the challenge");
return RESULT_BAD_PARAM;
}
GlobalLock();
......@@ -410,7 +425,7 @@ The development procedure is as follows:
solutionIn.authTrustLevel = param.authTrustLevel;
if (memcpy_s(&solutionIn.challenge, sizeof(uint64_t), &param.challenge[0],
param.challenge.size()) != EOK) {
IAM_LOGE("challenge copy failed");
IAM_LOGE("Failed to copy the challenge");
GlobalUnLock();
return RESULT_BAD_COPY;
}
......@@ -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:
```js
// API version 8
import userIAM_userAuth from '@ohos.userIAM.userAuth';
let auth = new userIAM_userAuth.UserAuth();
export default {
getVersion() {
console.info("start get version");
let version = this.auth.getVersion();
console.info("auth version = " + version);
},
startAuth() {
console.info("start auth");
this.auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
```js
// API version 9
import userIAM_userAuth from '@ohos.userIAM.userAuth';
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let authType = userIAM_userAuth.UserAuthType.FACE;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
// Obtain an authentication object.
let auth;
try {
console.info("auth onResult result = " + result);
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
if (result == 'SUCCESS') {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
}
} catch (e) {
console.info("auth onResult error = " + e);
auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
console.log("get auth instance success");
} catch (error) {
console.log("get auth instance failed" + error);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
// Subscribe to the authentication result.
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);
}
auth.on("result", {
callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.log("authV9 result " + result.result);
console.log("authV9 token " + result.token);
console.log("authV9 remainAttempts " + result.remainAttempts);
console.log("authV9 lockoutDuration " + result.lockoutDuration);
}
});
},
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);
},
console.log("subscribe authentication event success");
} catch (error) {
console.log("subscribe authentication event failed " + error);
}
onAcquireInfo: (module, acquire, extraInfo) => {
console.info("auth onAcquireInfo module = " + module);
// Start user authentication.
try {
auth.start();
console.info("authV9 start auth success");
} catch (error) {
console.info("authV9 start auth failed, error = " + error);
}
});
let cancelCode = this.auth.cancel(contextId);
if (cancelCode == userIAM_userAuth.Result.SUCCESS) {
// Cancel the authentication.
try {
auth.cancel();
console.info("Authentication canceled successfully");
} else {
console.error("Failed to cancel authentication");
} 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 @@
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
......@@ -15,24 +15,21 @@ General application privileges are privileges available to applications on all t
| Privilege| Description |
| ---------------- | ------------------------------------------------------------ |
| 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.|
| AllowAbilityPriorityQueried | Allows an ability to configure and query the priority. |
| 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.
2. Use the signing tool hapsigner to sign the HarmonyAppProvision file and generate a **.p7b** file.
3. Use the **.p7b** file to sign the HAP.
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 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.
Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#README.md)
### Example
```
```json
{
"version-name": "1.0.0",
...
......@@ -41,12 +38,10 @@ Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#READ
...
},
"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
### Introduction
......@@ -55,43 +50,55 @@ In addition to general application privileges, device vendors can define device-
| Privilege | Type | Default Value| Description |
| --------------------- | -------- | ------ | ------------------------------------------------- |
| removable | bool | true | Allows the application to be uninstalled. This privilege takes effect only for preset applications. |
| keepAlive | bool | false | Allows the application to keep running in the background. |
| singleton | bool | false | Allows the application to be installed for a single user (U0). |
| allowCommonEvent | string[] | - | Allows the 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. |
| runningResourcesApply | bool | false | Allows the application to request running resources, such as the CPU, event notifications, and Bluetooth.|
### Configuration
Configure the required privileges in [configuration files](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568/preinstall-config).
| removable | bool | true | Allows an application to be uninstalled. This privilege takes effect only for preset applications. |
| keepAlive | bool | false | Allows an application to keep running in the background. |
| singleton | bool | false | Allows an application to be installed for a single user (User 0). |
| allowCommonEvent | string[] | - | Allows an application to be started by a static broadcast. |
| associatedWakeUp | bool | false | Allows an application in the FA model to be woken up by an associated application. |
| 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.|
| 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.|
| 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
#### Configuration in **install_list_capability.json**
#### Configuration in install_list_capability.json
```
```json
{
"install_list": [
{
"bundleName": "com.example.kikakeyboard",
"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.
"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"]
"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**
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.
Example:
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.
```
```json
{
...
"bundle-info": {
......@@ -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.
Example:
```
-----BEGIN CERTIFICATE-----
MIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO
......@@ -125,30 +127,28 @@ Configure the required privileges in [configuration files](https://gitee.com/ope
-----END CERTIFICATE-----
```
3. Use keytool to run the following command to obtain the certificate fingerprint.
> **NOTE**<br>You can obtain keytool from the **\tools\openjdk\bin** directory after DevEco Studio is installed.
3. Use keytool to print the certificate fingerprint.
Example:
```
```shell
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" : [
{
......
......@@ -14,21 +14,12 @@ The table below describes the APIs for creating and deleting an RDB store.
| 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.|
| 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 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 | 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
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
- **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**.
**Table 3** APIs for setting RDB predicates
**Table 2** APIs for setting RDB predicates
| 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.|
......@@ -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.|
### Managing Data in an RDB Store
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
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|
| ---- | ---- | ---- |
......@@ -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.
**Table 5** API for deleting data
**Table 4** API for deleting data
| 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. |
......@@ -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.
**Table 6** API for updating data
**Table 5** API for updating data
| 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. |
......@@ -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.
- Run the native SQL statement.
**Table 7** APIs for querying data
**Table 6** APIs for querying data
| 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. |
......@@ -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**.
**Table 8** APIs of **ResultSet**
**Table 7** APIs of **ResultSet**
| Class| API| Description|
| ---- | ---- | ---- |
| 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
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|
| ---- | ---- | ---- |
| 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
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|
| ---- | ---- | ---- |
| 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
**Table 11** API for synchronizing data between devices
**Table 10** API for synchronizing data between devices
| 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. |
### Registering an RDB Store Observer
**Table 12** API for registering an observer
**Table 11** API for registering an observer
| 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. |
### Unregistering an RDB Store Observer
**Table 13** API for unregistering an observer
**Table 12** API for unregistering an observer
| 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. |
......@@ -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.
Table 14 API for backing up an RDB store
**Table 13** API for backing up an RDB store
| Class| API| Description|
| ---- | ---- | ---- |
......@@ -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.
Table 15 API for restoring an RDB store
**Table 14** API for restoring an RDB store
| Class| API| Description|
| ---- | ---- | ---- |
......@@ -181,15 +173,15 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab
### 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|
| ---- | ---- | ---- |
| RdbStore | int BeginTransaction() | Starts a transaction.|
| RdbStore | int Commit() | Commits the changes.|
| RdbStore | int RollBack() | Rolls back the changes.|
| Class| API| Description|
| ---- | ---- | ---- |
| RdbStore | int BeginTransaction() | Starts a transaction.|
| RdbStore | int Commit() | Commits the changes.|
| RdbStore | int RollBack() | Rolls back the changes.|
## Constraints
......
......@@ -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.
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)
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.
- 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.
The user IAM subsystem consists of the unified user authentication framework and authentication executor. The unified user authentication framework consists of the following:
- 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.
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**
>
>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
```undefined
//base/user_iam
├── 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
├── pin_auth # Password authentication module, which connects to the authentication executor management part and supports password recording, deletion, and verification
//base/useriam
├── user_auth_framework # User authentication framework, including user authentication, credential management, and executor management.
├── face_auth # Facial authentication component, which interacts with the authentication executor to implement facial information enrollment, deletion, and authentication.
├── pin_auth # PIN authentication component, which interacts with the authentication executor to implement PIN enrollment, deletion, and authentication.
```
## 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.
- 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.
- 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. Therefore, only system services can interact with the authentication executor management module to implement the executor functions.
## Usage
### How to Use
1. 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.
- The unified user authentication framework must work with an authentication executor.
- By default, the first authentication executor in the system is the PIN authentication executor.
## Repositories Involved
......
# 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 {
2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
类型定义中的Length、Resource、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。
Length、Resource、ResourceColor的定义请看文档[arkui-ts类型定义](../../application-dev/reference/arkui-ts/ts-types.md)。
类型定义中的Length、ResourceStr、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。
Length、ResourceStr、ResourceColor的定义请看文档[arkui-ts类型定义](../../application-dev/reference/arkui-ts/ts-types.md)。
示例:
......
......@@ -3,7 +3,7 @@
> **说明:**
>
> - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口从API9开始废弃。不建议使用以下接口,调用以下接口将抛出异常。
> - 本模块接口从API version 9开始废弃。不建议使用以下接口,调用以下接口将抛出异常。
## 导入模块
......
......@@ -3,8 +3,8 @@
该模块提供文件存储管理能力,包括文件基本管理、文件目录管理、文件信息统计、文件流式读写等常用功能。
> **说明:**
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块自API 9开始废弃,建议使用[@ohos.file.fs](./js-apis-file-fs.md)替代。
> - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块从API version 9开始废弃,建议使用[@ohos.file.fs](js-apis-file-fs.md)替代。
## 导入模块
......
......@@ -22,7 +22,7 @@ Context模块提供了ability或application的上下文的能力,包括访问
| preferencesDir | string | 是 | 否 | preferences目录。 |
| bundleCodeDir | string | 是 | 否 | 安装包目录。 |
| distributedFilesDir | string | 是 | 否 | 分布式文件目录。 |
| eventHub | string | 是 | 否 | 事件中心,提供订阅、取消订阅、触发事件对象。 |
| eventHub | [EventHub](js-apis-inner-application-eventHub.md) | 是 | 否 | 事件中心,提供订阅、取消订阅、触发事件对象。 |
| area | [AreaMode](#areamode) | 是 | 否 | 文件分区信息。 |
## Context.createBundleContext
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册