diff --git a/README_zh.md b/README_zh.md index 386fa1d7449553f92f399839d947a0dacd4e18b8..6e71a0abd9fba5cbe4b4de47c77437d3a851aa45 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,7 +18,7 @@ - master:最新开发版本。 - - OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。 + - OpenHarmony 3.2 Beta5版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta5.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 654f099dad350ce1158c2bfd3f5b01b39d781d4b..a43407aa5643f6a7d0265ca88c6234120e904d72 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -34,11 +34,9 @@ There are two roles in **DataShare**: - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data consumer: accesses the data provided by the provider using **DataShareHelper**. -Examples are given below. - ### Data Provider Application Development (Only for System Applications) -[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override the APIs as required. +[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required. - **onCreate** @@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ```ts import Extension from '@ohos.application.DataShareExtensionAbility'; - import rdb from '@ohos.data.rdb'; + import rdb from '@ohos.data.relationalStore'; import fileIo from '@ohos.fileio'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -4. Override the **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. +5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. -5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. +6. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. ```ts const DB_NAME = "DB00.db"; @@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + TBL_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; - + let rdbStore; let result; - + export default class DataShareExtAbility extends Extension { private rdbStore_; - + // Override onCreate(). onCreate(want, callback) { - result = this.context.cacheDir + '/datashare.txt' + result = this.context.cacheDir + '/datashare.txt'; // Create an RDB store. - rdb.getRdbStore(this.context, { - name: DB_NAME - }, 1, function (err, data) { - rdbStore = data; - rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { - console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); + rdb.getRdbStore(this.context, { + name: DB_NAME, + securityLevel: rdb.SecurityLevel.S1 + }, function (err, data) { + rdbStore = data; + rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { + console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); }); - callback(); + if (callbakc) { + callback(); + } }); } - + // Override query(). query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { @@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit }; ``` - - -6. Define **DataShareExtensionAbility** in **module.json5**. +7. Define **DataShareExtensionAbility** in **module.json5**. - | Field | Description | - | --------- | ------------------------------------------------------------ | - | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | - | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | - | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | - | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | - | | | + | Field| Description | + | ------------ | ------------------------------------------------------------ | + | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | + | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| + | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | + | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| **module.json5 example** @@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ] ``` - - ### Data Consumer Application Development 1. Import dependencies. @@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; let predicates = new dataSharePredicates.DataSharePredicates(); - let valArray = new Array("*"); + let valArray = ['*']; // Insert a piece of data. dsHelper.insert(dseUri, valuesBucket, (err, data) => { console.log("dsHelper insert result: " + data); diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index df633d8449281b12557bb3d39f333f97148af1a4..4d54d3de270712d876971053eebbce8665561ec9 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** @@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local ### Transaction -Table 15 Transaction APIs +**Table 15** Transaction APIs | Class | API | Description | | -------- | ----------------------- | --------------------------------- | @@ -202,44 +202,82 @@ Table 15 Transaction APIs ```js import data_rdb from '@ohos.data.relationalStore' - // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' + + // Obtain the context. let context = featureAbility.getContext() - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 + } - const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} + // Assume that the current RDB store version is 3. data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - rdbStore.executeSql(CREATE_TABLE_TEST) - console.info('create table done.') + // When an RDB store is created, the default version is 0. + if (rdbStore.version == 0) { + rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) + // Set the RDB store version. The input parameter must be an integer greater than 0. + rdbStore.version = 3 + } + + // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. + if (rdbStore.version != 3 && rdbStore.version == 1) { + // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) + rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) + rdbStore.version = 2 + } + + // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. + if (rdbStore.version != 3 && rdbStore.version == 2) { + // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) + rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) + rdbStore.version = 3 + } }) ``` Stage model: ```ts import data_rdb from '@ohos.data.relationalStore' - // Obtain the context. - import UIAbility from '@ohos.app.ability.UIAbility'; - let context = null + import UIAbility from '@ohos.app.ability.UIAbility' + class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { - context = this.context + const STORE_CONFIG = { + name: "rdbstore.db", + securityLevel: data_rdb.SecurityLevel.S1 + } + + // Assume that the current RDB store version is 3. + data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + // When an RDB store is created, the default version is 0. + if (rdbStore.version == 0) { + rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) + // Set the RDB store version. The input parameter must be an integer greater than 0. + rdbStore.version = 3 + } + + // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. + if (rdbStore.version != 3 && rdbStore.version == 1) { + // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) + rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) + rdbStore.version = 2 + } + + // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. + if (rdbStore.version != 3 && rdbStore.version == 2) { + // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) + rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) + rdbStore.version = 3 + } + }) } } - - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - - const STORE_CONFIG = { name: "rdbstore.db", - securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - rdbStore.executeSql(CREATE_TABLE_TEST) - console.info('create table done.') - }) ``` 2. Insert data. - (1) Create a **ValuesBucket** to store the data you need to insert. + (1) Create a **ValuesBucket** instance to store the data you need to insert. (2) Call the **insert()** method to insert data into the RDB store. @@ -384,14 +422,13 @@ Table 15 Transaction APIs 8. Query data of a remote device. - (1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device. (2) Call the resultSet() API to obtain the result. The sample code is as follows: - - ```js + + ```js let rdbPredicate = new data_rdb.RdbPredicates('employee') predicates.greaterThan("id", 0) let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) @@ -406,31 +443,32 @@ Table 15 Transaction APIs }).catch((err) => { console.info("failed to remoteQuery, err: " + err) }) - ``` - + ``` + 9. Back up and restore an RDB store. (1) Back up the current RDB store. - The sample code is as follows: + The sample code is as follows: - ```js + ```js let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(() => { - console.info('Backup success.') + console.info('Backup success.') }).catch((err) => { - console.info('Backup failed, err: ' + err) + console.info('Backup failed, err: ' + err) }) - ``` - (2) Restore the RDB store using the backup file. + ``` - The sample code is as follows: + (2) Restore the RDB store using the backup file. - ```js + The sample code is as follows: + + ```js let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { - console.info('Restore success.') + console.info('Restore success.') }).catch((err) => { - console.info('Restore failed, err: ' + err) + console.info('Restore failed, err: ' + err) }) - ``` + ``` diff --git a/en/application-dev/file-management/filepicker-guidelines.md b/en/application-dev/file-management/filepicker-guidelines.md index 8fcf96b2219151a9c197cd1f6bc2e738775646b7..f320f89d82ed0683b0057264430ee090fdd02974 100644 --- a/en/application-dev/file-management/filepicker-guidelines.md +++ b/en/application-dev/file-management/filepicker-guidelines.md @@ -33,7 +33,7 @@ ArkTS sample code: globalThis.context.startAbilityForResult( { bundleName: "com.ohos.filepicker", - abilityName: "EntryAbility", + abilityName: "MainAbility", parameters: { 'startMode': 'choose', //choose or save } @@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult( { bundleName: "com.ohos.filepicker", - abilityName: "EntryAbility", + abilityName: "MainAbility", parameters: { 'startMode': 'save', //choose or save 'saveFile': 'test.jpg', diff --git a/en/application-dev/media/avplayer-playback.md b/en/application-dev/media/avplayer-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..270081373fb500877ca4352366982b66f72bc09a --- /dev/null +++ b/en/application-dev/media/avplayer-playback.md @@ -0,0 +1,507 @@ +# AVPlayer Development + +## Introduction + +The AVPlayer converts audio or video resources into audible analog signals or renderable images and plays the signals or images using output devices. You can manage playback tasks on the AVPlayer. For example, you can control the playback (start/pause/stop/seek), set the volume, obtain track information, and release resources. + +## Working Principles + +The following figures show the [AVPlayer state](../reference/apis/js-apis-media.md#avplayerstate9) transition and interaction with external audio and video playback modules. + +**Figure 1** AVPlayer state transition + +![en-us_image_avplayer_state_machine](figures/en-us_image_avplayer_state_machine.png) + +**Figure 2** Interaction with external modules for audio playback + +![en-us_image_avplayer_audio](figures/en-us_image_avplayer_audio.png) + +**NOTE**: When an application calls the **AVPlayer** JS APIs at the JS interface layer to implement a feature, the framework layer parses the resources into audio data streams through the playback service of the player framework. The audio data streams are then decoded by software and output to the audio service of the audio framework. The audio framework outputs the audio data streams to the audio HDI at the hardware interface layer to implement audio playback. A complete audio playback process requires the cooperation of the application (application adaptation required), player framework, audio framework, and audio HDI (driver adaptation required). + +1. An application passes a URL into the **AVPlayer** JS API. +2. The playback service outputs the audio PCM data streams to the audio service, and the audio service outputs the data streams to the audio HDI. + + +**Figure 3** Interaction with external modules for video playback + +![en-us_image_avplayer_video](figures/en-us_image_avplayer_video.png) + +**NOTE**: When an application calls the **AVPlayer** JS APIs at the JS interface layer to implement a feature, the framework layer parses the resources into separate audio data streams and video data streams through the playback service of the player framework. The audio data streams are then decoded by software and output to the audio service of the audio framework. The audio framework outputs the audio data streams to the audio HDI at the hardware interface layer to implement audio playback. The video data streams are then decoded by hardware (recommended) or software and output to the renderer service of the graphic framework. The renderer service outputs the video data streams to the display HDI at the hardware interface layer. A complete video playback process requires the cooperation of the application (application adaptation required), XComponent, player framework, graphic framework, audio framework, display HDI (driver adaptation required), and audio HDI (driver adaptation required). + +1. An application obtains the surface ID from the XComponent. For details about the obtaining method, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md). +2. The application passes a URL and the surface ID into the **AVPlayer** JS API. +3. The playback service outputs video elementary streams (ESs) to the codec HDI, which decodes the ESs to obtain video frames (NV12/NV21/RGBA). +4. The playback service outputs the audio PCM data streams to the audio service, and the audio service outputs the data streams to the audio HDI. +5. The playback service outputs video frames (NV12/NV21/RGBA) to the renderer service, and the renderer service outputs the video frames to the display HDI. + +## Compatibility + +Use the mainstream playback formats and resolutions, rather than custom ones to avoid playback failures, frame freezing, and artifacts. The system will not be affected by incompatibility issues. If such an issue occurs, you can exit stream playback. + +The table below lists the mainstream playback formats and resolutions. + +| Video Container Format| Description | Resolution | +| :----------: | :-----------------------------------------------: | :--------------------------------: | +| mp4 | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| +| mkv | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| +| ts | Video format: H.264/MPEG-2/MPEG-4; audio format: AAC/MP3 | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| +| webm | Video format: VP8; audio format: VORBIS | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| + +| Audio Container Format | Description | +| :----------: | :----------: | +| m4a | Audio format: AAC| +| aac | Audio format: AAC| +| mp3 | Audio format: MP3| +| ogg | Audio format: VORBIS | +| wav | Audio format: PCM | + +## How to Develop + +For details about the APIs, see the [AVPlayer APIs in the Media Class](../reference/apis/js-apis-media.md#avplayer9). + +### Full-Process Scenario + +The full playback process includes creating an instance, setting resources, setting a video window, preparing for playback, controlling playback, and resetting or releasing the resources. (During the preparation, you can obtain track information, volume, speed, focus mode, and zoom mode, and set bit rates. To control the playback, you can start, pause, and stop the playback, seek to a playback position, and set the volume.) + +1. Call [createAVPlayer()](../reference/apis/js-apis-media.md#mediacreateavplayer9) to create an **AVPlayer** instance. The AVPlayer is initialized to the [idle](#avplayer_state) state. + +2. Set the events to listen for, which will be used in the full-process scenario. + +3. Set the resource [URL](../reference/apis/js-apis-media.md#avplayer_attributes). When the AVPlayer enters the [initialized](#avplayer_state) state, you can set the [surface ID](../reference/apis/js-apis-media.md#avplayer_attributes) for the video window. For details about the supported specifications, see [AVPlayer Attributes](../reference/apis/js-apis-media.md#avplayer_attributes). + +4. Call [prepare()](../reference/apis/js-apis-media.md#avplayer_prepare) to switch the AVPlayer to the [prepared](#avplayer_state) state. + +5. Perform video playback control. For example, you can call [play()](../reference/apis/js-apis-media.md#avplayer_play), [pause()](../reference/apis/js-apis-media.md#avplayer_pause), [seek()](../reference/apis/js-apis-media.md#avplayer_seek), and [stop()](../reference/apis/js-apis-media.md#avplayer_stop) to control the playback. + +6. Call [reset()](../reference/apis/js-apis-media.md#avplayer_reset) to reset resources. The AVPlayer enters the [idle](#avplayer_state) state again, and you can change the resource [URL](../reference/apis/js-apis-media.md#avplayer_attributes). + +7. Call [release()](../reference/apis/js-apis-media.md#avplayer_release) to release the instance. The AVPlayer enters the [released](#avplayer_state) state and exits the playback. + +> **NOTE** +> +> When the AVPlayer is in the prepared, playing, paused, or completed state, the playback engine is working and a large amount of system running memory is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the resources. + +### Listening Events + +| Event Type | Description | +| ------------------------------------------------- | ------------------------------------------------------------ | +| stateChange | Mandatory; used to listen for player state changes. | +| error | Mandatory; used to listen for player error information. | +| durationUpdate | Used to listen for progress bar updates to refresh the resource duration. | +| timeUpdate | Used to listen for the current position of the progress bar to refresh the current time. | +| seekDone | Used to listen for the completion status of the **seek()** request. | +| speedDone | Used to listen for the completion status of the **setSpeed()** request. | +| volumeChange | Used to listen for the completion status of the **setVolume()** request. | +| bitrateDone | Used to listen for the completion status of the **setBitrate()** request, which is used for HTTP Live Streaming (HLS) streams. | +| availableBitrates | Used to listen for available bit rates of HLS resources. The available bit rates are provided for **setBitrate()**. | +| bufferingUpdate | Used to listen for network playback buffer information. | +| startRenderFrame | Used to listen for the rendering time of the first frame during video playback. | +| videoSizeChange | Used to listen for the width and height of video playback and adjust the window size and ratio.| +| audioInterrupt | Used to listen for audio interruption during video playback. This event is used together with the **audioInterruptMode** attribute.| + +### Full-Process Scenario API Example + +```js +import media from '@ohos.multimedia.media' +import audio from '@ohos.multimedia.audio'; +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private count:number = 0 + private avPlayer + private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. + + // Set AVPlayer callback functions. + setAVPlayerCallback() { + // Callback function for state changes. + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // This state is reported upon a successful callback of reset(). + console.info(TAG + 'state idle called') + this.avPlayer.release() // Release the AVPlayer instance. + break; + case 'initialized': // This state is reported when the AVPlayer sets the playback source. + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played. + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // This state is reported upon a successful callback of prepare(). + console.info(TAG + 'state prepared called') + this.avPlayer.play() // Call play() to start playback. + break; + case 'playing': // This state is reported upon a successful callback of play(). + console.info(TAG + 'state playing called') + if (this.count == 0) { + this.avPlayer.pause() // Call pause() to pause the playback. + } else { + this.avPlayer.seek(10000, media.SeekMode.SEEK_PREV_SYNC) // Seek to 10 seconds. The seekDone callback is triggered. + } + break; + case 'paused': // This state is reported upon a successful callback of pause(). + console.info(TAG + 'state paused called') + if (this.count == 0) { + this.count++ + this.avPlayer.play() // Call play() to continue the playback. + } + break; + case 'completed': // This state is reported upon the completion of the playback. + console.info(TAG + 'state completed called') + this.avPlayer.stop() // Call stop() to stop the playback. + break; + case 'stopped': // This state is reported upon a successful callback of stop(). + console.info(TAG + 'state stopped called') + this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + // Callback function for time updates. + this.avPlayer.on('timeUpdate', (time:number) => { + console.info(TAG + 'timeUpdate success,and new time is :' + time) + }) + // Callback function for volume updates. + this.avPlayer.on('volumeChange', (vol:number) => { + console.info(TAG + 'volumeChange success,and new volume is :' + vol) + this.avPlayer.setSpeed(media.AVPlayerSpeed.SPEED_FORWARD_2_00_X) // Double the playback speed. The speedDone callback is triggered. + }) + // Callback function for the video playback completion event. + this.avPlayer.on('endOfStream', () => { + console.info(TAG + 'endOfStream success') + }) + // Callback function for the seek operation. + this.avPlayer.on('seekDone', (seekDoneTime:number) => { + console.info(TAG + 'seekDone success,and seek time is:' + seekDoneTime) + this.avPlayer.setVolume(0.5) // Set the volume to 0.5. The volumeChange callback is triggered. + }) + // Callback function for the speed setting operation. + this.avPlayer.on('speedDone', (speed:number) => { + console.info(TAG + 'speedDone success,and speed value is:' + speed) + }) + // Callback function for successful bit rate setting. + this.avPlayer.on('bitrateDone', (bitrate:number) => { + console.info(TAG + 'bitrateDone success,and bitrate value is:' + bitrate) + }) + // Callback function for buffering updates. + this.avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { + console.info(TAG + 'bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value) + }) + // Callback function invoked when frame rendering starts. + this.avPlayer.on('startRenderFrame', () => { + console.info(TAG + 'startRenderFrame success') + }) + // Callback function for video width and height changes. + this.avPlayer.on('videoSizeChange', (width: number, height: number) => { + console.info(TAG + 'videoSizeChange success,and width is:' + width + ', height is :' + height) + }) + // Callback function for the audio interruption event. + this.avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { + console.info(TAG + 'audioInterrupt success,and InterruptEvent info is:' + info) + }) + // Callback function to report the available bit rates of HLS. + this.avPlayer.on('availableBitrates', (bitrates: Array) => { + console.info(TAG + 'availableBitrates success,and availableBitrates length is:' + bitrates.length) + }) + } + + async avPlayerDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` + +### Normal Playback Scenario + +```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private avPlayer + private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. + + // Set AVPlayer callback functions. + setAVPlayerCallback() { + // Callback function for state changes. + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // This state is reported upon a successful callback of reset(). + console.info(TAG + 'state idle called') + break; + case 'initialized': // This state is reported when the AVPlayer sets the playback source. + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played. + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // This state is reported upon a successful callback of prepare(). + console.info(TAG + 'state prepared called') + this.avPlayer.play() // Call play() to start playback. + break; + case 'playing': // This state is reported upon a successful callback of play(). + console.info(TAG + 'state playing called') + break; + case 'paused': // This state is reported upon a successful callback of pause(). + console.info(TAG + 'state paused called') + break; + case 'completed': // This state is reported upon the completion of the playback. + console.info(TAG + 'state completed called') + this.avPlayer.stop() // Call stop() to stop the playback. + break; + case 'stopped': // This state is reported upon a successful callback of stop(). + console.info(TAG + 'state stopped called') + this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + } + + async avPlayerDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` + +### Switching to the Next Video Clip + +```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private count:number = 0 + private avPlayer + private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. + + // Set AVPlayer callback functions. + setAVPlayerCallback() { + // Callback function for state changes. + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // This state is reported upon a successful callback of reset(). + console.info(TAG + 'state idle called') + break; + case 'initialized': // This state is reported when the AVPlayer sets the playback source. + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played. + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // This state is reported upon a successful callback of prepare(). + console.info(TAG + 'state prepared called') + this.avPlayer.loop = true // Set the AVPlayer to loop a single item. The endOfStream callback is triggered when the previous round of the playback is complete. + this.avPlayer.play() // Call play() to start playback. + break; + case 'playing': // This state is reported upon a successful callback of play(). + console.info(TAG + 'state playing called') + break; + case 'paused': // This state is reported upon a successful callback of pause(). + console.info(TAG + 'state paused called') + break; + case 'completed': // This state is reported upon the completion of the playback. + console.info(TAG + 'state completed called') + // Cancel the loop playback when the endOfStream callback is triggered for the second time. The completed state is reported when the next round of the playback is complete. + this.avPlayer.stop() // Call stop() to stop the playback. + break; + case 'stopped': // This state is reported upon a successful callback of stop(). + console.info(TAG + 'state stopped called') + this.avPlayer.reset() // Call reset() to initialize the AVPlayer state. + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + // Callback function for the video playback completion event. + this.avPlayer.on('endOfStream', () => { + console.info(TAG + 'endOfStream success') + if (this.count == 1) { + this.avPlayer.loop = false // Cancel loop playback. + } else { + this.count++ + } + }) + } + + async avPlayerDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` +### Looping a Song + +```js +import media from '@ohos.multimedia.media' +import fileIO from '@ohos.fileio' + +const TAG = 'AVPlayerDemo:' +export class AVPlayerDemo { + private count:number = 0 + private avPlayer + private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. + + async nextVideo() { + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. + let path = pathDir + '/H264_MP3.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath // The initialized state is reported again. + } + + // Set AVPlayer callback functions. + setAVPlayerCallback() { + // Callback function for state changes. + this.avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': // This state is reported upon a successful callback of reset(). + console.info(TAG + 'state idle called') + await this.nextVideo() // Switch to the next video. + break; + case 'initialized': // This state is reported when the AVPlayer sets the playback source. + console.info(TAG + 'state initialized called ') + this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played. + this.avPlayer.prepare().then(() => { + console.info(TAG+ 'prepare success'); + }, (err) => { + console.error(TAG + 'prepare filed,error message is :' + err.message) + }) + break; + case 'prepared': // This state is reported upon a successful callback of prepare(). + console.info(TAG + 'state prepared called') + this.avPlayer.play() // Call play() to start playback. + break; + case 'playing': // This state is reported upon a successful callback of play(). + console.info(TAG + 'state playing called') + break; + case 'paused': // This state is reported upon a successful callback of pause(). + console.info(TAG + 'state paused called') + break; + case 'completed': // This state is reported upon the completion of the playback. + console.info(TAG + 'state completed called') + if (this.count == 0) { + this.count++ + this.avPlayer.reset() // Call reset() to prepare for switching to the next video. + } else { + this.avPlayer.release() // Release the AVPlayer instance when the new video finishes playing. + } + break; + case 'stopped': // This state is reported upon a successful callback of stop(). + console.info(TAG + 'state stopped called') + break; + case 'released': + console.info(TAG + 'state released called') + break; + case 'error': + console.info(TAG + 'state error called') + break; + default: + console.info(TAG + 'unkown state :' + state) + break; + } + }) + } + + async avPlayerDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer() + let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command. + let path = pathDir + '/H264_AAC.mp4' + await fileIO.open(path).then((fdNumber) => { + fdPath = fdPath + '' + fdNumber + console.info('open fd success fd is' + fdPath) + }, (err) => { + console.info('open fd failed err is' + err) + }).catch((err) => { + console.info('open fd failed err is' + err) + }); + this.avPlayer.url = fdPath + } +} +``` diff --git a/en/application-dev/media/avrecorder.md b/en/application-dev/media/avrecorder.md new file mode 100644 index 0000000000000000000000000000000000000000..b897c68a657f2891800e2f4d67fc60a1aec8eacf --- /dev/null +++ b/en/application-dev/media/avrecorder.md @@ -0,0 +1,488 @@ +# AVRecorder Development + +## Introduction + +The AVRecorder captures audio signals, receives video signals, encodes audio and video signals, and saves them to files. With the AVRecorder, you can easily implement audio and video recording, including starting, pausing, resuming, and stopping recording, and releasing resources. You can also specify parameters such as the encoding format, encapsulation format, and file path for recording. + +## Working Principles + +The following figures show the AVRecorder state transition and the interaction with external modules for audio and video recording. + +**Figure 1** AVRecorder state transition + +![en-us_image_video_recorder_state_machine](figures/en-us_image_avrecorder_state_machine.png) + +**Figure 2** Interaction between external modules for audio and video recording + +![en-us_image_video_recorder_zero](figures/en-us_image_avrecorder_module_interaction.png) + +**NOTE**: During audio recording, the framework layer calls the audio subsystem through the media service of the native framework to capture audio data through the audio HDI, encodes and encapsulates the data by using software, and saves the data to a file. During video recording, the camera subsystem captures image data through the video HDI. The media service encodes the image data through the video encoding HDI and encapsulates the encoded image data into a file. With the AVRecorder, you can implement pure audio recording, pure video recording, and audio and video recording. + +## Constraints + +Before developing the recording feature, configure permissions for your application. If audio recording is involved, obtain the permission **ohos.permission.MICROPHONE** by following the instructions provided in [Permission Application Guide](../security/accesstoken-guidelines.md). + +To use the camera to record videos, the camera module is required. For details about how to use the APIs and obtain permissions, see [Camera Management](../reference/apis/js-apis-camera.md). + +## How to Develop + +For details about the AVRecorder APIs, see the [AVRecorder APIs in the Media Class](../reference/apis/js-apis-media.md#avrecorder9). + +For details about the processes related to the media library, see [Media Library Management](../reference/apis/js-apis-medialibrary.md). + +For details about the camera-related process, see [Camera Management](../reference/apis/js-apis-camera.md). + +### Full-Process Scenario of Audio and Video Recording + +The full audio and video recording process includes creating an instance, setting recording parameters, obtaining the input surface, starting, pausing, resuming, and stopping recording, and releasing resources. + +The value range that can be set for the audio recording parameters is restricted by the codec performance of the device and the performance of the audio subsystem. + +The video range that can be set for the video recording parameters is restricted by the codec performance of the device and the performance of the camera subsystem. + +``` +import media from '@ohos.multimedia.media' +import camera from '@ohos.multimedia.camera' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +export class AVRecorderDemo { + private testFdNumber; // Used to save the File Descriptor (FD) address. + + // Obtain the FD corresponding to fileName of the recorded file. The media library capability is required. To use the media library, configure the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. + async getFd(fileName) { + // For details about the implementation mode, see the media library documentation. + this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54 + } + + // Error callback triggered in the case of an error in the promise mode. + failureCallback(error) { + console.info('error happened, error message is ' + error.message); + } + + // Error callback triggered in the case of an exception in the promise mode. + catchCallback(error) { + console.info('catch error happened, error message is ' + error.message); + } + + async AVRecorderDemo() { + let AVRecorder; // Assign a value to the empty AVRecorder instance upon a successful call of createAVRecorder(). + let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera. + await this.getFd('01.mp4'); + + // Configure the parameters related to audio and video recording. + let avProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 + } + let avConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : avProfile, + url : 'fd://', + rotation : 0, + location : { latitude : 30, longitude : 130 } + } + + // Create an AVRecorder instance. + await media.createAVRecorder().then((recorder) => { + console.info('case createAVRecorder called'); + if (typeof (recorder) != 'undefined') { + AVRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info('createAVRecorder failed'); + } + }, this.failureCallback).catch(this.catchCallback); + + // After the instance is created, use the on('stateChange') and on('error') callbacks to listen for state changes and errors. + AVRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state); + switch (state) { + // Your can set the desired behavior in different states as required. + case 'idle': + // This state is reported upon a successful call of rest() or create(). + break; + case 'prepared': + // This state is reported upon a successful call of prepare(). + break; + case 'started': + // This state is reported upon a successful call of start(). + break; + case 'paused': + // This state is reported upon a successful call of pause(). + break; + case 'stopped': + // This state is reported upon a successful call of stop(). + break; + case 'released': + // This state is reported upon a successful call of release(). + break; + case 'error': + // The error state indicates that an error occurs at the bottom layer. You must rectify the fault and create an AVRecorder instance again. + break; + default: + console.info('case state is unknown'); + } + }); + AVRecorder.on('error', (err) => { + // Listen for non-interface errors. + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + }); + + // Call prepare() to prepare for recording. The bottom layer determines whether to record audio, video, or audio and video based on the input parameters of prepare(). + await AVRecorder.prepare(avConfig).then(() => { + console.info('prepare success'); + }, this.failureCallback).catch(this.catchCallback); + + // If video recording is involved, call getInputSurface to obtain the input surface and pass the returned surface ID to the related camera API. + await AVRecorder.getInputSurface().then((surface) => { + console.info('getInputSurface success'); + surfaceID = surface; // The surfaceID is passed into createVideoOutput() of the camera as an input parameter. + }, this.failureCallback).catch(this.catchCallback); + + // Video recording depends on camera-related APIs. The following operations can be performed only after the video output start API is invoked. + // Start video recording. + await AVRecorder.start().then(() => { + console.info('start success'); + }, this.failureCallback).catch(this.catchCallback); + + // Pause video recording before the video output stop API of the camera is invoked. + await AVRecorder.pause().then(() => { + console.info('pause success'); + }, this.failureCallback).catch(this.catchCallback); + + // Resume video recording after the video output start API of the camera is invoked. + await AVRecorder.resume().then(() => { + console.info('resume success'); + }, this.failureCallback).catch(this.catchCallback); + + // Stop video recording after the video output stop API of the camera is invoked. + await AVRecorder.stop().then(() => { + console.info('stop success'); + }, this.failureCallback).catch(this.catchCallback); + + // Reset the recording configuration. + await AVRecorder.reset().then(() => { + console.info('reset success'); + }, this.failureCallback).catch(this.catchCallback); + + // Disable the listeners. The configured callbacks will be invalid after release() is invoked, even if you do not call off(). + AVRecorder.off('stateChange'); + AVRecorder.off('error'); + + // Release the video recording resources and camera object resources. + await AVRecorder.release().then(() => { + console.info('release success'); + }, this.failureCallback).catch(this.catchCallback); + + // Set the AVRecorder instance to null. + AVRecorder = undefined; + surfaceID = undefined; + } +} +``` + +### Full-Process Scenario of Pure Audio Recording + +The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources. + +The value range that can be set for the audio recording parameters is restricted by the codec performance of the device and the performance of the audio subsystem. + +``` +import media from '@ohos.multimedia.media' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +export class AudioRecorderDemo { + private testFdNumber; // Used to save the FD address. + + // Obtain the FD corresponding to fileName of the recorded file. The media library capability is required. To use the media library, configure the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. + async getFd(fileName) { + // For details about the implementation mode, see the media library documentation. + this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54 + } + + // Error callback triggered in the case of an error in the promise mode. + failureCallback(error) { + console.info('error happened, error message is ' + error.message); + } + + // Error callback triggered in the case of an exception in the promise mode. + catchCallback(error) { + console.info('catch error happened, error message is ' + error.message); + } + + async audioRecorderDemo() { + let audioRecorder; // Assign a value to the empty AudioRecorder instance upon a successful call of createAVRecorder(). + await this.getFd('01.m4a'); + // Configure the parameters related to audio recording. + let audioProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + } + let audioConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + profile : audioProfile, + url : this.testFdNumber, + rotation : 0, + location : { latitude : 30, longitude : 130 } + } + + // Create an AudioRecorder instance. + await media.createAVRecorder().then((recorder) => { + console.info('case createAVRecorder called'); + if (typeof (recorder) != 'undefined') { + audioRecorder = recorder; + console.info('createAudioRecorder success'); + } else { + console.info('createAudioRecorder failed'); + } + }, this.failureCallback).catch(this.catchCallback); + + // After the instance is created, use the on('stateChange') and on('error') callbacks to listen for state changes and errors. + audioRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state); + switch (state) { + // Your can set the desired behavior in different states as required. + case 'idle': + // This state is reported upon a successful call of rest() or create(). + break; + case 'prepared': + // This state is reported upon a successful call of prepare(). + break; + case 'started': + // This state is reported upon a successful call of start(). + break; + case 'paused': + // This state is reported upon a successful call of pause(). + break; + case 'stopped': + // This state is reported upon a successful call of stop(). + break; + case 'released': + // This state is reported upon a successful call of release(). + break; + case 'error': + // The error state indicates that an error occurs at the bottom layer. You must rectify the fault and create an AudioRecorder instance again. + break; + default: + console.info('case state is unknown'); + } + }); + audioRecorder.on('error', (err) => { + // Listen for non-interface errors. + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + }); + + // Call prepare() to prepare for recording. The bottom layer determines whether to record audio, video, or audio and video based on the input parameters of prepare(). + await audioRecorder.prepare(audioConfig).then(() => { + console.info('prepare success'); + }, this.failureCallback).catch(this.catchCallback); + + // Call start() to start audio recording. + await audioRecorder.start().then(() => { + console.info('start success'); + }, this.failureCallback).catch(this.catchCallback); + + // Call pause() to pause audio recording. + await audioRecorder.pause().then(() => { + console.info('pause success'); + }, this.failureCallback).catch(this.catchCallback); + + // Call resume() to resume audio recording. + await audioRecorder.resume().then(() => { + console.info('resume success'); + }, this.failureCallback).catch(this.catchCallback); + + // Call stop() to stop audio recording. + await audioRecorder.stop().then(() => { + console.info('stop success'); + }, this.failureCallback).catch(this.catchCallback); + + // Call reset() to reset the recording configuration. + await audioRecorder.reset().then(() => { + console.info('reset success'); + }, this.failureCallback).catch(this.catchCallback); + + // Disable the listeners. The configured callbacks will be invalid after release() is invoked, even if you do not call off(). + avRecorder.off('stateChange'); + avRecorder.off('error'); + + // Call release() to release audio recording resources. + await audioRecorder.release().then(() => { + console.info('release success'); + }, this.failureCallback).catch(this.catchCallback); + + // Set the AudioRecorder instance to null. + audioRecorder = undefined; + } +} + +``` + +### Full-Process Scenario of Pure Video Recording + +The full video recording process includes creating an instance, setting recording parameters, obtaining the input surface, starting, pausing, resuming, and stopping recording, and releasing resources. + +The video range that can be set for the video recording parameters is restricted by the codec performance of the device and the performance of the camera subsystem. + +``` +import media from '@ohos.multimedia.media' +import camera from '@ohos.multimedia.camera' +import mediaLibrary from '@ohos.multimedia.mediaLibrary' + +export class VideoRecorderDemo { + private testFdNumber; // Used to save the FD address. + + // Obtain the FD corresponding to fileName of the recorded file. The media library capability is required. To use the media library, configure the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. + async getFd(fileName) { + // For details about the implementation mode, see the media library documentation. + this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54 + } + + // Error callback triggered in the case of an error in the promise mode. + failureCallback(error) { + console.info('error happened, error message is ' + error.message); + } + + // Error callback triggered in the case of an exception in the promise mode. + catchCallback(error) { + console.info('catch error happened, error message is ' + error.message); + } + + async videoRecorderDemo() { + let videoRecorder; // Assign a value to the empty VideoRecorder instance upon a successful call of createAVRecorder(). + let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera. + await this.getFd('01.mp4'); + + // Configure the parameters related to video recording. + let videoProfile = { + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 + } + let videoConfig = { + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : videoProfile, + url : 'fd://', + rotation : 0, + location : { latitude : 30, longitude : 130 } + } + + // Create a VideoRecorder instance. + await media.createAVRecorder().then((recorder) => { + console.info('case createVideoRecorder called'); + if (typeof (recorder) != 'undefined') { + videoRecorder = recorder; + console.info('createVideoRecorder success'); + } else { + console.info('createVideoRecorder failed'); + } + }, this.failureCallback).catch(this.catchCallback); + + // After the instance is created, use the on('stateChange') and on('error') callbacks to listen for state changes and errors. + videoRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state); + switch (state) { + // Your can set the desired behavior in different states as required. + case 'idle': + // This state is reported upon a successful call of rest() or create(). + break; + case 'prepared': + // This state is reported upon a successful call of prepare(). + break; + case 'started': + // This state is reported upon a successful call of start(). + break; + case 'paused': + // This state is reported upon a successful call of pause(). + break; + case 'stopped': + // This state is reported upon a successful call of stop(). + break; + case 'released': + // This state is reported upon a successful call of release(). + break; + case 'error': + // The error state indicates that an error occurs at the bottom layer. You must rectify the fault and create a VideoRecorder instance again. + break; + default: + console.info('case state is unknown'); + } + }); + videoRecorder.on('error', (err) => { + // Listen for non-interface errors. + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + }); + + // Call prepare() to prepare for recording. The bottom layer determines whether to record audio, video, or audio and video based on the input parameters of prepare(). + await videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); + }, this.failureCallback).catch(this.catchCallback); + + // If video recording is involved, call getInputSurface to obtain the input surface and pass the returned surface ID to the related camera API. + await videoRecorder.getInputSurface().then((surface) => { + console.info('getInputSurface success'); + surfaceID = surface; // The surfaceID is passed into createVideoOutput() of the camera as an input parameter. + }, this.failureCallback).catch(this.catchCallback); + + // Video recording depends on camera-related APIs. The following operations can be performed only after the video output start API is invoked. + // Start video recording. + await videoRecorder.start().then(() => { + console.info('start success'); + }, this.failureCallback).catch(this.catchCallback); + + // Pause video recording before the video output stop API of the camera is invoked. + await videoRecorder.pause().then(() => { + console.info('pause success'); + }, this.failureCallback).catch(this.catchCallback); + + // Resume video recording after the video output start API of the camera is invoked. + await videoRecorder.resume().then(() => { + console.info('resume success'); + }, this.failureCallback).catch(this.catchCallback); + + // Stop video recording after the video output stop API of the camera is invoked. + await videoRecorder.stop().then(() => { + console.info('stop success'); + }, this.failureCallback).catch(this.catchCallback); + + // Reset the recording configuration. + await videoRecorder.reset().then(() => { + console.info('reset success'); + }, this.failureCallback).catch(this.catchCallback); + + // Disable the listeners. The configured callbacks will be invalid after release() is invoked, even if you do not call off(). + videoRecorder.off('stateChange'); + videoRecorder.off('error'); + + // Release the video recording resources and camera object resources. + await videoRecorder.release().then(() => { + console.info('release success'); + }, this.failureCallback).catch(this.catchCallback); + + // Set the VideoRecorder instance to null. + videoRecorder = undefined; + surfaceID = undefined; + } +} +``` + +### AVRecorder App + +The AVRecorder app provides a complete audio and video recording process, which includes creating an instance, setting recording parameters, obtaining the input surface, starting, pausing, resuming, and stopping recording, and releasing resources. + +For details about the code, see [AVRecorderDemo]([multimedia_player_framework: Implementation of media playback and recording](https://gitee.com/openharmony/multimedia_player_framework/tree/master/test/appdemo/AVRecorderDemo)). diff --git a/en/application-dev/media/figures/en-us_image_avplayer_audio.png b/en/application-dev/media/figures/en-us_image_avplayer_audio.png new file mode 100644 index 0000000000000000000000000000000000000000..b5eb9b02a977d0e4551a236c7cc8a154710f5517 Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avplayer_audio.png differ diff --git a/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png b/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png new file mode 100644 index 0000000000000000000000000000000000000000..aa8afdbcbf142fd745cee03fc422caec51cfe41b Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png differ diff --git a/en/application-dev/media/figures/en-us_image_avplayer_video.png b/en/application-dev/media/figures/en-us_image_avplayer_video.png new file mode 100644 index 0000000000000000000000000000000000000000..54525ebed1d1792f43156ffbeb1ffa37f56d8237 Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avplayer_video.png differ diff --git a/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png b/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png new file mode 100644 index 0000000000000000000000000000000000000000..7d5da3bdc91fe8fb7be9f0b4054f934ec054b8e6 Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png differ diff --git a/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png b/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png new file mode 100644 index 0000000000000000000000000000000000000000..7ffcb21f09365e9b072bdaf48f8b98d7d45a8aaa Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png differ diff --git a/en/application-dev/quick-start/app-structure.md b/en/application-dev/quick-start/app-structure.md index 62b23fad4d660b1d3e516a696b0f7ce95bbde053..78d727f2df95b3bdacc025f4159e88b47abf804e 100644 --- a/en/application-dev/quick-start/app-structure.md +++ b/en/application-dev/quick-start/app-structure.md @@ -3,7 +3,7 @@ The **app** tag contains application-wide configuration. The internal structure is as follows: -### Internal Structure of the app Tag +**Table 1** Internal structure of the app tag | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -14,15 +14,19 @@ The **app** tag contains application-wide configuration. The internal structure | smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)| | smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)| -#### Internal Structure of the version Atttribute +## Internal Structure of the version Atttribute + +**Table 2** Internal structure of the version atttribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | -| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:
For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.
*A* indicates the major version number.
*B* indicates the minor version number.
*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
*A* indicates the major version number.
*B* indicates the minor version number.
*C* indicates the feature version number.
*D* indicates the patch version number.| Number| No| +| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:
For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.
- *A* indicates the major version number.
- *B* indicates the minor version number.
- *C* indicates the patch version number.
For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
- *A* indicates the major version number.
- *B* indicates the minor version number.
- *C* indicates the feature version number.
- *D* indicates the patch version number. | Number| No| | code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:
API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No| | minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)| -#### Internal Structure of the apiVersion Attribute +## Internal Structure of the apiVersion Attribute + +**Table 3** Internal structure of the apiVersion attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -30,7 +34,7 @@ The **app** tag contains application-wide configuration. The internal structure | target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| | releaseType | SDK status when the application is running.
**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.
**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| -### Example of the **app** Tag +Example of the **app** tag: ```json "app": { diff --git a/en/application-dev/quick-start/arkts-restrictions-and-extensions.md b/en/application-dev/quick-start/arkts-restrictions-and-extensions.md index 1cb3b0fa04aedd8df61a660993e7f67e48c03c98..a03b839c3b1cdc06017c897cdd20be8a0dc02210 100644 --- a/en/application-dev/quick-start/arkts-restrictions-and-extensions.md +++ b/en/application-dev/quick-start/arkts-restrictions-and-extensions.md @@ -46,33 +46,77 @@ struct bindPopupPage { ## Restrictions on Data Type Declarations of State Variables -The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types. - -Example: - -```ts -// xxx.ets -@Entry -@Component -struct IndexPage { - // Incorrect: @State message: string | Resource = 'Hello World' - @State message: string = 'Hello World' - - build() { - Row() { - Column() { - Text(`${this.message}`) - .fontSize(50) - .fontWeight(FontWeight.Bold) +1. The data types of state variables decorated by state decorators must be explicitly declared. They cannot be declared as **any** or **Date**. + + Example: + + ```ts + // xxx.ets + @Entry + @Component + struct DatePickerExample { + // Incorrect: @State isLunar: any = false + @State isLunar: boolean = false + // Incorrect: @State selectedDate: Date = new Date('2021-08-08') + private selectedDate: Date = new Date('2021-08-08') + + build() { + Column() { + Button('Switch Calendar') + .margin({ top: 30 }) + .onClick(() => { + this.isLunar = !this.isLunar + }) + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.selectedDate + }) + .lunar(this.isLunar) + .onChange((value: DatePickerResult) => { + this.selectedDate.setFullYear(value.year, value.month, value.day) + console.info('select current date is: ' + JSON.stringify(value)) + }) + + }.width('100%') } - .width('100%') } - .height('100%') - } -} -``` + ``` + + ![datePicker](../../application-dev/reference/arkui-ts/figures/datePicker.gif) + +2. The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types. + + The **Length**, **ResourceStr**, and **ResourceColor** types are combinations of primitive data types or reference data types. Therefore, they cannot be used by the aforementioned types of state variables. + For details about the definitions of **Length**, **ResourceStr**, and **ResourceColor**, see [Types](../../application-dev/reference/arkui-ts/ts-types.md). + + Example: + + ```ts + // xxx.ets + @Entry + @Component + struct IndexPage { + // Incorrect: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + // Incorrect: @State message: ResourceStr = $r('app.string.hello') + @State resourceStr: Resource = $r('app.string.hello') + + build() { + Row() { + Column() { + Text(`${this.message}`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } + } + ``` -![hello](figures/hello.PNG) + ![hello](figures/hello.PNG) ## Initialization and Restrictions of Custom Components' Member Variables @@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t | @Link | Forbidden | Mandatory | | @StorageLink | Mandatory | Forbidden | | @StorageProp | Mandatory | Forbidden | +| @LocalStorageLink | Mandatory | Forbidden | +| @LocalStorageProp | Mandatory | Forbidden | | @Provide | Mandatory | Optional | | @Consume | Forbidden | Forbidden | | @ObjectLink | Forbidden | Mandatory | @@ -111,25 +157,78 @@ As indicated by the preceding table: Comply with the following rules when using constructors to initialize member variables: -| From the Variable in the Parent Component (Below) to the Variable in the Child Component (Right)| @State | @Link | @Prop | Normal Variable| -| -------------------------------------------- | ------ | ------ | ------ | -------- | -| @State | Not allowed| Allowed | Allowed | Allowed | -| @Link | Not allowed| Allowed | Not recommended| Allowed | -| @Prop | Not allowed| Not allowed| Allowed | Allowed | -| @StorageLink | Not allowed| Allowed | Not allowed| Not allowed | -| @StorageProp | Not allowed| Not allowed| Not allowed| Allowed | -| Normal variable | Allowed | Not allowed| Not allowed| Allowed | +| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** | +|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------| +| **regular** | Supported | Supported | Supported | Supported | Not supported | Not supported | Supported | +| **@State** | Supported | Supported | Supported | Supported | Supported | Supported | Supported | +| **@Link** | Not supported | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | +| **@Prop** | Supported | Supported | Supported | Supported | Supported | Supported | Supported | +| **@Provide** | Supported | Supported | Supported | Supported | Supported | Supported | Supported | +| **@Consume** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | +| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | -As indicated by the preceding table: +| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** | +|------------------|------------------|------------------|-----------------------|------------------------| +| **regular** | Supported | Not supported | Not supported | Not supported | +| **@State** | Supported | Supported | Supported | Supported | +| **@Link** | Supported (1) | Supported (1) | Supported (1) | Supported (1) | +| **@Prop** | Supported | Supported | Supported | Supported | +| **@Provide** | Supported | Supported | Supported | Supported | +| **@Consume** | Not supported | Not supported | Not supported | Not supported | +| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported | + +> **NOTE** +> +> **Supported (1)**: The dollar sign ($) must be used, for example, **this.$varA**. +> +> **regular**: refers to a regular variable that is not decorated by any decorator. + +As indicated by the preceding tables: + +- The **@ObjectLink** decorated variable cannot be directly initialized from a decorated variable in the parent component. The source of the parent component must be an array item or object attribute decorated by **@State**, **@Link**, **@Provide**, **@Consume**, or **@ObjectLink**. -- The normal variables of the parent component can be used to initialize the **@State** decorated variables of the child component, but not the **@Link** or **@Prop** decorated variables. +- The regular variables of the parent component can be used to initialize the **@State** variable of the child component, but cannot be used to initialize the **@Link**, **@Consume**, and **@ObjectLink** variables. -- The **@State** decorated variable of the parent component can be used to initialize the **@Prop**, **@Link** (using **$**), or normal variables of the child component, but not the **@State** decorated variables of the child component. +- The **@State** variable of the parent component can be used to initialize the **@Prop**, **@Link** (through **$**), or regular variables of the child component, but cannot be used to initialize the **@Consume** variable. -- The **@Link** decorated variables of the parent component can be used to initialize the **@Link** decorated or normal variables of the child component. However, initializing the **@State** decorated members of the child component can result in a syntax error. In addition, initializing the **@Prop** decorated variables is not recommended. +- The **@Link** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component. -- The **@Prop** decorated variables of the parent component can be used to initialize the normal variables or **@Prop** decorated variables of the child component, but not the **@State** or **@Link** decorated variables. +- The **@Prop** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component. -- Passing **@StorageLink** and **@StorageProp** from the parent component to the child component is prohibited. +- **@StorageLink**, **@StorageProp**, **@LocalStorageLink**, and **@LocalStorageProp** variables cannot be initialized from the parent component. - In addition to the preceding rules, the TypeScript strong type rules need to be followed. + +Example: +```ts +@Entry +@Component +struct Parent { + message: string = "Hello World" + build() { + Column() { + Child({ + stateMessage: this.message, + /* ArkTS:ERROR The regular property 'message' cannot be assigned + to the @Link property 'linkMessage'.*/ + linkMessage: this.$message + }) + } + .width('100%') + } +} + +@Component +struct Child { + @State stateMessage: string = "Hello World" + @Link linkMessage: string + build() { + Column() { + Text(this.stateMessage) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } +} +``` diff --git a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md index 2eae06eca22030673ef35bcf756279444fcd9c60..dd2398a71811e6bbd9b20d0f18ce0659c3bd7acf 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md @@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c - **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. - **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key. - **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started. + +For details about how to use state variables, see [Restrictions on Data Type Declarations of State Variables](arkts-restrictions-and-extensions.md). diff --git a/en/application-dev/quick-start/deviceconfig-structure.md b/en/application-dev/quick-start/deviceconfig-structure.md index 7386e27ea69a33efc2e7bca6dfcb2413e3479799..a6bb6fa6803eb6fa75e56c6a366ae7f32d63bb19 100644 --- a/en/application-dev/quick-start/deviceconfig-structure.md +++ b/en/application-dev/quick-start/deviceconfig-structure.md @@ -1,9 +1,11 @@ -# Internal Structure of deviceConfig Tag +# Internal structure of deviceConfig Tag The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. -### Table 1 Internal Structure of the deviceConfig Tag +## Internal Structure of the deviceConfig Tag + +**Table 1** Internal structure of the deviceConfig tag | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -16,7 +18,9 @@ The **deviceConfig** tag contains device-specific configuration of the applicati Table 2 describes the internal structure of the **deviceConfig** attributes. -#### Table 2 Internal Structure of the deviceConfig Attributes +## Internal Structure of the deviceConfig Attributes + +**Table 2** Internal structure of the deviceConfig attributes | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -26,27 +30,33 @@ Table 2 describes the internal structure of the **deviceConfig** attributes. | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| | network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| -#### Table 3 Internal Structure of the network Attribute +## Internal Structure of the network Attribute + +**Table 3** Internal structure of the network attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.
**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)| | securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)| -#### Table 4 Internal Structure of the securityConfig Attribute +## Internal Structure of the securityConfig Attribute + +**Table 4** Internal structure of the securityConfig attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| -#### Table 5 Internal Structure of the domainSettings Attribute +## Internal Structure of the domainSettings Attribute + +**Table 5** Internal structure of the domainSettings attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)| -### Example of the deviceConfig Tag +Example of the **deviceConfig** tag: ```json "deviceConfig": { diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md index a8df69c1846a1ff6f7647aff4490da5d4990d431..e4aee36db107109fcaa7e6d068cbc907009c69d4 100644 --- a/en/application-dev/quick-start/module-structure.md +++ b/en/application-dev/quick-start/module-structure.md @@ -3,7 +3,7 @@ The **module** tag contains the HAP configuration. -### Table 1 Internal Structure of the module Tag + **Table 1** Internal structure of the module tag | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -20,7 +20,7 @@ The **module** tag contains the HAP configuration. | shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)| | reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| | colorMode | Color mode of the application. The options are as follows:
- **dark**: Resources applicable for the dark mode are used.
- **light**: Resources applicable for the light mode are used.
- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| -| distroFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. | Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| +| distroFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| |commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the subscribed common events. When a subscribed event is sent, the static subscriber is started. Unlike the common dynamic subscriber, the static subscriber does not need to actively call the common event subscription API in the service code, and may not be started when the common event is released. In constrast, the dynamic subscriber actively calls the common event subscription API and therefore requires the application to stay active.| Object array| Yes (initial value: left empty)| | entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)| |testRunner | Test runner configuration.| Object| Yes (initial value: left empty)| @@ -30,7 +30,7 @@ Example of the **module** tag structure: ```json { "module": { - "mainAbility": ".MainAbility", + "mainAbility": ".EntryAbility", "deviceType": [ "default", "tablet" @@ -49,8 +49,8 @@ Example of the **module** tag structure: ], "orientation": "unspecified", "visible": true, - "srcPath": "MainAbility", - "name": ".MainAbility", + "srcPath": "EntryAbility", + "name": ".EntryAbility", "srcLanguage": "ets", "icon": "$media:icon", "description": "$string:MainAbility_desc", @@ -78,7 +78,7 @@ Example of the **module** tag structure: "pages": [ "pages/Index" ], - "name": ".MainAbility", + "name": ".EntryAbility", "window": { "designWidth": 720, "autoDesignWidth": false @@ -89,7 +89,9 @@ Example of the **module** tag structure: } ``` -#### Table 2 Internal structure of the distro attribute +## Internal Structure of the distro Attribute + +**Table 2** Internal structure of the distro attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -110,7 +112,9 @@ Example of the **distro** attribute structure: } ``` -#### Table 3 Internal structure of the metadata attribute +## Internal Structure of the metadata Attribute + +**Table 3** Internal structure of the metadata attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -118,7 +122,9 @@ Example of the **distro** attribute structure: | results | Metadata of the ability return value. The metadata of each return value consists of the **description**, **name**, and **type** sub-attributes.| Object array| Yes (initial value: left empty)| | customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| Object array| Yes (initial value: left empty)| -#### Table 4 Internal structure of the parameters attribute +## Internal Structure of the parameters Attribute + +**Table 4** Internal structure of the parameters attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -126,7 +132,9 @@ Example of the **distro** attribute structure: | name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 bytes.| String| No| | type | Type of the parameter passed for calling the ability, for example, **Integer**.| String| No| -#### Table 5 Internal structure of the results attribute +## Internal Structure of the results Attribute + +**Table 5** Internal structure of the results attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -134,7 +142,9 @@ Example of the **distro** attribute structure: | name | Name of the return value. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| | type | Type of the return value, for example, **Integer**.| String| No| -#### Table 6 Internal structure of the customizeData attribute +## Internal Structure of the customizeData Attribute + +**Table 6** Internal structure of the customizeData attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -166,7 +176,9 @@ Example of the metadata attribute: } ``` -#### Table 7 Values of the deviceType attribute +## deviceType Attribute + +**Table 7** Values of the deviceType attribute | Device Type| Value| Description| | -------- | -------- | -------- | @@ -176,12 +188,14 @@ Example of the metadata attribute: | Head unit| car | - | | Default device| default | OpenHarmony device that provides full access to system capabilities.| -#### Table 8 Internal structure of the abilities attribute +## Internal Structure of the abilities Attribute + +**Table 8** Internal structure of the abilities attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)| -| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created by default, and its configuration will be saved to the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 bytes.| String| No| +| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.
The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 bytes.| String| No| | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| | icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)| | label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| @@ -210,7 +224,9 @@ Example of the metadata attribute: | startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String| Yes (initial value: left empty)| | removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean| Yes (initial value: **false**)| -#### Table 9 Internal structure of the uriPermission attribute +## Internal Structure of the uriPermission Attribute + +**Table 9** Internal structure of the uriPermission attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -223,7 +239,7 @@ Example of the **abilities** attribute structure: ```json "abilities": [ { - "name": ".MainAbility", + "name": ".EntryAbility", "description": "test main ability", // $media:ic_launcher is a media resource. "icon": "$media:ic_launcher", @@ -286,8 +302,9 @@ Example of the **abilities** attribute structure: } ] ``` +## Internal Structure of the skills Attribute -#### Table 10 Internal structure of the skills attribute +**Table 10** Internal structure of the skills attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -295,7 +312,9 @@ Example of the **abilities** attribute structure: | entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| | uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both.
The URI is specified by separate attributes of each part: <scheme>://<host>:<port>[<path>\|<pathStartWith>\|<pathRegex>].
**scheme** is mandatory when the specification is of the URI type and is optional when the specification is of data type only.| Object array| Yes (initial value: left empty)| -#### Table 11 Internal structure of the uris attribute +## Internal Structure of the uris Attribute + +**Table 11** Internal structure of the uris attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -332,22 +351,28 @@ Example of the **skills** attribute structure: ] ``` -#### Table 12 reqPermissions attributes +## reqPermissions Attributes + +**Table 12** reqPermissions attributes | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | name | Name of the permission to request.| String| No| -| reason | Reason for requesting the permission. Multi-language adaptation is required.| String| No if the permission to request is **user_grant**, yes in other cases (initial value: left empty)
If the permission to request is **user_grant** this attribute is required for the application to be released to the application market, and multi-language adaptation is required. | +| reason | Reason for requesting the permission. Multi-language adaptation is required.| String| No if the permission to request is **user_grant**, yes in other cases (initial value: left empty)
If the permission to request is **user_grant** this attribute is required for the application to be released to the application market, and multi-language adaptation is required.| | usedScene | Scene under which the permission is used. It consists of the **abilities** and **when** sub-attributes.
- **ability**: ability name. Multiple ability names can be configured.
- **when**: time for using the permission. The options are **inuse** and **always**.| Object| Yes (initial value: left empty)
**when**: initial value (**inuse**) allowed| -#### Table 13 Internal structure of the usedScene attribute +## Internal Structure of the usedScene Attribute + +**Table 13** Internal structure of the usedScene attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | ability | Names of abilities that require the permission.| String array| Yes (initial value: all ability names)| | when | Time when the permission is used.
**inuse**: The permission is required when the ability is in use.
**always**: The permission is required at all times.| Value| Yes (initial value: left empty)| -#### Table 14 Internal structure of the js attribute +## Internal Structure of the js Attribute + +**Table 14** Internal structure of the js attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -357,14 +382,18 @@ Example of the **skills** attribute structure: | type | Type of the JS component. The options are as follows:
**normal**: indicates an application instance.
**form**: indicates a widget instance.| String| Yes (initial value: **"normal"**)| |mode | Development mode of the JS component.| Object| Yes (initial value: left empty)| -#### Table 15 Internal structure of the window attribute +## Internal Structure of the window Attribute + +**Table 15** Internal structure of the window attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number| Yes (initial value: 720px)| | autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| -#### Table 16 Internal structure of the mode attribute +## Internal Structure of the mode Attribute + +**Table 16** Internal structure of the mode attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -391,7 +420,9 @@ Example of the **js** attribute structure: ] ``` -#### Table 17 Internal structure of the shortcuts attribute +## Internal Structure of the shortcuts Attribute + +**Table 17** Internal structure of the shortcuts attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -400,7 +431,9 @@ Example of the **js** attribute structure: | icon | Icon of the shortcut. The value is a resource index to the description.| String| Yes (initial value: left empty)| | intents | Wants to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes.| Object array| Yes (initial value: left empty)| -#### Table 18 Internal structure of the intents attribute +## Internal Structure of the intents Attribute + +**Table 18** Internal structure of the intents attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -419,14 +452,16 @@ Example of the **shortcuts** attribute structure: "intents": [ { "targetBundle": "com.example.world.test", - "targetClass": "com.example.world.test.entry.MainAbility" + "targetClass": "com.example.world.test.entry.EntryAbility" } ] } ] ``` -#### Table 19 Internal structure of the forms attribute +## Internal Structure of the forms Attribute + +**Table 19** Internal structure of the forms attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -445,7 +480,9 @@ Example of the **shortcuts** attribute structure: | metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute.| Object| Yes (initial value: left empty)| | customizeData | Custom information of the widget.| Object array| Yes (initial value: left empty)| -#### Table 20 Internal structure of the customizeData attribute +## Internal Structure of the customizeData Attribute + +**Table 20** Internal structure of the customizeData attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -494,7 +531,7 @@ Example of the **forms** attribute structure: "portraitLayouts": [ "$layout:ability_form" ], - "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", + "formConfigAbility": "ability://com.example.myapplication.fa/.EntryAbility", "metaData": { "customizeData": [ { @@ -507,7 +544,9 @@ Example of the **forms** attribute structure: ] ``` -#### Table 21 Internal structure of the distroFilter attribute +## Internal Structure of the distroFilter Attribute + +**Table 21** Internal structure of the distroFilter attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -517,35 +556,45 @@ Example of the **forms** attribute structure: |screenDensity | Pixel density of the screen, in dots per inch (DPI).| Object array| Yes (initial value: left empty)| | countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported.| Object array| Yes (initial value: left empty)| -#### Table 22 Internal structure of the apiVersion attribute +## Internal Structure of the apiVersion Attribute + +**Table 22** Internal structure of the apiVersion attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| | value | API versions, for example, 4, 5, or 6. Example: If an application comes with two versions developed using API version 5 and API version 6 for the same device model, two installation packages of the entry type can be released for the application.| Array| No| -#### Table 23 Internal structure of the screenShape attribute +## Internal Structure of the screenShape Attribute + +**Table 23** Internal structure of the screenShape attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| -| value | Screen shapes. The value can be **circle**, **rect**, or both. Example: Different HAP files can be provided for a smart watch with a circular face and that with a rectangular face. | Array| No| +| value | API versions, for example, 4, 5, or 6. Example: If an application comes with two versions developed using API version 5 and API version 6 for the same device model, two installation packages of the entry type can be released for the application.| Array| No| + +## Internal Structure of the screenWindow Attribute -#### Table 24 Internal structure of the screenWindow attribute +**Table 24** Internal structure of the screenWindow attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| -| value | Screen width and height, in pixels. The value an array of supported width and height pairs, each in the "width * height" format, for example, **"454 * 454"**. | Array| No| +| value | API versions, for example, 4, 5, or 6. Example: If an application comes with two versions developed using API version 5 and API version 6 for the same device model, two installation packages of the entry type can be released for the application.| Array| No| + +## Internal Structure of the screenDensity Attribute -#### Table 25 Internal structure of the screenDensity attribute +**Table 25** Internal structure of the screenDensity attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| | value | Pixel density of the screen, in dots per inch (DPI). The options are as follows:
**sdpi**: small-scale DPI. This value is applicable to devices with a DPI range of (0, 120].
**mdpi**: medium-scale DPI. This value is applicable to devices with a DPI range of (120, 160].
**ldpi**: large-scale DPI. This value is applicable to devices with a DPI range of (160, 240].
**xldpi**: extra-large-scale DPI. This value is applicable to devices with a DPI range of (240, 320].
**xxldpi**: extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (320, 480].
**xxxldpi**: extra-extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (480, 640].| Array| No| -#### Table 26 Internal structure of the countryCode attribute +## Internal Structure of the countryCode attribute + +**Table 26** Internal structure of the countryCode attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -580,7 +629,9 @@ Example of the **distroFilter** attribute structure: } ``` -#### Table 27 Internal structure of the commonEvents attribute +## Internal Structure of the commonEvents Attribute + +**Table 27** Internal structure of the commonEvents attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -596,7 +647,7 @@ Example of the **commonEvents** attribute structure: ```json "commonEvents": [ { - "name": ".MainAbility", + "name": ".EntryAbility", "permission": "ohos.permission.GET_BUNDLE_INFO", "data": [ "com.example.demo", @@ -610,7 +661,9 @@ Example of the **commonEvents** attribute structure: ] ``` -#### Table 28 Internal structure of the testRunner attribute +## Internal Structure of the testRunner Attribute + +**Table 28** Internal structure of the testRunner attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -627,7 +680,8 @@ Example of the **commonEvents** attribute structure: **definePermission** applies only to system applications and does not take effect for third-party applications. -#### Table 29 Internal structure of the definePermissions attribute +## Internal Structure of the definePermissions Attribute +**Table 29** Internal structure of the definePermissions attribute | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 5af0c2ec5f64bbb5c477af7d133c1c1f2379f9ed..94813374a05e1dfe941c796b8c053b23cd3a1ff3 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -122,7 +122,7 @@ - continuation - [continuationExtraParams](js-apis-continuation-continuationExtraParams.md) - [continuationResult](js-apis-continuation-continuationResult.md) - + - Common Event and Notification - [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md) @@ -203,7 +203,6 @@ - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - security - [PermissionRequestResult](js-apis-permissionrequestresult.md) - - Data Management - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) @@ -215,11 +214,15 @@ - [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md) - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - data/rdb - - [resultSet](js-apis-data-resultset.md) + - [resultSet (Result Set)](js-apis-data-resultset.md) - File Management - - [@ohos.environment](js-apis-environment.md) + - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) + - [@ohos.file.fs (File Management)](js-apis-file-fs.md) + - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) + - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md) + - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md) diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index b0bfec0f18357dd7ce82d36b90d0f159f398c42f..febd683936b841caf9b7b44511ee18370761ca42 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro | ID | Error Message| | --------- | ------- | -| 100001 | If no page is found for pageId or fail to get object property list. | +| 100001 | if no page is found for pageId or fail to get object property list. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 6f933f9ca9997721df4377be310d6be1cb307e1e..b9ec53b660112df52456caa020b5e9105316bbbd 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -64,7 +64,6 @@ Creates an app account. This API uses an asynchronous callback to return the res **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.createAccount("WangWu", (err) => { console.log("createAccount err: " + JSON.stringify(err)); @@ -102,7 +101,6 @@ Creates an app account with custom data. This API uses an asynchronous callback **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { customData: { "age": "10" @@ -155,7 +153,6 @@ Creates an app account with custom data. This API uses a promise to return the r **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { customData: { "age": "10" @@ -215,7 +212,6 @@ Creates an app account implicitly based on the specified account owner. This API }); } - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.createAccountImplicitly("com.example.accountjsdemo", { onResult: onResultCallback, @@ -270,7 +266,6 @@ Creates an app account implicitly based on the specified account owner and optio }); } - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { authType: "getSocialData", requiredLabels: [ "student" ] @@ -311,7 +306,6 @@ Removes an app account. This API uses an asynchronous callback to return the res **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.removeAccount("ZhaoLiu", (err) => { if (err) { @@ -356,7 +350,6 @@ Removes an app account. This API uses a promise to return the result. **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.removeAccount("Lisi").then(() => { console.log("removeAccount successfully"); @@ -397,7 +390,6 @@ Sets the access to the data of an account for an app. This API uses an asynchron **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true, (err) => { if (err) { @@ -445,7 +437,6 @@ Sets the access to the data of an account for an app. This API uses a promise to **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true).then(() => { console.log("setAppAccess successfully"); @@ -485,7 +476,6 @@ Checks whether an app can access the data of an account. This API uses an asynch **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo", (err, isAccessible) => { if (err) { @@ -532,7 +522,6 @@ Checks whether an app can access the data of an account. This API uses a promise **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo").then((isAccessible) => { console.log("checkAppAccess successfully, isAccessible: " + isAccessible); @@ -573,7 +562,6 @@ Sets data synchronization for an app account. This API uses an asynchronous call **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { console.log("setDataSyncEnabled err: " + JSON.stringify(err)); @@ -617,7 +605,6 @@ Sets data synchronization for an app account. This API uses a promise to return **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { console.log('setDataSyncEnabled Success'); @@ -657,7 +644,6 @@ Checks whether data synchronization is enabled for an app account. This API uses **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.checkDataSyncEnabled("ZhangSan", (err, isEnabled) => { if (err) { @@ -704,7 +690,6 @@ Checks whether data synchronization is enabled for an app account. This API uses **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.checkDataSyncEnabled("ZhangSan").then((isEnabled) => { console.log("checkDataSyncEnabled successfully, isEnabled: " + isEnabled); @@ -744,7 +729,6 @@ Sets a credential for an app account. This API uses an asynchronous callback to **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx", (err) => { if (err) { @@ -791,7 +775,6 @@ Sets a credential for an app account. This API uses a promise to return the resu **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx").then(() => { console.log("setCredential successfully"); @@ -831,7 +814,6 @@ Obtains the credential of an app account. This API uses an asynchronous callback **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getCredential("ZhangSan", "PIN_SIX", (err, result) => { if (err) { @@ -878,7 +860,6 @@ Obtains the credential of an app account. This API uses a promise to return the **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getCredential("ZhangSan", "PIN_SIX").then((credential) => { console.log("getCredential successfully, credential: " + credential); @@ -919,7 +900,6 @@ Sets custom data for an app account. This API uses an asynchronous callback to r **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setCustomData("ZhangSan", "age", "12", (err) => { if (err) { @@ -967,7 +947,6 @@ Sets custom data for an app account. This API uses a promise to return the resul **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setCustomData("ZhangSan", "age", "12").then(() => { console.log("setCustomData successfully"); @@ -1007,7 +986,6 @@ Obtains the custom data of an app account based on the specified key. This API u **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getCustomData("ZhangSan", "age", (err, data) => { if (err) { @@ -1054,7 +1032,6 @@ Obtains the custom data of an app account based on the specified key. This API u **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getCustomData("ZhangSan", "age").then((data) => { console.log("getCustomData successfully, data: " + data); @@ -1099,7 +1076,6 @@ Obtains the custom data of an app account based on the specified key. The API re **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { let value = appAccountManager.getCustomDataSync("ZhangSan", "age"); console.info("getCustomDataSync successfully, vaue:" + value); @@ -1114,8 +1090,6 @@ getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS - **System capability**: SystemCapability.Account.AppAccount **Parameters** @@ -1133,7 +1107,6 @@ Obtains information about all accessible app accounts. This API uses an asynchro **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAllAccounts((err, data) => { if (err) { @@ -1153,8 +1126,6 @@ getAllAccounts(): Promise<Array<AppAccountInfo>> Obtains information about all accessible app accounts. This API uses a promise to return the result. -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS - **System capability**: SystemCapability.Account.AppAccount **Return value** @@ -1172,7 +1143,6 @@ Obtains information about all accessible app accounts. This API uses a promise t **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAllAccounts().then((data) => { console.debug("getAllAccounts successfully"); @@ -1190,8 +1160,6 @@ getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccount Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS - **System capability**: SystemCapability.Account.AppAccount **Parameters** @@ -1212,7 +1180,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAccountsByOwner("com.example.accountjsdemo2", (err, data) => { if (err) { @@ -1232,8 +1199,6 @@ getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses a promise to return the result. -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS - **System capability**: SystemCapability.Account.AppAccount **Parameters** @@ -1259,7 +1224,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAccountsByOwner("com.example.accountjsdemo2").then((data) => { console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); @@ -1299,7 +1263,6 @@ Subscribes to account information changes of apps. **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.log("receive change data:" + JSON.stringify(data)); } @@ -1312,7 +1275,7 @@ Subscribes to account information changes of apps. ### off('accountChange')9+ -off(type: 'accountChange', callback?: Callback>): void +off(type: 'accountChange', callback?: Callback<Array<AppAccountInfo>>): void Unsubscribes from account information changes. @@ -1323,7 +1286,7 @@ Unsubscribes from account information changes. | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | ------------ | | type | 'accountChange' | Yes | Event type to unsubscribe from. The value is **'accountChange'**. | -| callback | Callback> | No | Callback to unregister.| +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | No | Callback to unregister.| **Error codes** @@ -1336,8 +1299,7 @@ Unsubscribes from account information changes. **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ + function changeOnCallback(data) { console.log("receive change data:" + JSON.stringify(data)); } try{ @@ -1398,7 +1360,6 @@ Authenticates an app account. This API uses an asynchronous callback to return t }); } - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", { onResult: onResultCallback, @@ -1458,7 +1419,6 @@ Authenticates an app account with customized options. This API uses an asynchron let options = { "password": "xxxx", }; - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", options, { onResult: onResultCallback, @@ -1498,7 +1458,6 @@ Obtains the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, token) => { if (err) { @@ -1546,7 +1505,6 @@ Obtains the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((token) => { console.log("getAuthToken successfully, token: " + token); @@ -1587,7 +1545,6 @@ Sets an authorization token of the specific authentication type for an app accou **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { if (err) { @@ -1635,7 +1592,6 @@ Sets an authorization token of the specific authentication type for an app accou **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { console.log("setAuthToken successfully"); @@ -1677,7 +1633,6 @@ Deletes the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { if (err) { @@ -1726,7 +1681,6 @@ Deletes the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { console.log("deleteAuthToken successfully"); @@ -1770,7 +1724,6 @@ Sets the visibility of an authorization token to an app. This API uses an asynch **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { if (err) { @@ -1821,7 +1774,6 @@ Sets the visibility of an authorization token to an app. This API uses a promise **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { console.log("setAuthTokenVisibility successfully"); @@ -1863,7 +1815,6 @@ Checks the visibility of an authorization token of the specified authentication **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, isVisible) => { if (err) { @@ -1912,7 +1863,6 @@ Checks the visibility of an authorization token of the specified authentication **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((isVisible) => { console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); @@ -1951,7 +1901,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses an a **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo", (err, tokenArr) => { if (err) { @@ -1997,7 +1946,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses a pr **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo").then((tokenArr) => { console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); @@ -2037,7 +1985,6 @@ Obtains the authorization list of the specified authentication type for an app a **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData", (err, authList) => { if (err) { @@ -2084,7 +2031,6 @@ Obtains the authorization list of the specified authentication type for an app a **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData").then((authList) => { console.log("getAuthList successfully, authList: " + authList); @@ -2123,7 +2069,6 @@ Obtains the authenticator callback for the authentication session. This API uses ```js import featureAbility from '@ohos.ability.featureAbility'; - let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant((err, want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; try { @@ -2183,7 +2128,6 @@ Obtains the authenticator callback for the authentication session. This API uses ```js import featureAbility from '@ohos.ability.featureAbility'; - let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant().then((want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; try { @@ -2236,7 +2180,6 @@ Obtains the authenticator information of an app. This API uses an asynchronous c **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo", (err, info) => { if (err) { @@ -2281,7 +2224,6 @@ Obtains the authenticator information of an app. This API uses a promise to retu **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo").then((info) => { console.log("queryAuthenticatorInfo successfully, info: " + JSON.stringify(info)); @@ -2324,7 +2266,6 @@ Checks whether an app account has specific labels. This API uses an asynchronous **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let labels = ["student"]; try { appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels, (err, hasAllLabels) => { @@ -2375,7 +2316,6 @@ Checks whether an app account has specific labels. This API uses a promise to re **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let labels = ["student"]; try { appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels).then((hasAllLabels) => { @@ -2416,7 +2356,6 @@ Deletes the credential of the specified type from an app account. This API uses **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.deleteCredential("zhangsan", "PIN_SIX", (err) => { if (err) { @@ -2463,7 +2402,6 @@ Deletes the credential of the specified type from an app account. This API uses **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.deleteCredential("zhangsan", "PIN_SIX").then(() => { console.log("deleteCredential successfully"); @@ -2502,7 +2440,6 @@ Selects the accounts that can be accessed by the invoker based on the options. T **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { allowedOwners: [ "com.example.accountjsdemo" ], requiredLabels: [ "student" ] @@ -2552,7 +2489,6 @@ Selects the accounts that can be accessed by the invoker based on the options. T **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { allowedOwners: ["com.example.accountjsdemo"] }; @@ -2597,7 +2533,6 @@ Verifies the credential of an app account. This API uses an asynchronous callbac **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", { onResult: (resultCode, result) => { @@ -2644,7 +2579,6 @@ Verifies the user credential. This API uses an asynchronous callback to return t **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { credentialType: "pin", credential: "123456" @@ -2692,7 +2626,6 @@ Sets the authenticator attributes of an app. This API uses an asynchronous callb **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); try { appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", { onResult: (resultCode, result) => { @@ -2737,7 +2670,6 @@ Set authenticator properties. This API uses an asynchronous callback to return t **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); let options = { properties: {"prop1": "value1"} }; @@ -2780,7 +2712,6 @@ Adds an app account. This API uses an asynchronous callback to return the result **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccount("WangWu", (err) => { console.log("addAccount err: " + JSON.stringify(err)); }); @@ -2793,7 +2724,6 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>) Adds an app account name and additional information. This API uses an asynchronous callback to return the result. > **NOTE** -> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-1). **System capability**: SystemCapability.Account.AppAccount @@ -2809,7 +2739,6 @@ Adds an app account name and additional information. This API uses an asynchrono **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccount("LiSi", "token101", (err) => { console.log("addAccount err: " + JSON.stringify(err)); }); @@ -2843,7 +2772,6 @@ Adds an app account name and additional information. This API uses an asynchrono **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccount("LiSi", "token101").then(()=> { console.log('addAccount Success'); }).catch((err) => { @@ -2889,7 +2817,6 @@ Adds an app account implicitly based on the specified owner. This API uses an as }); } - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback @@ -2918,7 +2845,6 @@ Deletes an app account. This API uses an asynchronous callback to return the res **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.deleteAccount("ZhaoLiu", (err) => { console.log("deleteAccount err: " + JSON.stringify(err)); }); @@ -2951,7 +2877,6 @@ Deletes an app account. This API uses a promise to return the result. **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.deleteAccount("ZhaoLiu").then(() => { console.log('deleteAccount Success'); }).catch((err) => { @@ -2981,7 +2906,6 @@ Disables an app account from accessing an app. This API uses an asynchronous cal **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { console.log("disableAppAccess err: " + JSON.stringify(err)); }); @@ -3015,7 +2939,6 @@ Disables an app account from accessing an app. This API uses a promise to return **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { console.log('disableAppAccess Success'); }).catch((err) => { @@ -3046,7 +2969,6 @@ Enables an app account to access an app. This API uses an asynchronous callback **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { console.log("enableAppAccess: " + JSON.stringify(err)); }); @@ -3080,7 +3002,6 @@ Enables an app account to access an app. This API uses a promise to return the r **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { console.log('enableAppAccess Success'); }).catch((err) => { @@ -3112,7 +3033,6 @@ Checks whether data synchronization is enabled for an app account. This API uses **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); console.log('checkAppAccountSyncEnable result: ' + result); @@ -3148,7 +3068,6 @@ Checks whether data synchronization is enabled for an app account. This API uses **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { console.log('checkAppAccountSyncEnable, result: ' + data); }).catch((err) => { @@ -3180,7 +3099,6 @@ Set credentials for an app account. This API uses an asynchronous callback to re **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { console.log("setAccountCredential err: " + JSON.stringify(err)); }); @@ -3215,7 +3133,6 @@ Set credentials for an app account. This API uses a promise to return the result **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { console.log('setAccountCredential Success'); }).catch((err) => { @@ -3247,7 +3164,6 @@ Sets additional information for an app account. This API uses an asynchronous ca **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { console.log("setAccountExtraInfo err: " + JSON.stringify(err)); }); @@ -3282,7 +3198,6 @@ Sets additional information for an app account. This API uses a promise to retur **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { console.log('setAccountExtraInfo Success'); }).catch((err) => { @@ -3315,7 +3230,6 @@ Sets data synchronization for an app account. This API uses an asynchronous call **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); }); @@ -3351,7 +3265,6 @@ Sets data synchronization for an app account. This API uses a promise to return **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { console.log('setAppAccountSyncEnable Success'); }).catch((err) => { @@ -3384,7 +3297,6 @@ Sets data to be associated with an app account. This API uses an asynchronous ca **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { console.log("setAssociatedData err: " + JSON.stringify(err)); }); @@ -3420,7 +3332,6 @@ Sets data to be associated with an app account. This API uses a promise to retur **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { console.log('setAssociatedData Success'); }).catch((err) => { @@ -3451,7 +3362,6 @@ Obtains information about all accessible app accounts. This API uses an asynchro **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllAccessibleAccounts((err, data)=>{ console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); @@ -3481,7 +3391,6 @@ Obtains information about all accessible app accounts. This API uses a promise t **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllAccessibleAccounts().then((data) => { console.log('getAllAccessibleAccounts: ' + data); }).catch((err) => { @@ -3513,7 +3422,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); const selfBundle = "com.example.actsgetallaaccounts"; appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ console.debug("getAllAccounts err:" + JSON.stringify(err)); @@ -3550,7 +3458,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); const selfBundle = "com.example.actsgetallaaccounts"; appAccountManager.getAllAccounts(selfBundle).then((data) => { console.log('getAllAccounts: ' + data); @@ -3582,7 +3489,6 @@ Obtains the credential of an app account. This API uses an asynchronous callback **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { console.log("getAccountCredential err: " + JSON.stringify(err)); console.log('getAccountCredential result: ' + result); @@ -3617,7 +3523,6 @@ Obtains the credential of an app account. This API uses a promise to return the **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { console.log('getAccountCredential, result: ' + data); }).catch((err) => { @@ -3647,7 +3552,6 @@ Obtains additional information of an app account. Additional information refers **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { console.log("getAccountExtraInfo err: " + JSON.stringify(err)); console.log('getAccountExtraInfo result: ' + result); @@ -3681,7 +3585,6 @@ Obtains additional information of an app account. Additional information refers **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { console.log('getAccountExtraInfo, result: ' + data); }).catch((err) => { @@ -3712,7 +3615,6 @@ Obtains data associated with an app account. This API uses an asynchronous callb **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { console.log("getAssociatedData err: " + JSON.stringify(err)); console.log('getAssociatedData result: ' + result); @@ -3747,7 +3649,6 @@ Obtains data associated with an app account. This API uses a promise to return t **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { console.log('getAssociatedData: ' + data); }).catch((err) => { @@ -3778,7 +3679,6 @@ Subscribes to account information changes of apps. **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.debug("receive change data:" + JSON.stringify(data)); } @@ -3792,7 +3692,7 @@ Subscribes to account information changes of apps. ### off('change')(deprecated) -off(type: 'change', callback?: Callback>): void +off(type: 'change', callback?: Callback<Array<AppAccountInfo>>): void Unsubscribes from account information changes. @@ -3807,12 +3707,11 @@ Unsubscribes from account information changes. | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | ------------ | | type | 'change' | Yes | Event type to unsubscribe from. The value is **'change'**, which indicates the account change event. | -| callback | Callback> | No | Callback to unregister.| +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | No | Callback to unregister.| **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.debug("receive change data:" + JSON.stringify(data)); appAccountManager.off('change', function(){ @@ -3866,7 +3765,6 @@ Authenticates an app account with customized options. This API uses an asynchron }); } - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback @@ -3897,7 +3795,6 @@ Obtains the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); console.log('getOAuthToken token: ' + data); @@ -3933,7 +3830,6 @@ Obtains the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthToken token: ' + data); }).catch((err) => { @@ -3965,7 +3861,6 @@ Sets an authorization token of the specific authentication type for an app accou **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); @@ -4000,7 +3895,6 @@ Sets an authorization token of the specific authentication type for an app accou **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { console.log('setOAuthToken successfully'); }).catch((err) => { @@ -4033,7 +3927,6 @@ Deletes the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); @@ -4069,7 +3962,6 @@ Deletes the authorization token of the specified authentication type for an app **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { console.log('deleteOAuthToken successfully'); }).catch((err) => { @@ -4102,7 +3994,6 @@ Sets the visibility of an authorization token to an app. This API uses an asynch **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); @@ -4138,7 +4029,6 @@ Sets the visibility of an authorization token to an app. This API uses a promise **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { @@ -4170,7 +4060,6 @@ Checks the visibility of an authorization token of the specified authentication **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, data) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); @@ -4206,7 +4095,6 @@ Checks the visibility of an authorization token of the specified authentication **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((data) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { @@ -4237,7 +4125,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses an a **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo", (err, data) => { console.log("getAllOAuthTokens err: " + JSON.stringify(err)); console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); @@ -4272,7 +4159,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses a pr **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo").then((data) => { console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err) => { @@ -4303,7 +4189,6 @@ Obtains the authorization list of the specified authentication type for an app a **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthList err: ' + JSON.stringify(err)); console.log('getOAuthList data: ' + JSON.stringify(data)); @@ -4338,7 +4223,6 @@ Obtains the authorization list of the specified authentication type for an app a **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { @@ -4369,7 +4253,6 @@ Obtains the authenticator callback for an authentication session. This API uses ```js import featureAbility from '@ohos.ability.featureAbility'; - let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant((err, want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { @@ -4415,7 +4298,6 @@ Obtains the authenticator callback for an authentication session. This API uses ```js import featureAbility from '@ohos.ability.featureAbility'; - let appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant().then((want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { @@ -4454,7 +4336,6 @@ Obtains the authenticator information of an app. This API uses an asynchronous c **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo", (err, data) => { console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); @@ -4488,7 +4369,6 @@ Obtains the authenticator information of an app. This API uses a promise to retu **Example** ```js - let appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo").then((data) => { console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); }).catch((err) => { diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 5ba79b73ed0370258a87975c1a4ee576816964b4..b279dfcd4e2938efb33a33a70a35228a9de89b4d 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| | callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| @@ -69,9 +69,11 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + let context = null; -class MainAbility extends Ability{ + +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| **Return value** @@ -139,9 +141,11 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + let context = null; -class MainAbility extends Ability{ + +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| @@ -215,9 +219,11 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + let context = null; -class MainAbility extends Ability{ + +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** @@ -294,9 +300,11 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + let context = null; -class MainAbility extends Ability{ + +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| @@ -358,9 +366,11 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + let context = null; -class MainAbility extends Ability{ + +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** @@ -428,9 +438,9 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; let context = null; -class MainAbility extends Ability{ +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md index 4bd0a6e1357314bb04141ced51fe9d72238d6bc9..579dd277e83b8d7a20f55dc21542099e690ec470 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -// Obtain the context. + import featureAbility from '@ohos.ability.featureAbility' + +// Obtain the context. let context = featureAbility.getContext() -// Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1 } + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { if (err) { console.info("Failed to get RdbStore, err: " + err) return - } - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return } console.log("Got RdbStore successfully.") }) @@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { Stage model: ```ts -// Obtain the context. -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 + } + + data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + if (err) { + console.info("Failed to get RdbStore, err: " + err) + return + } + console.log("Got RdbStore successfully.") + }) } } - -// Call getRdbStore. -const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} -data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - if (err) { - console.info("Failed to get RdbStore, err: " + err) - return - } - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return - } - console.log("Got RdbStore successfully.") -}) ``` ## data_rdb.getRdbStore @@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -// Obtain the context. import featureAbility from '@ohos.ability.featureAbility' + +// Obtain the context. let context = featureAbility.getContext() -// Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1 } + let promise = data_rdb.getRdbStore(context, STORE_CONFIG); promise.then(async (rdbStore) => { - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return - } console.log("Got RdbStore successfully.") }).catch((err) => { console.log("Failed to get RdbStore, err: " + err) @@ -170,35 +147,23 @@ promise.then(async (rdbStore) => { Stage model: ```ts -// Obtain the context. -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 + } + + let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG); + promise.then(async (rdbStore) => { + console.log("Got RdbStore successfully.") + }).catch((err) => { + console.log("Failed to get RdbStore, err: " + err) + }) } } - -// Call getRdbStore. -const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} -let promise = data_rdb.getRdbStore(context, STORE_CONFIG); -promise.then(async (rdbStore) => { - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return - } - console.log("Got RdbStore successfully.") -}).catch((err) => { - console.log("Failed to get RdbStore, err: " + err) -}) ``` ## data_rdb.deleteRdbStore @@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -// Obtain the context. import featureAbility from '@ohos.ability.featureAbility' + +// Obtain the context. let context = featureAbility.getContext() -// Call deleteRdbStore. data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { if (err) { console.info("Failed to delete RdbStore, err: " + err) @@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { Stage model: ```ts -// Obtain the context. -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") + }) } } - -// Call deleteRdbStore. -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Failed to delete RdbStore, err: " + err) - return - } - console.log("Deleted RdbStore successfully.") -}) ``` ## data_rdb.deleteRdbStore @@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode FA model: ```js -// Obtain the context. import featureAbility from '@ohos.ability.featureAbility' + +// Obtain the context. let context = featureAbility.getContext() -// Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") promise.then(()=>{ console.log("Deleted RdbStore successfully.") @@ -318,24 +277,18 @@ promise.then(()=>{ Stage model: ```ts -// Obtain the context. -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") + promise.then(()=>{ + console.log("Deleted RdbStore successfully.") + }).catch((err) => { + console.info("Failed to delete RdbStore, err: " + err) + }) } } - -// Call deleteRdbStore. -let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ - console.log("Deleted RdbStore successfully.") -}).catch((err) => { - console.info("Failed to delete RdbStore, err: " + err) -}) ``` ## StoreConfig @@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict. | ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| | ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| -## OpenStatus10+ - -Enumerates the RDB store status. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Value | Description | -| --------- | ---- | --------------------------------------------------- | -| ON_CREATE | 0 | The RDB store is created for the first time. | -| ON_OPEN | 1 | The RDB store is already created. | - ## RdbPredicates Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. @@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the | Name | Type | Mandatory| Description | | ------------ | ----------- | ---- | -------------------------------- | -| openStatus10+ | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. | +| version10+ | number | Yes | RDB store version, which is an integer greater than 0. | + +**Example** + +```js +// Set the RDB store version. +rdbStore.version = 3 +// Obtain the RDB store version. +console.info("Get RdbStore version is " + rdbStore.version) +``` ### insert diff --git a/en/application-dev/reference/apis/js-apis-environment.md b/en/application-dev/reference/apis/js-apis-file-environment.md similarity index 65% rename from en/application-dev/reference/apis/js-apis-environment.md rename to en/application-dev/reference/apis/js-apis-file-environment.md index aca809efc243720dfdc7b95c4300ea84aee2f5c8..9c340eef3974ed2875f417c71cb8a5f7dd4b10d8 100644 --- a/en/application-dev/reference/apis/js-apis-environment.md +++ b/en/application-dev/reference/apis/js-apis-file-environment.md @@ -1,16 +1,17 @@ -# @ohos.environment (Directory Environment Capability) +# @ohos.file.environment (Directory Environment Capability) The **Environment** module provides APIs for obtaining the root directories of the storage and public files. > **NOTE** > -> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs and cannot be called by third-party applications. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import ```js -import environment from '@ohos.environment'; +import environment from '@ohos.file.environment'; ``` ## environment.getStorageDataDir @@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the **Example** ```js - environment.getStorageDataDir().then(function(path){ - console.info("getStorageDataDir successfully:"+ path); - }).catch(function(error){ - console.info("getStorageDataDir failed with error:"+ error); + environment.getStorageDataDir().then((path) => { + console.info("getStorageDataDir successfully, Path: " + path); + }).catch((err) => { + console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -54,8 +55,12 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac **Example** ```js - environment.getStorageDataDir(function(error, path){ - // do something + environment.getStorageDataDir((err, path) => { + if (err) { + console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getStorageDataDir successfully, Path: " + path); + } }); ``` @@ -76,10 +81,10 @@ Obtains the root directory of public files. This API uses a promise to return th **Example** ```js - environment.getUserDataDir().then(function(path){ - console.info("getUserDataDir successfully:"+ path); - }).catch(function(error){ - console.info("getUserDataDir failed with error:"+ error); + environment.getUserDataDir().then((path) => { + console.info("getUserDataDir successfully, Path: " + path); + }).catch((err) => { + console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -100,7 +105,11 @@ Obtains the root directory of public files. This API uses an asynchronous callba **Example** ```js - environment.getUserDataDir(function(error, path){ - // do something + environment.getUserDataDir((err, path) => { + if (err) { + console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getUserDataDir successfully, Path: " + path); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md new file mode 100644 index 0000000000000000000000000000000000000000..f82393a4691289ac4729b07334fa54c3b66067e2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -0,0 +1,2374 @@ +# @ohos.file.fs (File Management) + +The **fs** module provides APIs for file operations, including basic file management, directory management, file information statistics, and stream read and write. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import fs from '@ohos.file.fs'; +``` + +## Guidelines + +Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: + +**Stage Model** + + ```js +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + } +} + ``` + +**FA Model** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let context = featureAbility.getContext(); + context.getFilesDir().then((data) => { + let pathDir = data; + }) + ``` + +For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). + +## fs.stat + +stat(file: string|number): Promise<Stat> + +Obtains detailed file information. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------- | +| Promise<[Stat](#stat)> | Promise used to return the file information obtained.| + +**Example** + + ```js + let filePath = pathDir + "test.txt"; + fs.stat(filePath).then((stat) => { + console.info("get file info succeed, the size of file is " + stat.size); + }).catch((err) => { + console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.stat + +stat(file: string|number, callback: AsyncCallback<Stat>): void + +Obtains detailed file information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------ | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| + +**Example** + + ```js + fs.stat(pathDir, (err, stat) => { + if (err) { + console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("get file info succeed, the size of file is " + stat.size); + } + }); + ``` + +## fs.statSync + +statSync(file: string|number): Stat + +Obtains detailed file information synchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file.| + + +**Return value** + +| Type | Description | +| ------------- | ---------- | +| [Stat](#stat) | File information obtained.| + +**Example** + + ```js + let stat = fs.statSync(pathDir); + console.info("get file info succeed, the size of file is " + stat.size); + ``` + +## fs.access + +access(path: string): Promise<boolean> + +Checks whether a file exists. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<boolean> | Promise used to return a Boolean value. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.access(filePath).then((res) => { + if (res) { + console.info("file exists"); + } + }).catch((err) => { + console.info("access failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.access + +access(path: string, callback: AsyncCallback<boolean>): void + +Checks whether a file exists. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.access(filePath, (err, res) => { + if (err) { + console.info("access failed with error message: " + err.message + ", error code: " + err.code); + } else { + if (res) { + console.info("file exists"); + } + } + }); + ``` + +## fs.accessSync + +accessSync(path: string): boolean + +Synchronously checks whether a file exists. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + try { + let res = fs.accessSync(filePath); + if (res) { + console.info("file exists"); + } + } catch(err) { + console.info("accessSync failed with error message: " + err.message + ", error code: " + err.code); + } + ``` + + +## fs.close + +close(file: File|number): Promise<void> + +Closes a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.close(file).then(() => { + console.info("File closed"); + fs.closeSync(file); + }).catch((err) => { + console.info("close file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.close + +close(file: File|number, callback: AsyncCallback<void>): void + +Closes a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------ | +| file | [File](#file)\|number | Yes | File object or FD of the file to close.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.close(file, (err) => { + if (err) { + console.info("close file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("close file success"); + } + }); + ``` + +## fs.closeSync + +closeSync(file: File|number): void + +Synchronously closes a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.closeSync(file); + ``` + +## fs.copyFile + +copyFile(src: string|number, dest: string|number, mode?: number): Promise<void> + +Copies a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------- | ---- | ---------------------------------------- | +| src | string\|number | Yes | Path or FD of the file to copy. | +| dest | string\|number | Yes | Destination path of the file or FD of the file created. | +| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file of the same name.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fs.copyFile(srcPath, dstPath).then(() => { + console.info("copy file succeed"); + }).catch((err) => { + console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.copyFile + +copyFile(src: string|number, dest: string|number, mode?: number, callback: AsyncCallback<void>): void + +Copies a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------- | ---- | ---------------------------------------- | +| src | string\|number | Yes | Path or FD of the file to copy. | +| dest | string\|number | Yes | Destination path of the file or FD of the file created. | +| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | + +**Example** + + ```js + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fs.copyFile(srcPath, dstPath, (err) => { + if (err) { + console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("copy file success"); + } + }); + ``` + + +## fs.copyFileSync + +copyFileSync(src: string|number, dest: string|number, mode?: number): void + +Synchronously copies a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------- | ---- | ---------------------------------------- | +| src | string\|number | Yes | Path or FD of the file to copy. | +| dest | string\|number | Yes | Destination path of the file or FD of the file created. | +| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| + +**Example** + + ```js + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fs.copyFileSync(srcPath, dstPath); + ``` + + +## fs.mkdir + +mkdir(path: string): Promise<void> + +Creates a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the directory in the application sandbox. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.mkdir(dirPath).then(() => { + console.info("Directory created"); + }).catch((err) => { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.mkdir + +mkdir(path: string, callback: AsyncCallback<void>): void + +Creates a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the directory in the application sandbox. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.mkdir(dirPath, (err) => { + if (err) { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("mkdir success"); + } + }); + ``` + + +## fs.mkdirSync + +mkdirSync(path: string): void + +Synchronously creates a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the directory in the application sandbox. | + +**Example** + + ```js + let dirPath = path + '/testDir'; + fs.mkdirSync(dirPath); + ``` + + +## fs.open + +open(path: string, mode?: number): Promise<File> + +Opens a file. This API uses a promise to return the result. File uniform resource identifiers (URIs) are supported. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| mode | number | No | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| Promise<[File](#file)> | Promise used to return the file object.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => { + console.info("file fd: " + file.fd); + }).catch((err) => { + console.info("open file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.open + +open(path: string, mode?: number, callback: AsyncCallback<File>): void + +Opens a file. This API uses an asynchronous callback to return the result. File URIs are supported. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| mode | number | No | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err, file) => { + if (err) { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("file fd: " + file.fd); + } + }); + ``` + +## fs.openSync + +openSync(path: string, mode?: number): File + +Synchronously opens a file. File URIs are supported. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| mode | number | No | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| + +**Return value** + +| Type | Description | +| ------ | ----------- | +| [File](#file) | File object opened.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + console.info("file fd: " + file.fd); + fs.closeSync(file); + ``` + +## fs.read + +read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> + +Reads data from a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------- | ---- | ------------------------------------------------------------ | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------ | +| Promise<number> | Promise used to return the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + let buf = new ArrayBuffer(4096); + fs.read(file.fd, buf).then((readLen) => { + console.info("Read file data successfully"); + console.info(String.fromCharCode.apply(null, new Uint8Array(readLen))); + fs.closeSync(file); + }).catch((err) => { + console.info("read file data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.read + +read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback: AsyncCallback<number>): void + +Reads data from a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| +| callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + let buf = new ArrayBuffer(4096); + fs.read(file.fd, buf, (err, readLen) => { + if (err) { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("Read file data successfully"); + console.info(String.fromCharCode.apply(null, new Uint8Array(readLen))); + fs.closeSync(file); + } + }); + ``` + + +## fs.readSync + +readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number + +Synchronously reads data from a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + let buf = new ArrayBuffer(4096); + let num = fs.readSync(file.fd, buf); + fs.closeSync(file); + ``` + + +## fs.rmdir + +rmdir(path: string): Promise<void> + +Deletes a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.rmdir(dirPath).then(() => { + console.info("Directory deleted"); + }).catch((err) => { + console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.rmdir + +rmdir(path: string, callback: AsyncCallback<void>): void + +Deletes a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.rmdir(dirPath, (err) => { + if (err) { + console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("Directory deleted"); + } + }); + ``` + + +## fs.rmdirSync + +rmdirSync(path: string): void + +Synchronously deletes a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.rmdirSync(dirPath); + ``` + + +## fs.unlink + +unlink(path: string): Promise<void> + +Deletes a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.unlink(filePath).then(() => { + console.info("File deleted"); + }).catch((err) => { + console.info("remove file failed with error message: " + err.message + ", error code: " + err.codeor); + }); + ``` + + +## fs.unlink + +unlink(path: string, callback: AsyncCallback<void>): void + +Deletes a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.unlink(filePath, (err) => { + if (err) { + console.info("remove file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("File deleted"); + } + }); + ``` + + +## fs.unlinkSync + +unlinkSync(path: string): void + +Synchronously deletes a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.unlinkSync(filePath); + ``` + + +## fs.write + +write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> + +Writes data into a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| --------------------- | -------- | +| Promise<number> | Promise used to return the length of the data written.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.write(file.fd, "hello, world").then((writeLen) => { + console.info("write data to file succeed and size is:" + writeLen); + fs.closeSync(file); + }).catch((err) => { + console.info("write data to file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.write + +write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void + +Writes data into a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| +| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.write(file.fd, "hello, world", (err, writeLen) => { + if (err) { + console.info("write failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("write data to file succeed and size is:" + writeLen); + fs.closeSync(file); + } + }); + ``` + + +## fs.writeSync + +writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number + +Synchronously writes data into a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data written in the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let writeLen = fs.writeSync(file.fd, "hello, world"); + console.info("write data to file succeed and size is:" + writeLen); + fs.closeSync(file); + ``` + +## fs.truncate + +truncate(file: string|number, len?: number): Promise<void> + +Truncates a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| len | number | No | File length, in bytes, after truncation.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let len = 5; + fs.truncate(filePath, len).then(() => { + console.info("File truncated"); + }).catch((err) => { + console.info("truncate file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.truncate + +truncate(file: string|number, len?: number, callback: AsyncCallback<void>): void + +Truncates a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| len | number | No | File length, in bytes, after truncation.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let len = 5; + fs.truncate(filePath, len, (err) => { + if (err) { + console.info("truncate failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("truncate success"); + } + }); + ``` + + +## fs.truncateSync + +truncateSync(file: string|number, len?: number): void + +Synchronously truncates a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| len | number | No | File length, in bytes, after truncation.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let len = 5; + fs.truncateSync(filePath, len); + ``` + + +## fs.readText + +readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<string> + +Reads the text content of a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filePath | string | Yes | Path of the file in the application sandbox. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| Promise<string> | Promise used to return the content read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.readText(filePath).then((str) => { + console.info("readText succeed:" + str); + }).catch((err) => { + console.info("readText failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.readText + +readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<string>): void + +Reads the text content of a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| filePath | string | Yes | Path of the file in the application sandbox. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| +| callback | AsyncCallback<string> | Yes | Callback used to return the content read. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.readText(filePath, { offset: 1, encoding: 'UTF-8' }, (err, str) => { + if (err) { + console.info("read text failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("readText succeed:" + str); + } + }); + ``` + + +## fs.readTextSync + +readTextSync(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): string + +Synchronously reads the text of a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filePath | string | Yes | Path of the file in the application sandbox. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | Promise used to return the content of the file read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let str = fs.readTextSync(filePath, {offset: 1, length: 3}); + console.info("readText succeed:" + str); + ``` + +## fs.lstat + +lstat(path: string): Promise<Stat> + +Obtains information about a symbolic link. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| path | string | Yes | Path of the symbolic link in the application sandbox.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------- | +| Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.lstat(filePath).then((stat) => { + console.info("get link status succeed, the size of file is" + stat.size); + }).catch((err) => { + console.info("get link status failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.lstat + +lstat(path: string, callback: AsyncCallback<Stat>): void + +Obtains information about a symbolic link. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | -------------------------------------- | +| path | string | Yes | Path of the symbolic link in the application sandbox.| +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the symbolic link information obtained. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.lstat(filePath, (err, stat) => { + if (err) { + console.info("lstat failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("get link status succeed, the size of file is" + stat.size); + } + }); + ``` + +## fs.lstatSync + +lstatSync(path: string): Stat + +Obtains information about a symbolic link synchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------- | ---------- | +| [Stat](#stat) | File information obtained.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let stat = fs.lstatSync(filePath); + ``` + +## fs.rename + +rename(oldPath: string, newPath: string): Promise<void> + +Renames a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| oldPath | string | Yes | Path of the file to rename in the application sandbox.| +| newPath | string | Yes | Path of the renamed file in the application sandbox. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fs.rename(srcFile, dstFile).then(() => { + console.info("File renamed"); + }).catch((err) => { + console.info("rename failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.rename + +rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void + +Renames a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------- | +| oldPath | string | Yes | Path of the file to rename in the application sandbox.| +| newPath | string | Yes | Path of the renamed file in the application sandbox. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fs.rename(srcFile, dstFile, (err) => { + if (err) { + console.info("rename failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("rename success"); + } + }); + ``` + +## fs.renameSync + +renameSync(oldPath: string, newPath: string): void + +Synchronously renames a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| oldPath | string | Yes | Path of the file to rename in the application sandbox.| +| newPath | string | Yes | Path of the renamed file in the application sandbox. | + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fs.renameSync(srcFile, dstFile); + ``` + + +## fs.fsync + +fsync(fd: number): Promise<void> + +Flushes data of a file to disk. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fsync(file.fd).then(() => { + console.info("Data flushed"); + }).catch((err) => { + console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.fsync + +fsync(fd: number, callback: AsyncCallback<void>): void + +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------------- | +| fd | number | Yes | FD of the file. | +| Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fsync(file.fd, (err) => { + if (err) { + console.info("fsync failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("fsync success"); + fs.closeSync(file); + } + }); + ``` + + +## fs.fsyncSync + +fsyncSync(fd: number): void + +Flushes data of a file to disk in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fsyncSync(file.fd); + fs.closeSync(file); + ``` + + +## fs.fdatasync + +fdatasync(fd: number): Promise<void> + +Flushes data of a file to disk. This API uses a promise to return the result. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fdatasync(file.fd).then((err) => { + console.info("Data flushed"); + fs.closeSync(file); + }).catch((err) => { + console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.fdatasync + +fdatasync(fd: number, callback: AsyncCallback<void>): void + +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------- | +| fd | number | Yes | FD of the file. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fdatasync (file.fd, (err) => { + if (err) { + console.info("fdatasync failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("fdatasync success"); + fs.closeSync(file); + } + }); + ``` + +## fs.fdatasyncSync + +fdatasyncSync(fd: number): void + +Synchronizes data in a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + let stat = fs.fdatasyncSync(file.fd); + fs.closeSync(file); + ``` + + +## fs.symlink + +symlink(target: string, srcPath: string): Promise<void> + +Creates a symbolic link based on a file path. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| target | string | Yes | Path of the source file in the application sandbox. | +| srcPath | string | Yes | Path of the symbolic link in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fs.symlink(srcFile, dstFile).then(() => { + console.info("Symbolic link created"); + }).catch((err) => { + console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.symlink +symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void + +Creates a symbolic link based on a file path. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------- | +| target | string | Yes | Path of the source file in the application sandbox. | +| srcPath | string | Yes | Path of the symbolic link in the application sandbox. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fs.symlink(srcFile, dstFile, (err) => { + if (err) { + console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("symlink success"); + } + }); + ``` + +## fs.symlinkSync + +symlinkSync(target: string, srcPath: string): void + +Synchronously creates a symbolic link based on a file path. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| target | string | Yes | Path of the source file in the application sandbox. | +| srcPath | string | Yes | Path of the symbolic link in the application sandbox.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fs.symlinkSync(srcFile, dstFile); + ``` + +## fs.mkdtemp + +mkdtemp(prefix: string): Promise<string> + +Creates a temporary directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| Promise<string> | Promise used to return the unique directory generated.| + +**Example** + + ```js + fs.mkdtemp(pathDir + "/XXXXXX").then((pathDir) => { + console.info("mkdtemp succeed:" + pathDir); + }).catch((err) => { + console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.mkdtemp + +mkdtemp(prefix: string, callback: AsyncCallback<string>): void + +Creates a temporary directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------------------- | +| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| +| callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | + +**Example** + + ```js + fs.mkdtemp(pathDir + "/XXXXXX", (err, res) => { + if (err) { + console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("mkdtemp success"); + } + }); + ``` + +## fs.mkdtempSync + +mkdtempSync(prefix: string): string + +Synchronously creates a temporary directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + +**Return value** + +| Type | Description | +| ------ | ---------- | +| string | Unique path generated.| + +**Example** + + ```js + let res = fs.mkdtempSync(pathDir + "/XXXXXX"); + ``` + +## fs.createStream + +createStream(path: string, mode: string): Promise<Stream> + +Opens a file stream based on the file path. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| --------------------------------- | --------- | +| Promise<[Stream](#stream)> | Promise used to return the result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.createStream(filePath, "r+").then((stream) => { + console.info("Stream created"); + }).catch((err) => { + console.info("createStream failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.createStream + +createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void + +Opens a file stream based on the file path. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.createStream(filePath, "r+", (err, stream) => { + if (err) { + console.info("create stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("create stream success"); + } + }); + ``` + +## fs.createStreamSync + +createStreamSync(path: string, mode: string): Stream + +Synchronously opens a stream based on the file path. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| ------------------ | --------- | +| [Stream](#stream) | Stream opened.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + ``` + + +## fs.fdopenStream + +fdopenStream(fd: number, mode: string): Promise<Stream> + +Opens a file stream based on the file descriptor. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| --------------------------------- | --------- | +| Promise<[Stream](#stream)> | Promise used to return the result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fdopenStream(file.fd, "r+").then((stream) => { + console.info("Stream opened"); + fs.closeSync(file); + }).catch((err) => { + console.info("openStream failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.fdopenStream + +fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void + +Opens a file stream based on the file descriptor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + fs.fdopenStream(file.fd, "r+", (err, stream) => { + if (err) { + console.info("fdopen stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("fdopen stream success"); + fs.closeSync(file); + } + }); + ``` + +## fs.fdopenStreamSync + +fdopenStreamSync(fd: number, mode: string): Stream + +Synchronously opens a stream based on the file descriptor. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| ------------------ | --------- | +| [Stream](#stream) | Stream opened.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); + let ss = fs.fdopenStreamSync(file.fd, "r+"); + fs.closeSync(file); + ``` + +## Stat + +Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| | +| mode | number | Yes | No | File permissions. The meaning of each bit is as follows:
- **0o400**: The owner has the read permission on a regular file or a directory entry.
- **0o200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o040**: The user group has the read permission on a regular file or a directory entry.
- **0o020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o004**: Other users have the permission to read a regular file or read a directory entry.
- **0o002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| +| uid | number | Yes | No | ID of the file owner.| +| gid | number | Yes | No | ID of the user group of the file.| +| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. | +| atime | number | Yes | No | Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| mtime | number | Yes | No | Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| ctime | number | Yes | No | Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | + + +### isBlockDevice + +isBlockDevice(): boolean + +Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | ---------------- | +| boolean | Whether the file is a block special file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isBLockDevice = fs.statSync(filePath).isBlockDevice(); + ``` + +### isCharacterDevice + +isCharacterDevice(): boolean + +Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | ----------------- | +| boolean | Whether the file is a character special file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isCharacterDevice = fs.statSync(filePath).isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory(): boolean + +Checks whether this file is a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | ------------- | +| boolean | Whether the file is a directory.| + +**Example** + + ```js + let dirPath = pathDir + "/test"; + let isDirectory = fs.statSync(dirPath).isDirectory(); + ``` + + +### isFIFO + +isFIFO(): boolean + +Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | --------------------- | +| boolean | Whether the file is a FIFO.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isFIFO = fs.statSync(filePath).isFIFO(); + ``` + + +### isFile + +isFile(): boolean + +Checks whether this file is a regular file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | --------------- | +| boolean | Whether the file is a regular file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isFile = fs.statSync(filePath).isFile(); + ``` + + +### isSocket + +isSocket(): boolean + +Checks whether this file is a socket. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | -------------- | +| boolean | Whether the file is a socket.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isSocket = fs.statSync(filePath).isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink(): boolean + +Checks whether this file is a symbolic link. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | --------------- | +| boolean | Whether the file is a symbolic link.| + +**Example** + + ```js + let filePath = pathDir + "/test"; + let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); + ``` + +## Stream + +Provides file stream management. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. + + +### close + +close(): Promise<void> + +Closes the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the stream close result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.close().then(() => { + console.info("File stream closed"); + }).catch((err) => { + console.info("close fileStream failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### close + +close(callback: AsyncCallback<void>): void + +Closes the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.close((err) => { + if (err) { + console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("close stream success"): + } + }); + ``` + +### closeSync + +closeSync(): void + +Synchronously closes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.closeSync(); + ``` + +### flush + +flush(): Promise<void> + +Flushes the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the stream flushing result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.flush().then(() => { + console.info("Stream flushed"); + }).catch((err) => { + console.info("flush failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### flush + +flush(callback: AsyncCallback<void>): void + +Flushes the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.flush((err) => { + if (err) { + console.info("flush stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("flush success"); + } + }); + ``` + +### flushSync + +flushSync(): void + +Synchronously flushes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.flushSync(); + ``` + +### write + +write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> + +Writes data into the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| --------------------- | -------- | +| Promise<number> | Promise used to return the length of the data written.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.write("hello, world",{ offset: 5, length: 5, encoding: 'utf-8' }).then((number) => { + console.info("write succeed and size is:" + number); + }).catch((err) => { + console.info("write failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### write + +write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void + +Writes data into the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| +| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.write("hello, world", { offset: 5, length: 5, encoding :'utf-8'}, (err, bytesWritten) => { + if (err) { + console.info("write stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + if (bytesWritten) { + console.info("write succeed and size is:" + bytesWritten); + } + } + }); + ``` + +### writeSync + +writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number + +Synchronously writes data into the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data written in the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath,"r+"); + let num = ss.writeSync("hello, world", {offset: 5, length: 5, encoding :'utf-8'}); + ``` + +### read + +read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> + +Reads data from the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------ | +| Promise<number> | Promise used to return the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + let buf = new ArrayBuffer(4096); + ss.read(buf, {offset: 5, length: 5}).then((readLen) => { + console.info("Read data successfully"); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + }).catch((err) => { + console.info("read data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### read + +read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback<number>): void + +Reads data from the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.| +| callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + let buf = new ArrayBuffer(4096) + ss.read(buf, {offset: 5, length: 5}, (err, readLen) => { + if (err) { + console.info("read stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("Read data successfully"); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + } + }); + ``` + +### readSync + +readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number + +Synchronously reads data from the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + let num = ss.readSync(new ArrayBuffer(4096), {offset: 5, length: 5}); + ``` + +## File + +Represents a **File** object opened by **open()**. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------- | +| fd | number | Yes | No | FD of the file.| + +## OpenMode + +Defines the constants of the **mode** parameter used in **open()**. It species the mode for opening a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +| Name | Type | Value | Description | +| ---- | ------ |---- | ------- | +| READ_ONLY | number | 0o0 | Open the file in read-only mode.| +| WRITE_ONLY | number | 0o1 | Open the file in write-only mode.| +| READ_WRITE | number | 0o2 | Open the file in read/write mode.| +| CREATE | number | 0o100 | Create a file if the specified file does not exist.| +| TRUNC | number | 0o1000 | If the file exists and is open in write-only or read/write mode, truncate the file length to 0.| +| APPEND | number | 0o2000 | Open the file in append mode. New data will be written to the end of the file.| +| NONBLOCK | number | 0o4000 | If **path** points to a named pipe (FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.| +| DIR | number | 0o200000 | If **path** does not point to a directory, throw an exception.| +| NOFOLLOW | number | 0o400000 | If **path** points to a symbolic link, throw an exception.| +| SYNC | number | 0o4010000 | Open the file in synchronous I/O mode.| diff --git a/en/application-dev/reference/apis/js-apis-file-hash.md b/en/application-dev/reference/apis/js-apis-file-hash.md new file mode 100644 index 0000000000000000000000000000000000000000..fca5de996e882e8a568dd3851512ed5e8be18c9c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-hash.md @@ -0,0 +1,103 @@ +# @ohos.file.hash (File Hash Processing) + +The **fileHash** module implements hash processing on files. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import Hash from '@ohos.file.hash'; +``` + +## Guidelines + +Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows: + +**Stage Model** + + ```js +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + } +} + ``` + +**FA Model** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let context = featureAbility.getContext(); + context.getFilesDir().then((data) => { + let pathDir = data; + }) + ``` + +For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). + +## Hash.hash + +hash(path: string, algorithm: string): Promise<string> + +Calculates a hash value for a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| + +**Return value** + +| Type | Description | +| --------------------- | -------------------------- | +| Promise<string> | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + Hash.hash(filePath, "sha256").then((str) => { + console.info("calculate file hash succeed:" + str); + }).catch((err) => { + console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## Hash.hash + +hash(path: string, algorithm: string, callback: AsyncCallback<string>): void + +Calculates a hash value for a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| +| callback | AsyncCallback<string> | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + +**Example** + ```js + Hash.hash(filePath, "sha256", (err, str) => { + if (err) { + console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("calculate file hash succeed:" + str); + } + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-file-securityLabel.md b/en/application-dev/reference/apis/js-apis-file-securityLabel.md new file mode 100644 index 0000000000000000000000000000000000000000..b9071ecc64025491ed21e55490f4753b83440eb1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -0,0 +1,207 @@ +# @ohos.file.securityLabel (Data Label) + +The **securityLabel** module provides APIs for managing data security levels of files, including obtaining and setting file security levels. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import securityLabel from '@ohos.file.securityLabel'; +``` + +## Guidelines + +Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the file or directory in the application sandbox as follows: + +**Stage Model** + + ```js +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + } +} + ``` + +**FA Model** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let context = featureAbility.getContext(); + context.getFilesDir().then((data) => { + let pathDir = data; + }) + ``` + +For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). + +## securityLabel.setSecurityLabel + +setSecurityLabel(path:string, type:dataLevel):Promise<void> + +Sets a security label for a file in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | Path of the target file. | +| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + securityLabel.setSecurityLabel(path, "s0").then(() => { + console.info("setSecurityLabel successfully"); + }).catch((err) => { + console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## securityLabel.setSecurityLabel + +setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void + +Sets a security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------------------------------------- | +| path | string | Yes | Path of the target file. | +| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + securityLabel.setSecurityLabel(path, "s0", (err) => { + if (err) { + console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("setSecurityLabel successfully."); + } + }); + ``` + +## securityLabel.setSecurityLabelSync + +setSecurityLabelSync(path:string, type:dataLevel):void + +Sets a security label for a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | Path of the target file. | +| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| + +**Example** + +```js +securityLabel.setSecurityLabelSync(path, "s0"); +``` + +## securityLabel.getSecurityLabel + +getSecurityLabel(path:string):Promise<string> + +Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| path | string | Yes | Path of the target file.| + +**Return value** + +| Type | Description | +| --------------------- | ------------ | +| Promise<string> | Security label obtained.| + +**Example** + + ```js + securityLabel.getSecurityLabel(path).then((type) => { + console.log("getSecurityLabel successfully, Label: " + type); + }).catch((err) => { + console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## securityLabel.getSecurityLabel + +getSecurityLabel(path:string, callback:AsyncCallback<string>): void + +Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the security label obtained.| + +**Example** + + ```js + securityLabel.getSecurityLabel(path, (err, type) => { + if (err) { + console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.log("getSecurityLabel successfully, Label: " + type); + } + }); + ``` +## securityLabel.getSecurityLabelSync + +getSecurityLabelSync(path:string):string + +Obtains the security label of a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| path | string | Yes | Path of the target file.| + +**Return value** + +| Type | Description | +| ------ | ------------ | +| string | Security label obtained.| + +**Example** + +```js +let type = securityLabel.getSecurityLabelSync(path); +console.log("getSecurityLabel successfully, Label: " + type); +``` diff --git a/en/application-dev/reference/apis/js-apis-file-statvfs.md b/en/application-dev/reference/apis/js-apis-file-statvfs.md new file mode 100644 index 0000000000000000000000000000000000000000..8241f4734312251f1d4dce13888a2e8ce521ca90 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-statvfs.md @@ -0,0 +1,131 @@ +# @ohos.file.statvfs (File System Space Statistics) + +The **statfs** module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import statvfs from '@ohos.file.statvfs'; +``` +## statvfs.getFreeSize + +getFreeSize(path:string):Promise<number> + +Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| + +**Return value** + +| Type | Description | +| --------------------- | -------------- | +| Promise<number> | Promise used to return the number of free bytes obtained.| + +**Example** + + ```js + let path = "/dev"; + statfs.getFreeSize(path).then((number) => { + console.info("getFreeSize promise successfully, Size: " + number); + }).catch((err) => { + console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## statfs.getFreeSize + +getFreeSize(path:string, callback:AsyncCallback<number>): void + +Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| + +**Example** + + ```js + let path = "/dev"; + statfs.getFreeSize(path, (err, number) => { + if (err) { + console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getFreeSize callback successfully, Size: " + number); + } + }); + ``` + +## statfs.getTotalSize + +getTotalSize(path: string): Promise<number> + +Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| + +**Return value** + +| Type | Description | +| --------------------- | ------------ | +| Promise<number> | Promise used to return the total number of bytes obtained.| + +**Example** + + ```js + let path = "/dev"; + statfs.getTotalSize(path).then((number) => { + console.info("getTotalSize promise successfully, Size: " + number); + }).catch((err) => { + console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## statfs.getTotalSize + +getTotalSize(path: string, callback: AsyncCallback<number>): void + +Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | + +**Example** + + ```js + let path = "/dev"; + statfs.getTotalSize(path, (err, number) => { + if (err) { + console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getTotalSize promise successfully, Size: " + number); + } + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 6d395fd5f21b8b041f7930ae96002dc430fd650b..5a1dcff96d3f5d3c7e2dc1beeb8038e3b68bb46c 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,18 +1,19 @@ # @ohos.multimedia.media (Media) > **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. -This subsystem offers various media services covering audio and video, which provide the following capabilities: +This subsystem offers the following audio and video services: -- Audio playback ([AudioPlayer](#audioplayer)) -- Video playback ([VideoPlayer](#videoplayer8)) -- Audio recording ([AudioRecorder](#audiorecorder)) -- Video recording ([VideoRecorder](#videorecorder9)) - -The following capabilities will be provided in later versions: data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. +- Audio and video playback, implemented by the [AVPlayer](#avplayer9)9+ class. This class has integrated [AudioPlayer](#audioplayerdeprecated)6+ and [VideoPlayer](#videoplayer)8+, with the state machine and error codes upgraded. It is recommended. +- Audio and video recording, implemented by the [AVRecorder](#avrecorder9)9+ class. This class has integrated [AudioRecorder](#audiorecorderdeprecated)6+ and [VideoRecorder](#videorecorder9)9+. It is recommended. +- Audio playback, implemented by the [AudioPlayer](#audioplayerdeprecated)6+ class. It is deprecated. You are advised to use [AVPlayer](#avplayer9)9+. +- Video playback, implemented by the [VideoPlayer](#videoplayerdeprecated)8+ class. It is deprecated. You are advised to use [AVPlayer](#avplayer9)9+. +- Audio recording, implemented by the [AudioRecorder](#audiorecorderdeprecated)6+ class. It is deprecated. You are advised to use [AVRecorder](#avrecorder9)9+. +- Video recording, implemented by the [VideoRecorder](#videorecorder9)9+ class. It is deprecated. You are advised to use [AVRecorder](#avrecorder9)9+. ## Modules to Import @@ -20,113 +21,166 @@ The following capabilities will be provided in later versions: data source audio import media from '@ohos.multimedia.media'; ``` -## media.createAudioPlayer +## media.createAVPlayer9+ -createAudioPlayer(): [AudioPlayer](#audioplayer) +createAVPlayer(callback: AsyncCallback\): void -Creates an **AudioPlayer** instance in synchronous mode. +Creates an **AVPlayer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Return value** +**Parameters** -| Type | Description | -| --------------------------- | ------------------------------------------------------------ | -| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. After the instance is created, you can start, pause, or stop audio playback.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[AVPlayer](#avplayer9)> | Yes | Callback used to return the result. If the operation is successful, an **AVPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to play audio and video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 5400101 | No memory. Return by callback. | **Example** ```js -let audioPlayer = media.createAudioPlayer(); +let avPlayer + +media.createAVPlayer((error, video) => { + if (video != null) { + avPlayer = video; + console.info('createAVPlayer success'); + } else { + console.info(`createAVPlayer fail, error:${error}`); + } +}); ``` -## media.createVideoPlayer8+ +## media.createAVPlayer9+ -createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void +createAVPlayer(): Promise\ -Creates a **VideoPlayer** instance. This API uses an asynchronous callback to return the result. +Creates an **AVPlayer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Parameters** +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise\<[AVPlayer](#avplayer9)> | Promise used to return the result. If the operation is successful, an **AVPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to play audio and video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| +| ID| Error Message | +| -------- | ----------------------------- | +| 5400101 | No memory. Return by promise. | **Example** ```js -let videoPlayer +let avPlayer -media.createVideoPlayer((error, video) => { - if (video != null) { - videoPlayer = video; - console.info('video createVideoPlayer success'); +media.createAVPlayer().then((video) => { + if (video != null) { + avPlayer = video; + console.info('createAVPlayer success'); } else { - console.info(`video createVideoPlayer fail, error:${error}`); + console.info('createAVPlayer fail'); } +}).catch((error) => { + console.info(`AVPlayer catchCallback, error:${error}`); }); ``` -## media.createVideoPlayer8+ +## media.createAVRecorder9+ -createVideoPlayer(): Promise<[VideoPlayer](#videoplayer8)> +createAVRecorder(callback: AsyncCallback\): void -Creates a **VideoPlayer** instance. This API uses a promise to return the result. +Creates an **AVRecorder** instance. This API uses an asynchronous callback to return the result. +Only one **AVRecorder** instance can be created per device. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -**Return value** +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[AVRecorder](#avrecorder9)> | Yes | Callback used to return the result. If the operation is successful, an **AVRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio and video.| -| Type | Description | -| ------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 5400101 | No memory. Return by callback. | **Example** ```js -let videoPlayer +let avRecorder -media.createVideoPlayer().then((video) => { - if (video != null) { - videoPlayer = video; - console.info('video createVideoPlayer success'); +media.createAVRecorder((error, recorder) => { + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); } else { - console.info('video createVideoPlayer fail'); + console.info(`createAVRecorder fail, error:${error}`); } -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); }); ``` -## media.createAudioRecorder +## media.createAVRecorder9+ -createAudioRecorder(): AudioRecorder +createAVRecorder(): Promise\ -Creates an **AudioRecorder** instance to control audio recording. -Only one **AudioRecorder** instance can be created per device. +Creates an **AVRecorder** instance. This API uses a promise to return the result. +Only one **AVRecorder** instance can be created per device. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------------------ | -| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio.| +| Type | Description | +| ------------------------------------ | ------------------------------------------------------------ | +| Promise\<[AVRecorder](#avrecorder9)> | Promise used to return the result. If the operation is successful, an **AVRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio and video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------- | +| 5400101 | No memory. Return by promise. | **Example** ```js -let audioRecorder = media.createAudioRecorder(); +let avRecorder + +media.createAVRecorder().then((recorder) => { + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info('createAVRecorder fail'); + } +}).catch((error) => { + console.info(`createAVRecorder catchCallback, error:${error}`); +}); ``` ## media.createVideoRecorder9+ -createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): void +createVideoRecorder(callback: AsyncCallback\): void Creates a **VideoRecorder** instance. This API uses an asynchronous callback to return the result. -Only one **AudioRecorder** instance can be created per device. +Only one **VideoRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -134,9 +188,9 @@ Only one **AudioRecorder** instance can be created per device. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, a **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| **Error codes** @@ -163,10 +217,10 @@ media.createVideoRecorder((error, video) => { ## media.createVideoRecorder9+ -createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)> +createVideoRecorder(): Promise\ Creates a **VideoRecorder** instance. This API uses a promise to return the result. -Only one **AudioRecorder** instance can be created per device. +Only one **VideoRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -176,7 +230,7 @@ Only one **AudioRecorder** instance can be created per device. | Type | Description | | ----------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| +| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, a **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| **Error codes** @@ -203,26 +257,24 @@ media.createVideoRecorder().then((video) => { }); ``` +## AVErrorCode9+ - -## MediaErrorCode8+ - -Enumerates the media error codes. +Enumerates the [media error codes](../errorcodes/errorcode-media.md). **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Value | Description | -| -------------------------- | ---- | -------------------------------------- | -| MSERR_OK | 0 | The operation is successful. | -| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| -| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation. | -| MSERR_INVALID_VAL | 3 | Invalid input parameter. | -| MSERR_IO | 4 | An I/O error occurs. | -| MSERR_TIMEOUT | 5 | The operation times out. | -| MSERR_UNKNOWN | 6 | An unknown error occurs. | -| MSERR_SERVICE_DIED | 7 | Invalid server. | -| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state. | -| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version. | +| Name | Value | Description | +| :------------------------- | ------- | ------------------------------------ | +| AVERR_OK | 0 | The operation is successful. | +| AVERR_NO_PERMISSION | 201 | You do not have the permission to perform the operation. | +| AVERR_INVALID_PARAMETER | 401 | Invalid input parameter. | +| AVERR_UNSUPPORT_CAPABILITY | 801 | Unsupported API. | +| AVERR_NO_MEMORY | 5400101 | The system memory is insufficient or the number of services reaches the upper limit.| +| AVERR_OPERATE_NOT_PERMIT | 5400102 | The operation is not allowed in the current state or you do not have the permission to perform the operation.| +| AVERR_IO | 5400103 | The data stream is abnormal. | +| AVERR_TIMEOUT | 5400104 | The system or network response times out. | +| AVERR_SERVICE_DIED | 5400105 | The service process is dead. | +| AVERR_UNSUPPORT_FORMAT | 5400106 | The format of the media asset is not supported. | ## MediaType8+ @@ -284,1120 +336,1083 @@ Enumerates the buffering event types. | BUFFERING_PERCENT | 3 | Buffering progress, in percent. | | CACHED_DURATION | 4 | Cache duration, in ms.| -## AudioPlayer +## StateChangeReason9+ -Provides APIs to manage and play audio. Before calling an API of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. +Enumerates the reasons for the state transition of the **AVPlayer** or **AVRecorder** instance. The enum value is reported together with **state**. -For details about the audio playback demo, see [Audio Playback Development](../../media/audio-playback.md). +**System capability**: SystemCapability.Multimedia.Media.Core -### Attributes +| Name | Value | Description | +| ---------- | ---- | ------------------------------------------------------------ | +| USER | 1 | State transition triggered by user behavior. It happens when a user or the client calls an API.| +| BACKGROUND | 2 | State transition caused by system behavior. For example, if an application does not have the permission of Media Controller, the application is forcibly suspended or stopped by the system when it switches to the background.| -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +## AVPlayer9+ -| Name | Type | Readable| Writable| Description | -| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent music file, use **src=fd://xx**.
| -| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | -| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | -| currentTime | number | Yes | No | Current audio playback position, in ms. | -| duration | number | Yes | No | Audio duration, in ms. | -| state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| -### play +A playback management class that provides APIs to manage and play media assets. Before calling any API in **AVPlayer**, you must use [createAVPlayer()](#mediacreateavplayer9) to create an **AVPlayer** instance. -play(): void +For details about the AVPlayer demo, see [AVPlayer Development](../../media/avplayer-playback.md). -Starts to play audio resources. This API can be called only after the [dataLoad](#audioplayer_on) event is triggered. +### Attributes -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Example** +| Name | Type | Readable| Writable| Description | +| --------------------------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| url9+ | string | Yes | Yes | URL of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| +| surfaceId9+ | string | Yes | Yes | Video window ID. By default, there is no video window. It is a static attribute and can be set only when the AVPlayer is in the initialized state.
It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.
**Example:**
[Create a surface ID through XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| +| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scaling type. The default value is **VIDEO_SCALE_TYPE_FIT_CROP**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| audioRendererInfo10+ | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | Yes | Yes | Audio renderer information. The default value of **contentType** is **CONTENT_TYPE_MUSIC**, and the default value of **streamUsage** is **STREAM_USAGE_MEDIA**.
It can be set only when the AVPlayer is in the initialized state.| +| state9+ | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state. | +| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.| +| duration9+ | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live streaming scenarios, **-1** is returned by default.| +| width9+ | number | Yes | No | Video width, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| +| height9+ | number | Yes | No | Video height, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| -```js -audioPlayer.on('play', () => { // Set the 'play' event callback. - console.log('audio play success'); -}); -audioPlayer.play(); -``` +### on('stateChange')9+ -### pause +on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void -pause(): void +Subscribes to AVPlayer state changes. -Pauses audio playback. +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| +| callback | function | Yes | Callback invoked when the event is triggered. It reports the following information:
state: [AVPlayerState](#avplayerstate9), indicating the AVPlayer state.
reason: [StateChangeReason](#statechangereason9), indicating the reason for the state transition.| **Example** ```js -audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.log('audio pause success'); -}); -audioPlayer.pause(); +avPlayer.on('stateChange', async (state, reason) => { + switch (state) { + case 'idle': + console.info('state idle called') + break; + case 'initialized': + console.info('initialized prepared called') + break; + case 'prepared': + console.info('state prepared called') + break; + case 'playing': + console.info('state playing called') + break; + case 'paused': + console.info('state paused called') + break; + case 'completed': + console.info('state completed called') + break; + case 'stopped': + console.info('state stopped called') + break; + case 'released': + console.info('state released called') + break; + case 'error': + console.info('state error called') + break; + default: + console.info('unkown state :' + state) + break; + } +}) ``` -### stop +### off('stateChange')9+ -stop(): void +off(type: 'stateChange'): void -Stops audio playback. +Unsubscribes from AVPlayer state changes. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------- | +| type | string | Yes | Event type, which is **'stateChange'** in this case.| **Example** ```js -audioPlayer.on('stop', () => { // Set the 'stop' event callback. - console.log('audio stop success'); -}); -audioPlayer.stop(); +avPlayer.off('stateChange') ``` -### reset7+ +### on('error')9+ -reset(): void +on(type: 'error', callback: ErrorCallback): void -Resets the audio asset to be played. +Subscribes to AVPlayer errors. This event is used only for error prompt and does not require the user to stop playback control. If the [AVPlayer state](#avplayerstate9) is also switched to error, call **reset()** or **release()** to exit the playback. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.| +| callback | function | Yes | Callback used to return the error code ID and error message.| + +The AVPlayer provides the following error types: + +| ID| Error Message | Description | +| -------- | --------------------- | ------------------------------------------------------------ | +| 201 | No Permission: | No permission to perform the operation. The [AVPlayer state](#avplayerstate9) is error.| +| 401 | Invalid Parameter: | Incorrect input parameter, causing an invalid call. | +| 801 | Unsupport Capability: | Unsupported API, causing an invalid call. | +| 5400101 | No Memory: | Insufficient memory. The [AVPlayer state](#avplayerstate9) is error.| +| 5400102 | Operate Not Permit: | Unsupported operation in the current state, causing an invalid call. | +| 5400103 | IO Error: | Abnormal stream. | +| 5400104 | Network Timeout: | The response times out due to a network error. The [AVPlayer state](#avplayerstate9) is error.| +| 5400105 | Service Died: | The playback process is dead. The [AVPlayer state](#avplayerstate9) is error.| +| 5400106 | Unsupport Format: | Unsupported file format. The [AVPlayer state](#avplayerstate9) is error.| **Example** ```js -audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.log('audio reset success'); -}); -audioPlayer.reset(); +avPlayer.on('error', (error) => { + console.info('error happened,and error message is :' + error.message) + console.info('error happened,and error code is :' + error.code) +}) ``` -### seek +### off('error')9+ -seek(timeMs: number): void +off(type: 'error'): void -Seeks to the specified playback position. +Unsubscribes from AVPlayer errors. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ----------------------------------------------------------- | -| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------- | +| type | string | Yes | Event type, which is **'error'** in this case.| **Example** ```js -audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (seekDoneTime == null) { - console.info('audio seek fail'); - return; - } - console.log('audio seek success. seekDoneTime: ' + seekDoneTime); -}); -audioPlayer.seek(30000); // Seek to 30000 ms. +avPlayer.off('error') ``` -### setVolume +### prepare9+ -setVolume(vol: number): void +prepare(callback: AsyncCallback\): void -Sets the volume. +Prepares for audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the initialized state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------- | +| callback | function | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400106 | Unsupport format. Return by callback. | **Example** ```js -audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.log('audio volumeChange success'); -}); -audioPlayer.setVolume(1); // Set the volume to 100%. +avPlayer.prepare((err) => { + if (err == null) { + console.info('prepare success'); + } else { + console.error('prepare filed,error message is :' + err.message) + } +}) ``` -### release +### prepare9+ -release(): void +prepare(): Promise\ -Releases the audio playback resource. +Prepares for audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the initialized state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400106 | Unsupport format. Return by promise. | **Example** ```js -audioPlayer.release(); -audioPlayer = undefined; +avPlayer.prepare().then(() => { + console.info('prepare success'); +}, (err) => { + console.error('prepare filed,error message is :' + err.message) +}) ``` -### getTrackDescription8+ +### play9+ -getTrackDescription(callback: AsyncCallback>): void +play(callback: AsyncCallback\): void -Obtains the audio track information. This API uses an asynchronous callback to return the result. It can be called only after the [dataLoad](#audioplayer_on) event is triggered. +Starts to play an audio and video asset. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, paused, or completed state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | -| callback | AsyncCallback> | Yes | Callback used to return a **MediaDescription** array, which records the audio track information.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------- | +| callback | function | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **Example** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } -} - -audioPlayer.getTrackDescription((error, arrList) => { - if (arrList != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } +avPlayer.play((err) => { + if (err == null) { + console.info('play success'); } else { - console.log(`audio getTrackDescription fail, error:${error}`); + console.error('play filed,error message is :' + err.message) } -}); +}) ``` -### getTrackDescription8+ +### play9+ -getTrackDescription(): Promise> +play(): Promise\ -Obtains the audio track information. This API uses a promise to return the result. It can be called only after the [dataLoad](#audioplayer_on) event is triggered. +Starts to play an audio and video asset. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, paused, or completed state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Return value** -| Type | Description | -| ------------------------------------------------------ | ----------------------------------------------- | -| Promise> | Promise used to return a **MediaDescription** array, which records the audio track information.| +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **Example** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } -} -let arrayDescription = null -audioPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('audio getTrackDescription fail'); - } -}).catch((error) => { - console.info(`audio catchCallback, error:${error}`); -}); - -for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); -} +avPlayer.play().then(() => { + console.info('play success'); +}, (err) => { + console.error('play filed,error message is :' + err.message) +}) ``` -### on('bufferingUpdate')8+ +### pause9+ -on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void +pause(callback: AsyncCallback\): void -Subscribes to the audio buffering update event. This API works only under online playback. +Pauses audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the playing state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | -| callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------- | +| callback | function | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **Example** ```js -audioPlayer.on('bufferingUpdate', (infoType, value) => { - console.log('audio bufferingInfo type: ' + infoType); - console.log('audio bufferingInfo value: ' + value); -}); +avPlayer.pause((err) => { + if (err == null) { + console.info('pause success'); + } else { + console.error('pause filed,error message is :' + err.message) + } +}) ``` - ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') +### pause9+ -on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void +pause(): Promise\ -Subscribes to the audio playback events. +Pauses audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the playing state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed.| -| callback | () => void | Yes | Callback invoked when the event is triggered. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**Example** +**Error codes** -```js -import fileio from '@ohos.fileio' +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. -audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. - console.info('audio set source success'); - audioPlayer.play(); // Start the playback and trigger the 'play' event callback. -}); -audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); - audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. -}); -audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.info('audio pause success'); - audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. -}); -audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.info('audio reset success'); - audioPlayer.release(); // Release the AudioPlayer instance. - audioPlayer = undefined; -}); -audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (seekDoneTime == null) { - console.info('audio seek fail'); - return; - } - console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. -}); -audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.info('audio volumeChange success'); - audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. -}); -audioPlayer.on('finish', () => { // Set the 'finish' event callback. - console.info('audio play finish'); - audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. -}); -audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); -}); +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | -// Set the FD (local playback) of the video file selected by the user. -let fdPath = 'fd://'; -// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. -let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; -fileio.open(path).then((fdValue) => { - fdPath = fdPath + '' + fdValue; - console.info('open fd success fd is' + fdPath); +**Example** + +```js +avPlayer.pause().then(() => { + console.info('pause success'); }, (err) => { - console.info('open fd failed err is' + err); -}).catch((err) => { - console.info('open fd failed err is' + err); -}); -audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. + console.error('pause filed,error message is :' + err.message) +}) ``` -### on('timeUpdate') +### stop9+ -on(type: 'timeUpdate', callback: Callback\): void +stop(callback: AsyncCallback\): void -Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress. +Stops audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'timeUpdate'** in this case.
The **'timeUpdate'** event is triggered when the audio playback starts after an audio playback timestamp update.| -| callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter is the updated timestamp. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------- | +| callback | function | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **Example** ```js -audioPlayer.on('timeUpdate', (newTime) => { // Set the 'timeUpdate' event callback. - if (newTime == null) { - console.info('audio timeUpadate fail'); - return; +avPlayer.stop((err) => { + if (err == null) { + console.info('stop success'); + } else { + console.error('stop filed,error message is :' + err.message) } - console.log('audio timeUpadate success. seekDoneTime: ' + newTime); -}); -audioPlayer.play(); // The 'timeUpdate' event is triggered when the playback starts. +}) ``` -### on('error') +### stop9+ -on(type: 'error', callback: ErrorCallback): void +stop(): Promise\ -Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback. +Stops audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during audio playback.| -| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **Example** ```js -audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); -}); -audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. +avPlayer.stop().then(() => { + console.info('stop success'); +}, (err) => { + console.error('stop filed,error message is :' + err.message) +}) ``` -## AudioState - -Enumerates the audio playback states. You can obtain the state through the **state** attribute. +### reset9+ -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer +reset(callback: AsyncCallback\): void -| Name | Type | Description | -| ------- | ------ | ---------------------------------------------- | -| idle | string | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| -| playing | string | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | -| paused | string | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | -| stopped | string | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | -| error | string | Audio playback is in the error state. | +Resets audio and video playback. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the initialized, prepared, playing, paused, completed, stopped, or error state. -## AVFileDescriptor9+ +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -Describes audio and video file resources. It is used to specify a particular resource for playback based on its offset and length within a file. +**Parameters** -**System capability**: SystemCapability.Multimedia.Media.Core +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------- | +| callback | function | Yes | Callback used to return the result.| -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| fd | number | Yes | Resource handle, which is obtained by calling **resourceManager.getRawFileDescriptor**. | -| offset | number | Yes | Resource offset, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.| -| length | number | Yes | Resource length, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.| +**Error codes** -## VideoPlayer8+ +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must use [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | -For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). +**Example** -### Attributes +```js +avPlayer.reset((err) => { + if (err == null) { + console.info('reset success'); + } else { + console.error('reset filed,error message is :' + err.message) + } +}) +``` -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +### reset9+ -| Name | Type | Readable| Writable| Description | -| ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
| -| loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | -| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | -| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | -| currentTime8+ | number | Yes | No | Current video playback position, in ms. | -| duration8+ | number | Yes | No | Video duration, in ms. The value **-1** indicates the live mode. | -| state8+ | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state. | -| width8+ | number | Yes | No | Video width, in pixels. | -| height8+ | number | Yes | No | Video height, in pixels. | +reset(): Promise\ -### setDisplaySurface8+ +Resets audio and video playback. This API uses a promise to return the result. It can be called only when the AVPlayer is in the initialized, prepared, playing, paused, completed, stopped, or error state. -setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -Sets **SurfaceId**. This API uses an asynchronous callback to return the result. +**Return value** -*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**Error codes** -**Parameters** +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------------- | -| surfaceId | string | Yes | Surface ID to set. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **Example** ```js -let surfaceId = null; -videoPlayer.setDisplaySurface(surfaceId, (err) => { - if (err == null) { - console.info('setDisplaySurface success!'); - } else { - console.info('setDisplaySurface fail!'); - } -}); +avPlayer.reset().then(() => { + console.info('reset success'); +}, (err) => { + console.error('reset filed,error message is :' + err.message) +}) ``` -### setDisplaySurface8+ - -setDisplaySurface(surfaceId: string): Promise\ +### release9+ -Sets **SurfaceId**. This API uses a promise to return the result. +release(callback: AsyncCallback\): void -*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. +Releases the playback resources. This API uses an asynchronous callback to return the result. It can be called when the AVPlayer is in any state except released. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------- | -| surfaceId | string | Yes | Surface ID to set.| - -**Return value** - -| Type | Description | -| -------------- | ------------------------------ | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -let surfaceId = null; -videoPlayer.setDisplaySurface(surfaceId).then(() => { - console.info('setDisplaySurface success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); -``` - -### prepare8+ - -prepare(callback: AsyncCallback\): void +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------- | +| callback | function | Yes | Callback used to return the result.| -Prepares for video playback. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**Error codes** -**Parameters** +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **Example** ```js -videoPlayer.prepare((err) => { +avPlayer.release((err) => { if (err == null) { - console.info('prepare success!'); + console.info('reset success'); } else { - console.info('prepare fail!'); + console.error('release filed,error message is :' + err.message) } -}); +}) ``` -### prepare8+ +### release9+ -prepare(): Promise\ +release(): Promise\ -Prepares for video playback. This API uses a promise to return the result. +Releases the playback resources. This API uses a promise to return the result. It can be called when the AVPlayer is in any state except released. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Return value** -| Type | Description | -| -------------- | ----------------------------- | +| Type | Description | +| -------------- | ------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | + **Example** ```js -videoPlayer.prepare().then(() => { - console.info('prepare success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.release().then(() => { + console.info('release success'); +}, (err) => { + console.error('release filed,error message is :' + err.message) +}) ``` -### play8+ +### getTrackDescription9+ -play(callback: AsyncCallback\): void; +getTrackDescription(callback: AsyncCallback\>): void -Starts to play video resources. This API uses an asynchronous callback to return the result. +Obtains the audio and video track information. This API uses an asynchronous callback to return the result. It can be called only when the AVPlayer is in the prepared, playing, or paused state. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | +| callback | AsyncCallback> | Yes | Callback used to return a **MediaDescription** array, which records the audio and video track information.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | **Example** ```js -videoPlayer.play((err) => { - if (err == null) { - console.info('play success!'); +avPlayer.getTrackDescription((error, arrList) => { + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); + } } else { - console.info('play fail!'); + console.log(`video getTrackDescription fail, error:${error}`); } }); ``` -### play8+ +### getTrackDescription9+ -play(): Promise\; +getTrackDescription(): Promise\> -Starts to play video resources. This API uses a promise to return the result. +Obtains the audio and video track information. This API uses a promise to return the result. It can be called only when the AVPlayer is in the prepared, playing, or paused state. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Return value** -| Type | Description | -| -------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------- | +| Promise> | Promise used to return a **MediaDescription** array, which records the audio and video track information.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | **Example** ```js -videoPlayer.play().then(() => { - console.info('play success'); +let arrayDescription; +avPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('video getTrackDescription fail'); + } }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.info(`video catchCallback, error:${error}`); }); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} ``` -### pause8+ +### seek9+ -pause(callback: AsyncCallback\): void +seek(timeMs: number, mode?:SeekMode): void -Pauses video playback. This API uses an asynchronous callback to return the result. +Seeks to the specified playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the seek operation takes effect by subscribing to the [seekDone](#seekDone_on) event. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, [duration](#avplayer_duration)].| +| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. **Set this parameter only for video playback.** | **Example** ```js -videoPlayer.pause((err) => { - if (err == null) { - console.info('pause success!'); - } else { - console.info('pause fail!'); - } -}); +let seekTime = 1000 +avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC) ``` -### pause8+ +### on('seekDone')9+ -pause(): Promise\ +on(type: 'seekDone', callback: Callback\): void -Pauses video playback. This API uses a promise to return the result. +Subscribes to the event to check whether the seek operation takes effect. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'seekDone'** in this case. This event is triggered each time **seek()** is called.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. It reports the time position requested by the user.
For video playback, [SeekMode](#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** attribute. The time in this callback only means that the requested seek operation is complete.| **Example** ```js -videoPlayer.pause().then(() => { - console.info('pause success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.on('seekDone', (seekDoneTime:number) => { + console.info('seekDone success,and seek time is:' + seekDoneTime) +}) ``` -### stop8+ +### off('seekDone')9+ -stop(callback: AsyncCallback\): void +off(type: 'seekDone'): void -Stops video playback. This API uses an asynchronous callback to return the result. +Unsubscribes from the event that checks whether the seek operation takes effect. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------------------- | +| type | string | Yes | Event type, which is **'seekDone'** in this case.| **Example** ```js -videoPlayer.stop((err) => { - if (err == null) { - console.info('stop success!'); - } else { - console.info('stop fail!'); - } -}); +avPlayer.off('seekDone') ``` -### stop8+ +### setSpeed9+ -stop(): Promise\ +setSpeed(speed: PlaybackSpeed): void -Stops video playback. This API uses a promise to return the result. +Sets the playback speed. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [speedDone](#speedDone_on) event. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ------------------ | +| speed | [PlaybackSpeed](#playbackspeed8) | Yes | Playback speed to set.| **Example** ```js -videoPlayer.stop().then(() => { - console.info('stop success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.setSpeed(media.AVPlayerSpeed.SPEED_FORWARD_2_00_X) ``` -### reset8+ +### on('speedDone')9+ -reset(callback: AsyncCallback\): void +on(type: 'speedDone', callback: Callback\): void -Resets the video asset to be played. This API uses an asynchronous callback to return the result. +Subscribes to the event to check whether the playback speed is successfully set. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'speedDone'** in this case. This event is triggered each time **setSpeed()** is called.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. It reports the speed set. For details, see [PlaybackSpeed](#playbackspeed8).| **Example** ```js -videoPlayer.reset((err) => { - if (err == null) { - console.info('reset success!'); - } else { - console.info('reset fail!'); - } -}); +avPlayer.on('speedDone', (speed:number) => { + console.info('speedDone success,and speed value is:' + speed) +}) ``` -### reset8+ +### off('speedDone')9+ -reset(): Promise\ +off(type: 'speedDone'): void -Resets the video asset to be played. This API uses a promise to return the result. +Unsubscribes from the event that checks whether the playback speed is successfully set. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------------------------------------------- | +| type | string | Yes | Event type, which is **'speedDone'** in this case.| **Example** ```js -videoPlayer.reset().then(() => { - console.info('reset success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.off('speedDone') ``` -### seek8+ +### setBitrate9+ -seek(timeMs: number, callback: AsyncCallback\): void +setBitrate(bitrate: number): void -Seeks to the specified playback position. The next key frame at the specified position is played. This API uses an asynchronous callback to return the result. +Sets the bit rate, which is valid only for HTTP Live Streaming (HLS) streams. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [bitrateDone](#bitrateDone_on) event. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| bitrate | number | Yes | Bit rate to set. You can obtain the available bit rates of the current HLS stream by subscribing to the [availableBitrates](#availableBitrates_on) event. If the bit rate to set is not in the list of the available bit rates, the AVPlayer selects from the list the minimum bit rate that is closed to the bit rate to set.| **Example** ```js -let seekTime = 5000; -videoPlayer.seek(seekTime, (err, result) => { - if (err == null) { - console.info('seek success!'); - } else { - console.info('seek fail!'); - } -}); +let bitrate = 96000 +avPlayer.setBitrate(bitrate) ``` -### seek8+ +### on('bitrateDone')9+ -seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void +on(type: 'bitrateDone', callback: Callback\): void -Seeks to the specified playback position. This API uses an asynchronous callback to return the result. +Subscribes to the event to check whether the bit rate is successfully set. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| -| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'bitrateDone'** in this case. This event is triggered each time **setBitrate()** is called.| +| callback | function | Yes | Callback invoked when the event is triggered. It reports the effective bit rate. | **Example** ```js -import media from '@ohos.multimedia.media' -let seekTime = 5000; -videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => { - if (err == null) { - console.info('seek success!'); - } else { - console.info('seek fail!'); - } -}); +avPlayer.on('bitrateDone', (bitrate:number) => { + console.info('bitrateDone success,and bitrate value is:' + bitrate) +}) ``` -### seek8+ +### off('bitrateDone')9+ -seek(timeMs: number, mode?:SeekMode): Promise\ +off(type: 'bitrateDone'): void -Seeks to the specified playback position. If **mode** is not specified, the next key frame at the specified position is played. This API uses a promise to return the result. +Unsubscribes from the event that checks whether the bit rate is successfully set. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------- | ---- | ------------------------------------------------------------ | -| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| -| mode | [SeekMode](#seekmode8) | No | Seek mode. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'bitrateDone'** in this case| -**Return value** +**Example** -| Type | Description | -| -------------- | ------------------------------------------- | -| Promise\| Promise used to return the playback position, in ms.| +```js +avPlayer.off('bitrateDone') +``` + +### on('availableBitrates')9+ + +on(type: 'availableBitrates', callback: (bitrates: Array\) => void): void + +Subscribes to available bit rates of HLS streams. This event is reported only after the AVPlayer switches to the prepared state. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.| +| callback | function | Yes | Callback invoked when the event is triggered. It returns an array that holds the available bit rates.| **Example** ```js -import media from '@ohos.multimedia.media' -let seekTime = 5000; -videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. - console.info('seek success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); - -videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { - console.info('seek success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.on('availableBitrates', (bitrates: Array) => { + console.info('availableBitrates success,and availableBitrates length is:' + bitrates.length) +}) ``` -### setVolume8+ +### off('availableBitrates')9+ -setVolume(vol: number, callback: AsyncCallback\): void +off(type: 'availableBitrates'): void -Sets the volume. This API uses an asynchronous callback to return the result. +Unsubscribes from available bit rates of HLS streams. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'availableBitrates'** in this case.| **Example** ```js -let vol = 0.5; -videoPlayer.setVolume(vol, (err, result) => { - if (err == null) { - console.info('setVolume success!'); - } else { - console.info('setVolume fail!'); - } -}); +avPlayer.off('availableBitrates') ``` -### setVolume8+ +### setVolume9+ -setVolume(vol: number): Promise\ +setVolume(volume: number): void -Sets the volume. This API uses a promise to return the result. +Sets the volume. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [volumeChange](#volumeChange_on) event. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| - -**Return value** - -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| volume | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| **Example** ```js -let vol = 0.5; -videoPlayer.setVolume(vol).then(() => { - console.info('setVolume success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +let volume = 1.0 +avPlayer.setVolume(volume) ``` -### release8+ +### on('volumeChange')9+ -release(callback: AsyncCallback\): void +on(type: 'volumeChange', callback: Callback\): void -Releases the video playback resource. This API uses an asynchronous callback to return the result. +Subscribes to the event to check whether the volume is successfully set. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'volumeChange'** in this case. This event is triggered each time **setVolume()** is called.| +| callback | function | Yes | Callback invoked when the event is triggered. It reports the effective volume. | **Example** ```js -videoPlayer.release((err) => { - if (err == null) { - console.info('release success!'); - } else { - console.info('release fail!'); - } -}); +avPlayer.on('volumeChange', (vol:number) => { + console.info('volumeChange success,and new volume is :' + vol) +}) ``` -### release8+ +### off('volumeChange')9+ -release(): Promise\ +off(type: 'volumeChange'): void -Releases the video playback resource. This API uses a promise to return the result. +Unsubscribes from the event that checks whether the volume is successfully set. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'volumeChange'** in this case.| **Example** ```js -videoPlayer.release().then(() => { - console.info('release success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.off('volumeChange') ``` -### getTrackDescription8+ +### on('endOfStream')9+ -getTrackDescription(callback: AsyncCallback>): void +on(type: 'endOfStream', callback: Callback\): void -Obtains the video track information. This API uses an asynchronous callback to return the result. +Subscribes to the event that indicates the end of the stream being played. If **loop=1** is set, the AVPlayer seeks to the beginning of the stream and plays the stream again. If **loop** is not set, the completed state is reported through the [stateChange](#stateChange_on) event. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | -| callback | AsyncCallback> | Yes | Callback used to return a **MediaDescription** array, which records the video track information.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'endOfStream'** in this case. This event is triggered when the AVPlayer finishes playing the media asset.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('video key is ' + item); - console.info('video value is ' + property); - } -} - -videoPlayer.getTrackDescription((error, arrList) => { - if ((arrList) != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } - } else { - console.log(`video getTrackDescription fail, error:${error}`); - } -}); +avPlayer.on('endOfStream', () => { + console.info('endOfStream success') +}) ``` -### getTrackDescription8+ +### off('endOfStream')9+ -getTrackDescription(): Promise> +off(type: 'endOfStream'): void -Obtains the video track information. This API uses a promise to return the result. +Unsubscribes from the event that indicates the end of the stream being played. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer -**Return value** +**Parameters** -| Type | Description | -| ------------------------------------------------------ | ----------------------------------------------- | -| Promise> | Promise used to return a **MediaDescription** array, which records the video track information.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'endOfStream'** in this case.| **Example** ```js -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('video key is ' + item); - console.info('video value is ' + property); - } -} - -let arrayDescription; -videoPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('video getTrackDescription fail'); - } -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); -for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); -} +avPlayer.off('endOfStream') ``` -### setSpeed8+ +### on('timeUpdate')9+ -setSpeed(speed:number, callback: AsyncCallback\): void +on(type: 'timeUpdate', callback: Callback\): void -Sets the video playback speed. This API uses an asynchronous callback to return the result. +Subscribes to playback position changes. It is used to refresh the current position of the progress bar. By default, this event is reported every 1 second. However, it is reported immediately upon a successful seek operation. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------------------------------------------------- | -| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ---------------------------------------------- | +| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| +| callback | function | Yes | Callback invoked when the event is triggered. It reports the current playback position, in ms. | **Example** ```js -import media from '@ohos.multimedia.media' -let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; - -videoPlayer.setSpeed(speed, (err, result) => { - if (err == null) { - console.info('setSpeed success!'); - } else { - console.info('setSpeed fail!'); - } -}); +avPlayer.on('timeUpdate', (time:number) => { + console.info('timeUpdate success,and new time is :' + time) +}) ``` -### setSpeed8+ +### off('timeUpdate')9+ -setSpeed(speed:number): Promise\ +off(type: 'timeUpdate'): void -Sets the video playback speed. This API uses a promise to return the result. +Unsubscribes from playback position changes. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------------------------------------- | -| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------------------- | +| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| -**Return value** +**Example** -| Type | Description | -| ---------------- | ------------------------------------------------------------ | -| Promise\| Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +```js +avPlayer.off('timeUpdate') +``` + +### on('durationUpdate')9+ + +on(type: 'durationUpdate', callback: Callback\): void + +Subscribes to media asset duration changes. It is used to refresh the length of the progress bar. By default, this event is reported once when the AVPlayer switches to the prepared state. However, it can be repeatedly reported for special streams that trigger duration changes. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | -------------------------------------------------- | +| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| +| callback | function | Yes | Callback invoked when the event is triggered. It reports the media asset duration, in ms. | **Example** ```js -import media from '@ohos.multimedia.media' -let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; - -videoPlayer.setSpeed(speed).then(() => { - console.info('setSpeed success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); +avPlayer.on('durationUpdate', (duration) => { + console.info('durationUpdate success,new duration is :' + duration) +}) ``` -### on('playbackCompleted')8+ +### off('durationUpdate')9+ -on(type: 'playbackCompleted', callback: Callback\): void +off(type: 'durationUpdate'): void -Subscribes to the video playback completion event. +Unsubscribes from media asset duration changes. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | Yes | Event type, which is **'playbackCompleted'** in this case.| -| callback | function | Yes | Callback invoked when the event is triggered. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------ | +| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| **Example** ```js -videoPlayer.on('playbackCompleted', () => { - console.info('playbackCompleted success!'); -}); +avPlayer.off('durationUpdate') ``` -### on('bufferingUpdate')8+ +### on('bufferingUpdate')9+ on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void -Subscribes to the video buffering update event. Only network playback supports this subscription. +Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** @@ -1409,122 +1424,189 @@ Subscribes to the video buffering update event. Only network playback supports t **Example** ```js -videoPlayer.on('bufferingUpdate', (infoType, value) => { - console.log('video bufferingInfo type: ' + infoType); - console.log('video bufferingInfo value: ' + value); -}); +avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { + console.info('bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value) +}) ``` -### on('startRenderFrame')8+ +### off('bufferingUpdate')9+ -on(type: 'startRenderFrame', callback: Callback\): void +off(type: 'bufferingUpdate'): void -Subscribes to the frame rendering start event. +Unsubscribes from audio and video buffer changes. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------------------------------------------- | +| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case.| **Example** ```js -videoPlayer.on('startRenderFrame', () => { - console.info('startRenderFrame success!'); -}); +avPlayer.off('bufferingUpdate') ``` -### on('videoSizeChanged')8+ +### on('startRenderFrame')9+ -on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void +on(type: 'startRenderFrame', callback: Callback\): void -Subscribes to the video width and height change event. +Subscribes to the event that indicates rendering starts for the first frame. This subscription is supported only in the video playback scenarios. This event only means that the playback service sends the first frame to the display module. The actual rendering effect depends on the rendering performance of the display service. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'videoSizeChanged'** in this case.| -| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | +| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -videoPlayer.on('videoSizeChanged', (width, height) => { - console.log('video width is: ' + width); - console.log('video height is: ' + height); -}); +avPlayer.on('startRenderFrame', () => { + console.info('startRenderFrame success') +}) ``` -### on('error')8+ +### off('startRenderFrame')9+ -on(type: 'error', callback: ErrorCallback): void +off(type: 'startRenderFrame'): void -Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback. +Unsubscribes from the event that indicates rendering starts for the first frame. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during video playback.| -| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| **Example** ```js -videoPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`video error called, error: ${error}`); -}); -videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. +avPlayer.off('startRenderFrame') ``` -### on('availableBitratesCollect')9+ +### on('videoSizeChange')9+ -on(type: 'availableBitratesCollect', callback: (bitrates: Array\) => void): void +on(type: 'videoSizeChange', callback: (width: number, height: number) => void): void -Subscribes to the video playback bit rate reporting event. +Subscribes to video size (width and height) changes. This subscription is supported only in the video playback scenarios. By default, this event is reported only once in the prepared state. However, it is also reported upon resolution changes in the case of HLS streams. -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +**System capability**: SystemCapability.Multimedia.Media.AVPlayer **Parameters** | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'availableBitratesCollect'** in this case. This event is reported only once when the playback starts.| -| callback | function | Yes | Callback used to return supported bit rates, in an array. | +| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| +| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | **Example** ```js -videoPlayer.on('availableBitratesCollect', (bitrates) => { - for (let i = 0; i < bitrates.length; i++) { - console.info('case availableBitratesCollect bitrates: ' + bitrates[i]); // Print bit rates. - } -}); +avPlayer.on('videoSizeChange', (width: number, height: number) => { + console.info('videoSizeChange success,and width is:' + width + ', height is :' + height) +}) ``` -## VideoPlayState8+ +### off('videoSizeChange')9+ -Enumerates the video playback states. You can obtain the state through the **state** attribute. +off(type: 'videoSizeChange'): void -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer +Unsubscribes from video size changes. -| Name | Type | Description | -| -------- | ------ | -------------- | -| idle | string | The video player is idle.| -| prepared | string | Video playback is being prepared.| -| playing | string | Video playback is in progress.| -| paused | string | Video playback is paused.| -| stopped | string | Video playback is stopped.| -| error | string | Video playback is in the error state. | +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| + +**Example** + +```js +avPlayer.off('videoSizeChange') +``` + +### on('audioInterrupt')9+ + +on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void + +Subscribes to the audio interruption event. When multiple audio and video assets are played at the same time, this event is triggered based on the audio interruption mode [audio.InterruptMode](js-apis-audio.md#interruptmode9). + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | +| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| +| callback | [audio.InterruptEvent9+](js-apis-audio.md#interruptevent9) | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { + console.info('audioInterrupt success,and InterruptEvent info is:' + info) +}) +``` + +### off('audioInterrupt')9+ + +off(type: 'audioInterrupt'): void + +Unsubscribes from the audio interruption event. + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| + +**Example** + +```js +avPlayer.off('audioInterrupt') +``` + +## AVPlayerState9+ + +Enumerates the states of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** attribute or obtain the reported AVPlayer state by subscribing to the [stateChange](#stateChange_on) event. For details about the rules for state transition, see [AVPlayer Development](../../media/avplayer-playback.md). + +**System capability**: SystemCapability.Multimedia.Media.AVPlayer + +| Name | Type | Description | +| :-----------------------------: | :----: | :----------------------------------------------------------- | +| idle | string | The AVPlayer enters this state after [createAVPlayer()](#mediacreateavplayer9) or **reset()** is called.
In case **createAVPlayer()** is used, all attributes are set to their default values.
In case **reset()** is invoked, the **url9+** or **fdSrc9+** attribute is reset, and other attributes set by the application are retained.| +| initialized | string | The AVPlayer enters this state after **url9+** or **fdSrc9+** attribute is set in the idle state. In this case, you can configure static attributes such as the window and audio.| +| prepared | string | The AVPlayer enters this state when **prepare()** is called in the initialized state. In this case, the playback engine has prepared the resources.| +| playing | string | The AVPlayer enters this state when **play()** is called in the prepared, paused, or completed state.| +| paused | string | The AVPlayer enters this state when **pause()** is called in the playing state.| +| completed | string | The AVPlayer enters this state when a media asset finishes playing and loop playback is not set (no **loop = 1**). In this case, if **play()** is called, the AVPlayer enters the playing state and replays the media asset; if **stop()** is called, the AVPlayer enters the stopped state.| +| stopped | string | The AVPlayer enters this state when **stop()** is called in the prepared, playing, paused, or completed state. In this case, the playback engine retains the attributes but releases the memory resources. You can call **prepare()** to prepare the resources again, call **reset()** to reset the attributes, or call **release()** to destroy the playback engine.| +| released | string | The AVPlayer enters this state when **release()** is called. The playback engine associated with the **AVPlayer** instance is destroyed, and the playback process ends. This is the final state.| +| error | string | The AVPlayer enters this state when an irreversible error occurs in the playback engine. You can call **reset()** to reset the attributes or call **release()** to destroy the playback engine. For details on the errors, see [Error Classification](#error_info).
**NOTE** Relationship between the error state and the [on('error')](#error_on) event
1. When the AVPlayer enters the error state, the [on('error')](#error_on) event is triggered. You can obtain the detailed error information through this event.
2. When the AVPlayer enters the error state, the playback service stops. This requires the client to design a fault tolerance mechanism to call **reset()** or **release()**.
3. The client receives [on('error')](#error_on) event but the AVPlayer does not enter the error state. This situation occurs due to either of the following reasons:
Cause 1: The client calls an API in an incorrect state or passes in an incorrect parameter, and the AVPlayer intercepts the call. If this is the case, the client must correct its code logic.
Cause 2: A stream error is detected during playback. As a result, the container and decoding are abnormal for a short period of time, but continuous playback and playback control operations are not affected. If this is the case, the client does not need to design a fault tolerance mechanism.| + +## AVFileDescriptor9+ + +Describes an audio and video file asset. It is used to specify a particular asset for playback based on its offset and length within a file. + +**System capability**: SystemCapability.Multimedia.Media.Core + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| fd | number | Yes | Resource handle, which is obtained by calling **resourceManager.getRawFileDescriptor**. | +| offset | number | Yes | Resource offset, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse audio and video assets.| +| length | number | Yes | Resource length, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse audio and video assets.| ## SeekMode8+ @@ -1557,10 +1639,10 @@ Enumerates the video scale modes. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer -| Name | Value| Description | -| ---------------------------- | ------ | ---------- | -| VIDEO_SCALE_TYPE_FIT | 0 | The video will be stretched to fit the window.| -| VIDEO_SCALE_TYPE_FIT_CROP| 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped. | +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------------------------ | +| VIDEO_SCALE_TYPE_FIT | 0 | The video will be stretched to fit the window. | +| VIDEO_SCALE_TYPE_FIT_CROP | 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped.| ## MediaDescription8+ @@ -1589,852 +1671,915 @@ audioPlayer.getTrackDescription((error, arrList) => { }); ``` -## AudioRecorder +## AVRecorder9+ -Implements audio recording. Before calling an API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. +A recording management class that provides APIs to record media assets. Before calling any API in **AVRecorder**, you must use **createAVRecorder()** to create an **AVRecorder** instance. -For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). +For details about the AVRecorder demo, see [AVRecorder Development](../../media/avrecorder.md). -### prepare +### Attributes -prepare(config: AudioRecorderConfig): void +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -Prepares for recording. +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------ | ---- | ---- | ------------------ | +| state9+ | [AVRecorderState](#avrecorderstate9) | Yes | No | AVRecorder state.| + +### prepare9+ + +prepare(config: AVRecorderConfig, callback: AsyncCallback\): void + +Sets audio and video recording parameters. This API uses an asynchronous callback to return the result. **Required permissions:** ohos.permission.MICROPHONE -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +This permission is required only if audio recording is involved. + +To use the camera to record videos, the camera module is required. For details about how to obtain the permissions and use the APIs, see [Camera Management](js-apis-camera.md). + +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------- | +| config | [AVRecorderConfig](#avrecorderconfig9) | Yes | Audio and video recording parameters to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operate not permit. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. - location : { latitude : 30, longitude : 130}, +let AVRecorderProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 } -audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. - console.log('prepare success'); -}); -audioRecorder.prepare(audioRecorderConfig); +let AVRecorderConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45. + rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. + location : { latitude : 30, longitude : 130 } +} + +AVRecorder.prepare(AVRecorderConfig, (err) => { + if (err == null) { + console.info('prepare success'); + } else { + console.info('prepare failed and error is ' + err.message); + } +}) ``` +### prepare9+ -### start +prepare(config: AVRecorderConfig): Promise\ -start(): void +Sets audio and video recording parameters. This API uses a promise to return the result. -Starts audio recording. This API can be called only after the [prepare](#audiorecorder_on) event is triggered. +**Required permissions:** ohos.permission.MICROPHONE -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +This permission is required only if audio recording is involved. -**Example** +To use the camera to record videos, the camera module is required. For details about how to obtain the permissions and use the APIs, see [Camera Management](js-apis-camera.md). -```js -audioRecorder.on('start', () => { // Set the 'start' event callback. - console.log('audio recorder start success'); -}); -audioRecorder.start(); -``` +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -### pause +**Parameters** -pause():void +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | -------------------------- | +| config | [AVRecorderConfig](#avrecorderconfig9) | Yes | Audio and video recording parameters to set.| -Pauses audio recording. This API can be called only after the [start](#audiorecorder_on) event is triggered. +**Return value** -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +| Type | Description | +| -------------- | ------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operate not permit. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js -audioRecorder.on('pause', () => { // Set the 'pause' event callback. - console.log('audio recorder pause success'); +let AVRecorderProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 48000, + videoCodec : media.CodecMimeType.VIDEO_MPEG4, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} +let AVRecorderConfig = { + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45. + rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. + location : { latitude : 30, longitude : 130 } +} + +AVRecorder.prepare(AVRecorderConfig).then(() => { + console.info('prepare success'); +}).catch((err) => { + console.info('prepare failed and catch error is ' + err.message); }); -audioRecorder.pause(); + ``` -### resume +### getInputSurface9+ -resume():void +getInputSurface(callback: AsyncCallback\): void -Resumes audio recording. This API can be called only after the [pause](#audiorecorder_on) event is triggered. +Obtains the surface required for recording. This API uses an asynchronous callback to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding video data. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time. + +This API can be called only after the **prepare()** API is called. + +**System capability**: SystemCapability.Multimedia.Media.AVRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -audioRecorder.on('resume', () => { // Set the 'resume' event callback. - console.log('audio recorder resume success'); +let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance. + +AVRecorder.getInputSurface((err, surfaceId) => { + if (err == null) { + console.info('getInputSurface success'); + surfaceID = surfaceId; + } else { + console.info('getInputSurface failed and error is ' + err.message); + } }); -audioRecorder.resume(); + +// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); + ``` -### stop +### getInputSurface9+ -stop(): void +getInputSurface(): Promise\ -Stops audio recording. +Obtains the surface required for recording. This API uses a promise to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding video data. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time. + +This API can be called only after the **prepare()** API is called. + +**System capability**: SystemCapability.Multimedia.Media.AVRecorder + +**Return value** + +| Type | Description | +| ---------------- | -------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js -audioRecorder.on('stop', () => { // Set the 'stop' event callback. - console.log('audio recorder stop success'); +let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance. + +AVRecorder.getInputSurface().then((surfaceId) => { + console.info('getInputSurface success'); + surfaceID = surfaceId; +}).catch((err) => { + console.info('getInputSurface failed and catch error is ' + err.message); }); -audioRecorder.stop(); + +// videoOutput = await cameraManager.createVideoOutput(videoProfiles[0], surfaceID); ``` -### release +### start9+ -release(): void +start(callback: AsyncCallback\): void -Releases the audio recording resource. +Starts recording. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +For audio-only recording, this API can be called only after the **prepare()** API is called. For video-only recording, this API can be called only after the **getInputSurface()** API is called. + +**System capability**: SystemCapability.Multimedia.Media.AVRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -audioRecorder.on('release', () => { // Set the 'release' event callback. - console.log('audio recorder release success'); +AVRecorder.start((err) => { + if (err == null) { + console.info('start AVRecorder success'); + } else { + console.info('start AVRecorder failed and error is ' + err.message); + } }); -audioRecorder.release(); -audioRecorder = undefined; ``` -### reset +### start9+ -reset(): void +start(): Promise\ -Resets audio recording. +Starts recording. This API uses a promise to return the result. -Before resetting audio recording, you must call [stop()](#audiorecorder_stop) to stop recording. After audio recording is reset, you must call [prepare()](#audiorecorder_prepare) to set the recording parameters for another recording. +For audio-only recording, this API can be called only after the **prepare()** API is called. For video-only recording, this API can be called only after the **getInputSurface()** API is called. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +**System capability**: SystemCapability.Multimedia.Media.AVRecorder + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js -audioRecorder.on('reset', () => { // Set the 'reset' event callback. - console.log('audio recorder reset success'); +AVRecorder.start().then(() => { + console.info('start AVRecorder success'); +}).catch((err) => { + console.info('start AVRecorder failed and catch error is ' + err.message); }); -audioRecorder.reset(); ``` -### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset') +### pause9+ -on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void +pause(callback: AsyncCallback\): void -Subscribes to the audio recording events. +Pauses recording. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +This API can be called only after the **start()** API is called. You can call **resume()** to resume recording. + +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset.| -| callback | ()=>void | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| -**Example** +**Error codes** -```js -let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - location : { latitude : 30, longitude : 130}, -} -audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); -}); -audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. - console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the 'start' event callback. -}); -audioRecorder.on('start', () => { // Set the 'start' event callback. - console.log('audio recorder start success'); -}); -audioRecorder.on('pause', () => { // Set the 'pause' event callback. - console.log('audio recorder pause success'); -}); -audioRecorder.on('resume', () => { // Set the 'resume' event callback. - console.log('audio recorder resume success'); -}); -audioRecorder.on('stop', () => { // Set the 'stop' event callback. - console.log('audio recorder stop success'); -}); -audioRecorder.on('release', () => { // Set the 'release' event callback. - console.log('audio recorder release success'); -}); -audioRecorder.on('reset', () => { // Set the 'reset' event callback. - console.log('audio recorder reset success'); +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +AVRecorder.pause((err) => { + if (err == null) { + console.info('pause AVRecorder success'); + } else { + console.info('pause AVRecorder failed and error is ' + err.message); + } }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` -### on('error') +### pause9+ -on(type: 'error', callback: ErrorCallback): void +pause(): Promise\ -Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording. +Pauses recording. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +This API can be called only after the **start()** API is called. You can call **resume()** to resume recording. -**Parameters** +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during audio recording.| -| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js -let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - location : { latitude : 30, longitude : 130}, -} -audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); +AVRecorder.pause().then(() => { + console.info('pause AVRecorder success'); +}).catch((err) => { + console.info('pause AVRecorder failed and catch error is ' + err.message); }); -audioRecorder.prepare(audioRecorderConfig); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` -## AudioRecorderConfig +### resume9+ -Describes audio recording configurations. +resume(callback: AsyncCallback\): void -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +Resumes recording. This API uses an asynchronous callback to return the result. -| Name | Type | Mandatory| Description | -| --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| audioEncoder(deprecated) | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**.
**Note**: This parameter is deprecated since API version 8. Use **audioEncoderMime** instead. | -| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**. | -| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | -| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | -| format(deprecated) | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**.
**Note**: This parameter is deprecated since API version 8. Use **fileFormat** instead. | -| location | [Location](#location) | No | Geographical location of the recorded audio. | -| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| -| audioEncoderMime8+ | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | -| fileFormat8+ | [ContainerFormatType](#containerformattype8) | No | Audio encoding format. | +This API can be called only after the **pause()** API is called. -## AudioEncoder(deprecated) +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -> **NOTE** -> This API is deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead. +**Parameters** -Enumerates the audio encoding formats. +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +**Error codes** -| Name | Value | Description | -| ------- | ---- | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet. | -| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| -| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| -| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | -## AudioOutputFormat(deprecated) +**Example** -> **NOTE** -> This API is deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead. +```js +AVRecorder.resume((err) => { + if (err == null) { + console.info('resume AVRecorder success'); + } else { + console.info('resume AVRecorder failed and error is ' + err.message); + } +}); +``` -Enumerates the audio output formats. +### resume9+ -**System capability**: SystemCapability.Multimedia.Media.AudioRecorder +resume(): Promise\ -| Name | Value | Description | -| -------- | ---- | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet. | -| MPEG_4 | 2 | MPEG-4. | -| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet. | -| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet. | -| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| +Resumes recording. This API uses a promise to return the result. -## VideoRecorder9+ +This API can be called only after the **pause()** API is called. -Implements video recording. Before calling an API of the **VideoRecorder** class, you must call [createVideoRecorder()](#mediacreatevideorecorder9) to create a [VideoRecorder](#videorecorder9) instance. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md). +**Return value** -### Attributes +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**Error codes** -**System API**: This is a system API. +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| Name | Type | Readable| Writable| Description | -| ------------------ | -------------------------------------- | ---- | ---- | ---------------- | -| state9+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | -### prepare9+ +**Example** -prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; +```js +AVRecorder.resume().then(() => { + console.info('resume AVRecorder success'); +}).catch((err) => { + console.info('resume AVRecorder failed and catch error is ' + err.message); +}); +``` -Sets video recording parameters. This API uses an asynchronous callback to return the result. +### stop9+ -**Required permissions:** ohos.permission.MICROPHONE +stop(callback: AsyncCallback\): void -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +Stops recording. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +This API can be called only after the **start()** or **pause()** API is called. + +For audio-only recording, you can call **prepare()** again for re-recording. For video-only recording or audio and video recording, you can call **prepare()** and **getInputSurface()** again for re-recording. + +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ----------------------------------- | -| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ------------------------------------------ | -| 201 | Permission denied. Return by callback. | -| 401 | Parameter error. Return by callback. | -| 5400102 | Operation not allowed. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | --------------------------------------- | +| 5400102 | Operate not permit. Return by callback. | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} - -let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// asyncallback -videoRecorder.prepare(videoConfig, (err) => { +AVRecorder.stop((err) => { if (err == null) { - console.info('prepare success'); + console.info('stop AVRecorder success'); } else { - console.info('prepare failed and error is ' + err.message); + console.info('stop AVRecorder failed and error is ' + err.message); } -}) +}); ``` -### prepare9+ - -prepare(config: VideoRecorderConfig): Promise\; - -Sets video recording parameters. This API uses a promise to return the result. +### stop9+ -**Required permissions:** ohos.permission.MICROPHONE +stop(): Promise\ -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +Stops recording. This API uses a promise to return the result. -**System API**: This is a system API. +This API can be called only after the **start()** or **pause()** API is called. -**Parameters** +For audio-only recording, you can call **prepare()** again for re-recording. For video-only recording or audio and video recording, you can call **prepare()** and **getInputSurface()** again for re-recording. -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------------- | ---- | ------------------------ | -| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set.| +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Return value** -| Type | Description | -| -------------- | ---------------------------------------- | +| Type | Description | +| -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 201 | Permission denied. Return by promise. | -| 401 | Parameter error. Return by promise. | -| 5400102 | Operation not allowed. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | -------------------------------------- | +| 5400102 | Operate not permit. Return by promise. | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} - -let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// promise -videoRecorder.prepare(videoConfig).then(() => { - console.info('prepare success'); +AVRecorder.stop().then(() => { + console.info('stop AVRecorder success'); }).catch((err) => { - console.info('prepare failed and catch error is ' + err.message); + console.info('stop AVRecorder failed and catch error is ' + err.message); }); ``` -### getInputSurface9+ - -getInputSurface(callback: AsyncCallback\): void; - -Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. +### reset9+ -Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. +reset(callback: AsyncCallback\): void -This API can be called only after [prepare()](#videorecorder_prepare1) is called. +Resets audio and video recording. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +For audio-only recording, you can call **prepare()** again for re-recording. For video-only recording or audio and video recording, you can call **prepare()** and **getInputSurface()** again for re-recording. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | --------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -// asyncallback -let surfaceID = null; // Surface ID passed to the external system. -videoRecorder.getInputSurface((err, surfaceId) => { +AVRecorder.reset((err) => { if (err == null) { - console.info('getInputSurface success'); - surfaceID = surfaceId; + console.info('reset AVRecorder success'); } else { - console.info('getInputSurface failed and error is ' + err.message); + console.info('reset AVRecorder failed and error is ' + err.message); } }); ``` -### getInputSurface9+ - -getInputSurface(): Promise\; - - Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. +### reset9+ -Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. +reset(): Promise\ -This API can be called only after [prepare()](#videorecorder_prepare1) is called. +Resets audio and video recording. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +For audio-only recording, you can call **prepare()** again for re-recording. For video-only recording or audio and video recording, you can call **prepare()** and **getInputSurface()** again for re-recording. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Return value** -| Type | Description | -| ---------------- | -------------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | --------------------------------------- | +| Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | -------------------------------- | +| 5400103 | IO error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js -// promise -let surfaceID = null; // Surface ID passed to the external system. -videoRecorder.getInputSurface().then((surfaceId) => { - console.info('getInputSurface success'); - surfaceID = surfaceId; +AVRecorder.reset().then(() => { + console.info('reset AVRecorder success'); }).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); + console.info('reset AVRecorder failed and catch error is ' + err.message); }); ``` -### start9+ - -start(callback: AsyncCallback\): void; +### release9+ -Starts video recording. This API uses an asynchronous callback to return the result. +release(callback: AsyncCallback\): void -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. +Releases the audio and video recording resources. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +After the resources are released, you can no longer perform any operation on the **AVRecorder** instance. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | **Example** ```js -// asyncallback -videoRecorder.start((err) => { +AVRecorder.release((err) => { if (err == null) { - console.info('start videorecorder success'); + console.info('release AVRecorder success'); } else { - console.info('start videorecorder failed and error is ' + err.message); + console.info('release AVRecorder failed and error is ' + err.message); } }); ``` -### start9+ - -start(): Promise\; +### release9+ -Starts video recording. This API uses a promise to return the result. +release(): Promise\ -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. +Releases the audio and video recording resources. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +After the resources are released, you can no longer perform any operation on the **AVRecorder** instance. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Return value** -| Type | Description | -| -------------- | ------------------------------------- | +| Type | Description | +| -------------- | ------------------------------------------- | | Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | **Example** ```js -// promise -videoRecorder.start().then(() => { - console.info('start videorecorder success'); +AVRecorder.release().then(() => { + console.info('release AVRecorder success'); }).catch((err) => { - console.info('start videorecorder failed and catch error is ' + err.message); + console.info('release AVRecorder failed and catch error is ' + err.message); }); ``` -### pause9+ - -pause(callback: AsyncCallback\): void; - -Pauses video recording. This API uses an asynchronous callback to return the result. +### on('stateChange')9+ -This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). +on(type: 'stateChange', callback: (state: AVRecorderState, reason: StateChangeReason) => void): void -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +Subscribes to AVRecorder state changes. An application can subscribe to only one AVRecorder state change event. When the application initiates multiple subscriptions to this event, the last subscription prevails. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Error codes** - -For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). - -| ID| Error Message | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| +| callback | function | Yes | Callback invoked when the event is triggered. It reports the following information:
**state**: [AVRecorderState](#avrecorderstate9), indicating the AVRecorder state.
**reason**: [StateChangeReason](#statechangereason9), indicating the reason for the state transition.| **Example** ```js -// asyncallback -videoRecorder.pause((err) => { - if (err == null) { - console.info('pause videorecorder success'); - } else { - console.info('pause videorecorder failed and error is ' + err.message); +AVRecorder.on('stateChange', async (state, reason) => { + console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); } }); ``` -### pause9+ - -pause(): Promise\; - -Pauses video recording. This API uses a promise to return the result. - -This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**System API**: This is a system API. +### off('stateChange')9+ -**Return value** +off(type: 'stateChange'): void -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| +Unsubscribes from AVRecorder state changes. -**Error codes** +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). +**Parameters** -| ID| Error Message | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| **Example** ```js -// promise -videoRecorder.pause().then(() => { - console.info('pause videorecorder success'); -}).catch((err) => { - console.info('pause videorecorder failed and catch error is ' + err.message); -}); +AVRecorder.off('stateChange'); ``` -### resume9+ +### on('error')9+ -resume(callback: AsyncCallback\): void; +on(type: 'error', callback: ErrorCallback): void -Resumes video recording. This API uses an asynchronous callback to return the result. +Subscribes to AVRecorder errors. This event is used only for error prompt and does not require the user to stop recording control. If the [AVRecorderState](#avrecorderstate9) is also switched to error, call **reset()** or **release()** to exit the recording. -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +An application can subscribe to only one AVRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case.
This event is triggered when an error occurs during recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -// asyncallback -videoRecorder.resume((err) => { - if (err == null) { - console.info('resume videorecorder success'); - } else { - console.info('resume videorecorder failed and error is ' + err.message); - } +AVRecorder.on('error', (err) => { + console.info('case avRecorder.on(error) called, errMessage is ' + err.message); }); ``` -### resume9+ - -resume(): Promise\; +### off('error')9+ -Resumes video recording. This API uses a promise to return the result. +off(type: 'error'): void -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +Unsubscribes from AVRecorder errors. After the unsubscription, your application can no longer receive AVRecorder errors. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -**Return value** +**Parameters** -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case.
This event is triggered when an error occurs during recording.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | IO error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -// promise -videoRecorder.resume().then(() => { - console.info('resume videorecorder success'); -}).catch((err) => { - console.info('resume videorecorder failed and catch error is ' + err.message); -}); +AVRecorder.off('error'); ``` -### stop9+ +## AVRecorderState9+ -stop(callback: AsyncCallback\): void; +Enumerates the AVRecorder states. You can obtain the state through the **state** attribute. -Stops video recording. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. +| Name | Type | Description | +| -------- | ------ | ------------------------------------------------------------ | +| idle | string | The AVRecorder enters this state when the AVRecorder is just created or the [reset()](#avrecorder_reset) API is called in any non-released state. In this state, you can call [prepare()](#avrecorder_prepare) to set recording parameters. | +| prepared | string | The AVRecorder enters this state when the parameters are set. In this state, you can call [start()](#avrecorder_start) to start recording.| +| started | string | The AVRecorder enters this state when the recording starts. In this state, you can call [pause()](#avrecorder_pause) to pause the recording or call [stop()](#avrecorder_stop) to stop recording.| +| paused | string | The AVRecorder enters this state when the recording is paused. In this state, you can call [resume()](#avrecorder_resume) to continue the recording or call [stop()](#avrecorder_stop) to stop recording.| +| stopped | string | The AVRecorder enters this state when the recording stops. In this state, you can call [prepare()](#avrecorder_prepare) to set recording parameters.| +| released | string | The AVRecorder enters this state when the recording resources are released. In this state, no operation can be performed. In any other state, you can call [release()](#avrecorder_release) to enter the released state.| +| error | string | The AVRecorder enters this state when an irreversible error occurs in the **AVRecorder** instance. In this state, the [on('error') event](#avrecorder_onerror) is reported, with the detailed error cause. In the error state, you must call [reset()](#avrecorder_reset) to reset the **AVRecorder** instance or call [release()](#avrecorder_release) to release the resources.| -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +## AVRecorderConfig9+ -**System API**: This is a system API. +Describes the audio and video recording parameters. -**Parameters** +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| audioSourceType | [AudioSourceType](#audiosourcetype9) | No | Type of the audio source to record. This parameter is mandatory for audio recording. | +| videoSourceType | [VideoSourceType](#videosourcetype9) | No | Type of the video source to record. This parameter is mandatory for video recording. | +| profile | [AVRecorderProfile](#avrecorderprofile9) | Yes | Recording profile. This parameter is mandatory. | +| url | string | Yes | Recording output URL: fd://xx (fd number).
![img](figures/en-us_image_url.png)
This parameter is mandatory. | +| rotation | number | No | Rotation angle of the recorded video. The value can only be 0, 90, 180, or 270. | +| location | [Location](#location) | No | Geographical location of the recorded video. | -**Error codes** +The **audioSourceType** and **videoSourceType** parameters are used to distinguish audio-only recording, video-only recording, and audio and video recording. For audio-only recording, set only **audioSourceType**. For video-only recording, set only **videoSourceType**. For audio and video recording, set both **audioSourceType** and **videoSourceType**. -For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). +## AVRecorderProfile9+ -| ID| Error Message | -| -------- | ------------------------------------------ | -| 5400102 | Operation not allowed. Return by callback. | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +Describes the audio and video recording profile. -**Example** +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -```js -// asyncallback -videoRecorder.stop((err) => { - if (err == null) { - console.info('stop videorecorder success'); - } else { - console.info('stop videorecorder failed and error is ' + err.message); - } -}); -``` +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioBitrate | number | No | Audio encoding bit rate. This parameter is mandatory for audio recording. | +| audioChannels | number | No | Number of audio channels. This parameter is mandatory for audio recording. | +| audioCodec | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. This parameter is mandatory for audio recording. Only **AUDIO_AAC** is supported. | +| audioSampleRate | number | No | Audio sampling rate. This parameter is mandatory for audio recording. | +| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file. This parameter is mandatory. | +| videoBitrate | number | No | Video encoding bit rate. This parameter is mandatory for video recording. | +| videoCodec | [CodecMimeType](#codecmimetype8) | No | Video encoding format. This parameter is mandatory for video recording. Only **VIDEO_AVC** and **VIDEO_MPEG4** are supported.| +| videoFrameWidth | number | No | Width of a video frame. This parameter is mandatory for video recording. | +| videoFrameHeight | number | No | Height of a video frame. This parameter is mandatory for video recording. | +| videoFrameRate | number | No | Video frame rate. This parameter is mandatory for video recording. | -### stop9+ +## AudioSourceType9+ -stop(): Promise\; +Enumerates the audio source types for video recording. -Stops video recording. This API uses a promise to return the result. +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. +| Name | Value | Description | +| ------------------------- | ---- | ---------------------- | +| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| +| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source. | -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder +## VideoSourceType9+ -**System API**: This is a system API. +Enumerates the video source types for video recording. -**Return value** +**System capability**: SystemCapability.Multimedia.Media.AVRecorder -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------- | +| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| +| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data. | -**Error codes** +## ContainerFormatType8+ -For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). +Enumerates the container format types (CFTs). -| ID| Error Message | -| -------- | ----------------------------------------- | -| 5400102 | Operation not allowed. Return by promise. | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +**System capability**: SystemCapability.Multimedia.Media.Core -**Example** +| Name | Value | Description | +| ----------- | ----- | --------------------- | +| CFT_MPEG_4 | 'mp4' | Video container format MP4.| +| CFT_MPEG_4A | 'm4a' | Audio container format M4A.| -```js -// promise -videoRecorder.stop().then(() => { - console.info('stop videorecorder success'); -}).catch((err) => { - console.info('stop videorecorder failed and catch error is ' + err.message); -}); -``` +## Location -### release9+ +Describes the geographical location of the recorded video. -release(callback: AsyncCallback\): void; +**System capability**: SystemCapability.Multimedia.Media.Core + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------- | +| latitude | number | Yes | Latitude of the geographical location.| +| longitude | number | Yes | Longitude of the geographical location.| + +## VideoRecorder9+ + +> **NOTE** +> +> This class is deprecated after AVRecorder9+ is released. You are advised to use [AVRecorder](#avrecorder9) instead. + +Implements video recording. Before calling any API in the **VideoRecorder** class, you must use [createVideoRecorder()](#mediacreatevideorecorder9) to create a [VideoRecorder](#videorecorder9) instance. + +For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md). + +### Attributes + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +| Name | Type | Readable| Writable| Description | +| ------------------ | -------------------------------------- | ---- | ---- | ---------------- | +| state9+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| + +### prepare9+ + +prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; + +Sets video recording parameters. This API uses an asynchronous callback to return the result. -Releases the video recording resource. This API uses an asynchronous callback to return the result. +**Required permissions:** ohos.permission.MICROPHONE **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2442,73 +2587,134 @@ Releases the video recording resource. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ----------------------------------- | +| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------- | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operation not allowed. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + // asyncallback -videoRecorder.release((err) => { +videoRecorder.prepare(videoConfig, (err) => { if (err == null) { - console.info('release videorecorder success'); + console.info('prepare success'); } else { - console.info('release videorecorder failed and error is ' + err.message); + console.info('prepare failed and error is ' + err.message); } -}); +}) ``` -### release9+ +### prepare9+ -release(): Promise\; +prepare(config: VideoRecorderConfig): Promise\; + +Sets video recording parameters. This API uses a promise to return the result. -Releases the video recording resource. This API uses a promise to return the result. +**Required permissions:** ohos.permission.MICROPHONE **System capability**: SystemCapability.Multimedia.Media.VideoRecorder **System API**: This is a system API. +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------- | ---- | ------------------------ | +| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set.| + **Return value** -| Type | Description | -| -------------- | ----------------------------------------- | +| Type | Description | +| -------------- | ---------------------------------------- | | Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------- | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operation not allowed. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js +let videoProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 48000, + videoCodec : 'video/mp4v-es', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 +} + +let videoConfig = { + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, +} + // promise -videoRecorder.release().then(() => { - console.info('release videorecorder success'); +videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); }).catch((err) => { - console.info('release videorecorder failed and catch error is ' + err.message); + console.info('prepare failed and catch error is ' + err.message); }); ``` -### reset9+ +### getInputSurface9+ -reset(callback: AsyncCallback\): void; +getInputSurface(callback: AsyncCallback\): void; -Resets video recording. This API uses an asynchronous callback to return the result. +Obtains the surface required for recording. This API uses an asynchronous callback to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time. + +This API can be called only after [prepare()](#videorecorder_prepare1) is called. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2516,39 +2722,44 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------- | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js // asyncallback -videoRecorder.reset((err) => { +let surfaceID = null; // Surface ID passed to the external system. +videoRecorder.getInputSurface((err, surfaceId) => { if (err == null) { - console.info('reset videorecorder success'); + console.info('getInputSurface success'); + surfaceID = surfaceId; } else { - console.info('reset videorecorder failed and error is ' + err.message); + console.info('getInputSurface failed and error is ' + err.message); } }); ``` -### reset9+ +### getInputSurface9+ -reset(): Promise\; +getInputSurface(): Promise\; -Resets video recording. This API uses a promise to return the result. + Obtains the surface required for recording. This API uses a promise to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. +Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time. + +This API can be called only after [prepare()](#videorecorder_prepare1) is called. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2556,162 +2767,2240 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **Return value** -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ---------------- | -------------------------------- | +| Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------- | -| 5400103 | I/O error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** ```js // promise -videoRecorder.reset().then(() => { - console.info('reset videorecorder success'); +let surfaceID = null; // Surface ID passed to the external system. +videoRecorder.getInputSurface().then((surfaceId) => { + console.info('getInputSurface success'); + surfaceID = surfaceId; }).catch((err) => { - console.info('reset videorecorder failed and catch error is ' + err.message); + console.info('getInputSurface failed and catch error is ' + err.message); }); ``` -### on('error')9+ +### start9+ -on(type: 'error', callback: ErrorCallback): void +start(callback: AsyncCallback\): void; -Subscribes to video recording error events. After an error event is reported, you must handle the event and exit the recording. +Starts video recording. This API uses an asynchronous callback to return the result. + +This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during video recording.| -| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------- | -| 5400103 | I/O error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** ```js -// This event is reported when an error occurs during the retrieval of videoRecordState. -videoRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); -}) +// asyncallback +videoRecorder.start((err) => { + if (err == null) { + console.info('start videorecorder success'); + } else { + console.info('start videorecorder failed and error is ' + err.message); + } +}); ``` -## VideoRecordState9+ - -Enumerates the video recording states. You can obtain the state through the **state** attribute. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**System API**: This is a system API. +### start9+ -| Name | Type | Description | -| -------- | ------ | ---------------------- | -| idle | string | The video recorder is idle. | -| prepared | string | The video recording parameters are set.| -| playing | string | Video recording is in progress. | -| paused | string | Video recording is paused. | -| stopped | string | Video recording is stopped. | -| error | string | Video recording is in the error state. | +start(): Promise\; -## VideoRecorderConfig9+ +Starts video recording. This API uses a promise to return the result. -Describes the video recording parameters. +This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder **System API**: This is a system API. -| Name | Type | Mandatory| Description | -| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. | -| videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. | -| profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | -| rotation | number | No | Rotation angle of the recorded video. | -| location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png) | +**Return value** -## AudioSourceType9+ +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| -Enumerates the audio source types for video recording. +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**Example** + +```js +// promise +videoRecorder.start().then(() => { + console.info('start videorecorder success'); +}).catch((err) => { + console.info('start videorecorder failed and catch error is ' + err.message); +}); +``` + +### pause9+ + +pause(callback: AsyncCallback\): void; + +Pauses video recording. This API uses an asynchronous callback to return the result. + +This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). **System capability**: SystemCapability.Multimedia.Media.VideoRecorder **System API**: This is a system API. -| Name | Value | Description | -| ------------------------- | ---- | ---------------------- | -| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| -| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source. | +**Parameters** -## VideoSourceType9+ +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -Enumerates the video source types for video recording. +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +// asyncallback +videoRecorder.pause((err) => { + if (err == null) { + console.info('pause videorecorder success'); + } else { + console.info('pause videorecorder failed and error is ' + err.message); + } +}); +``` + +### pause9+ + +pause(): Promise\; + +Pauses video recording. This API uses a promise to return the result. + +This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). **System capability**: SystemCapability.Multimedia.Media.VideoRecorder **System API**: This is a system API. -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------- | -| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| -| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data. | +**Return value** -## VideoRecorderProfile9+ +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| -Describes the video recording profile. +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**Example** + +```js +// promise +videoRecorder.pause().then(() => { + console.info('pause videorecorder success'); +}).catch((err) => { + console.info('pause videorecorder failed and catch error is ' + err.message); +}); +``` + +### resume9+ + +resume(callback: AsyncCallback\): void; + +Resumes video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder **System API**: This is a system API. -| Name | Type | Mandatory| Description | -| ---------------- | -------------------------------------------- | ---- | ---------------- | -| audioBitrate | number | Yes | Audio encoding bit rate.| -| audioChannels | number | Yes | Number of audio channels.| -| audioCodec | [CodecMimeType](#codecmimetype8) | Yes | Audio encoding format. | -| audioSampleRate | number | Yes | Audio sampling rate. | -| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.| -| videoBitrate | number | Yes | Video encoding bit rate.| -| videoCodec | [CodecMimeType](#codecmimetype8) | Yes | Video encoding format. | -| videoFrameWidth | number | Yes | Width of the recorded video frame.| -| videoFrameHeight | number | Yes | Height of the recorded video frame.| -| videoFrameRate | number | Yes | Video frame rate. | +**Parameters** -## ContainerFormatType8+ +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -Enumerates the container format types (CFTs). +**Error codes** -**System capability**: SystemCapability.Multimedia.Media.Core +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| Name | Value | Description | -| ----------- | ----- | --------------------- | -| CFT_MPEG_4 | 'mp4' | Video container format MPEG-4.| -| CFT_MPEG_4A | 'm4a' | Audio container format M4A.| +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | -## Location +**Example** -Describes the geographical location of the recorded video. +```js +// asyncallback +videoRecorder.resume((err) => { + if (err == null) { + console.info('resume videorecorder success'); + } else { + console.info('resume videorecorder failed and error is ' + err.message); + } +}); +``` -**System capability**: SystemCapability.Multimedia.Media.Core +### resume9+ -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------------- | -| latitude | number | Yes | Latitude of the geographical location.| -| longitude | number | Yes | Longitude of the geographical location.| +resume(): Promise\; + +Resumes video recording. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**Example** + +```js +// promise +videoRecorder.resume().then(() => { + console.info('resume videorecorder success'); +}).catch((err) => { + console.info('resume videorecorder failed and catch error is ' + err.message); +}); +``` + +### stop9+ + +stop(callback: AsyncCallback\): void; + +Stops video recording. This API uses an asynchronous callback to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +// asyncallback +videoRecorder.stop((err) => { + if (err == null) { + console.info('stop videorecorder success'); + } else { + console.info('stop videorecorder failed and error is ' + err.message); + } +}); +``` + +### stop9+ + +stop(): Promise\; + +Stops video recording. This API uses a promise to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**Example** + +```js +// promise +videoRecorder.stop().then(() => { + console.info('stop videorecorder success'); +}).catch((err) => { + console.info('stop videorecorder failed and catch error is ' + err.message); +}); +``` + +### release9+ + +release(callback: AsyncCallback\): void; + +Releases the video recording resources. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +// asyncallback +videoRecorder.release((err) => { + if (err == null) { + console.info('release videorecorder success'); + } else { + console.info('release videorecorder failed and error is ' + err.message); + } +}); +``` + +### release9+ + +release(): Promise\; + +Releases the video recording resources. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +// promise +videoRecorder.release().then(() => { + console.info('release videorecorder success'); +}).catch((err) => { + console.info('release videorecorder failed and catch error is ' + err.message); +}); +``` + +### reset9+ + +reset(callback: AsyncCallback\): void; + +Resets video recording. This API uses an asynchronous callback to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +// asyncallback +videoRecorder.reset((err) => { + if (err == null) { + console.info('reset videorecorder success'); + } else { + console.info('reset videorecorder failed and error is ' + err.message); + } +}); +``` + +### reset9+ + +reset(): Promise\; + +Resets video recording. This API uses a promise to return the result. + +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + +**Example** + +```js +// promise +videoRecorder.reset().then(() => { + console.info('reset videorecorder success'); +}).catch((err) => { + console.info('reset videorecorder failed and catch error is ' + err.message); +}); +``` + +### on('error')9+ + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to video recording error events. After an error event is reported, you must handle the event and exit the recording. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case.
This event is triggered when an error occurs during video recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + +**Example** + +```js +// This event is reported when an error occurs during the retrieval of videoRecordState. +videoRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, error: ${error}`); +}) +``` + +## VideoRecordState9+ + +Enumerates the video recording states. You can obtain the state through the **state** attribute. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +| Name | Type | Description | +| -------- | ------ | ---------------------- | +| idle | string | The video recorder is idle. | +| prepared | string | The video recording parameters are set.| +| playing | string | Video recording is in progress. | +| paused | string | Video recording is paused. | +| stopped | string | Video recording is stopped. | +| error | string | Video recording is in the error state. | + +## VideoRecorderConfig9+ + +Describes the video recording parameters. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. | +| videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. | +| profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | +| rotation | number | No | Rotation angle of the recorded video. | +| location | [Location](#location) | No | Geographical location of the recorded video. | +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png) | + +## VideoRecorderProfile9+ + +Describes the video recording profile. + +**System capability**: SystemCapability.Multimedia.Media.VideoRecorder + +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------------- | ---- | ---------------- | +| audioBitrate | number | Yes | Audio encoding bit rate.| +| audioChannels | number | Yes | Number of audio channels.| +| audioCodec | [CodecMimeType](#codecmimetype8) | Yes | Audio encoding format. | +| audioSampleRate | number | Yes | Audio sampling rate. | +| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.| +| videoBitrate | number | Yes | Video encoding bit rate.| +| videoCodec | [CodecMimeType](#codecmimetype8) | Yes | Video encoding format. | +| videoFrameWidth | number | Yes | Width of the recorded video frame.| +| videoFrameHeight | number | Yes | Height of the recorded video frame.| +| videoFrameRate | number | Yes | Video frame rate. | + +## media.createAudioPlayer(deprecated) + +createAudioPlayer(): AudioPlayer + +Creates an **AudioPlayer** instance in synchronous mode. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Return value** + +| Type | Description | +| --------------------------- | ------------------------------------------------------------ | +| [AudioPlayer](#audioplayerdeprecated) | If the operation is successful, an **AudioPlayer** instance is returned; otherwise, **null** is returned. After the instance is created, you can start, pause, or stop audio playback.| + +**Example** + +```js +let audioPlayer = media.createAudioPlayer(); +``` + +## media.createVideoPlayer(deprecated) + +createVideoPlayer(callback: AsyncCallback\): void + +Creates a **VideoPlayer** instance. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[VideoPlayer](#videoplayerdeprecated)> | Yes | Callback used to return the result. If the operation is successful, a **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| + +**Example** + +```js +let videoPlayer + +media.createVideoPlayer((error, video) => { + if (video != null) { + videoPlayer = video; + console.info('video createVideoPlayer success'); + } else { + console.info(`video createVideoPlayer fail, error:${error}`); + } +}); +``` + +## media.createVideoPlayer(deprecated) + +createVideoPlayer(): Promise\ + +Creates a **VideoPlayer** instance. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9-1) instead. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------------------------------ | +| Promise<[VideoPlayer](#videoplayerdeprecated)> | Promise used to return the result. If the operation is successful, a **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| + +**Example** + +```js +let videoPlayer + +media.createVideoPlayer().then((video) => { + if (video != null) { + videoPlayer = video; + console.info('video createVideoPlayer success'); + } else { + console.info('video createVideoPlayer fail'); + } +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +## media.createAudioRecorder(deprecated) + +createAudioRecorder(): AudioRecorder + +Creates an **AudioRecorder** instance to control audio recording. +Only one **AudioRecorder** instance can be created per device. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVRecorder](#mediacreateavrecorder9) instead. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, the **AudioRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio.| + +**Example** + +```js +let audioRecorder = media.createAudioRecorder(); +``` + +## MediaErrorCode(deprecated) + +Enumerates the media error codes. + +> **NOTE** +> +> This enum is supported since API version 8 and deprecated since API version 9. You are advised to use [Media Error Codes](../errorcodes/errorcode-media.md) instead. + +**System capability**: SystemCapability.Multimedia.Media.Core + +| Name | Value | Description | +| -------------------------- | ---- | -------------------------------------- | +| MSERR_OK | 0 | The operation is successful. | +| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| +| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform the operation. | +| MSERR_INVALID_VAL | 3 | Invalid input parameter. | +| MSERR_IO | 4 | An I/O error occurs. | +| MSERR_TIMEOUT | 5 | The operation times out. | +| MSERR_UNKNOWN | 6 | An unknown error occurs. | +| MSERR_SERVICE_DIED | 7 | Invalid server. | +| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state. | +| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version. | + +## AudioPlayer(deprecated) + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead. + +Provides APIs to manage and play audio. Before calling any API in **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayerdeprecated) to create an **AudioPlayer** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +| Name | Type | Readable| Writable| Description | +| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MP3, OGG, and WAV) are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio assets of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music assets consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent music file, use **src=fd://xx**.
| +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | +| currentTime | number | Yes | No | Current audio playback position, in ms. | +| duration | number | Yes | No | Audio duration, in ms. | +| state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| + +### play + +play(): void + +Starts to play an audio asset. This API can be called only after the [dataLoad](#audioplayer_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Example** + +```js +audioPlayer.on('play', () => { // Set the 'play' event callback. + console.log('audio play success'); +}); +audioPlayer.play(); +``` + +### pause + +pause(): void + +Pauses audio playback. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Example** + +```js +audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.log('audio pause success'); +}); +audioPlayer.pause(); +``` + +### stop + +stop(): void + +Stops audio playback. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Example** + +```js +audioPlayer.on('stop', () => { // Set the 'stop' event callback. + console.log('audio stop success'); +}); +audioPlayer.stop(); +``` + +### reset7+ + +reset(): void + +Resets the audio asset to be played. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Example** + +```js +audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.log('audio reset success'); +}); +audioPlayer.reset(); +``` + +### seek + +seek(timeMs: number): void + +Seeks to the specified playback position. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------------- | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| + +**Example** + +```js +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (seekDoneTime == null) { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); +}); +audioPlayer.seek(30000); // Seek to 30000 ms. +``` + +### setVolume + +setVolume(vol: number): void + +Sets the volume. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| + +**Example** + +```js +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.log('audio volumeChange success'); +}); +audioPlayer.setVolume(1); // Set the volume to 100%. +``` + +### release + +release(): void + +Releases the audio playback resources. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Example** + +```js +audioPlayer.release(); +audioPlayer = undefined; +``` + +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback\>): void + +Obtains the audio track information. This API uses an asynchronous callback to return the result. It can be called only after the [dataLoad](#audioplayer_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return a **MediaDescription** array, which records the audio track information.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + +audioPlayer.getTrackDescription((error, arrList) => { + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); + } + } else { + console.log(`audio getTrackDescription fail, error:${error}`); + } +}); +``` + +### getTrackDescription8+ + +getTrackDescription(): Promise\> + +Obtains the audio track information. This API uses a promise to return the result. It can be called only after the [dataLoad](#audioplayer_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | Promise used to return a **MediaDescription** array, which records the audio track information.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} +let arrayDescription = null +audioPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('audio getTrackDescription fail'); + } +}).catch((error) => { + console.info(`audio catchCallback, error:${error}`); +}); + +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} +``` + +### on('bufferingUpdate')8+ + +on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void + +Subscribes to the audio buffering update event. This API works only under online playback. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | +| callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| + +**Example** + +```js +audioPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('audio bufferingInfo type: ' + infoType); + console.log('audio bufferingInfo value: ' + value); +}); +``` + + ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + +on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void + +Subscribes to the audio playback events. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed. | +| callback | () => void | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +import fileio from '@ohos.fileio' + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Start the playback and trigger the 'play' event callback. +}); +audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. +}); +audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.info('audio pause success'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. +}); +audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.info('audio reset success'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; +}); +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (seekDoneTime == null) { + console.info('audio seek fail'); + return; + } + console.info('audio seek success, and seek time is ' + seekDoneTime); + audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. +}); +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.info('audio volumeChange success'); + audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. +}); +audioPlayer.on('finish', () => { // Set the 'finish' event callback. + console.info('audio play finish'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. +}); +audioPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, error: ${error}`); +}); + +// Set the FD (local playback) of the video file selected by the user. +let fdPath = 'fd://'; +// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. +let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; +fileio.open(path).then((fdValue) => { + fdPath = fdPath + '' + fdValue; + console.info('open fd success fd is' + fdPath); +}, (err) => { + console.info('open fd failed err is' + err); +}).catch((err) => { + console.info('open fd failed err is' + err); +}); +audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. +``` + +### on('timeUpdate') + +on(type: 'timeUpdate', callback: Callback\): void + +Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'timeUpdate'** in this case.
The **'timeUpdate'** event is triggered when the audio playback starts after an audio playback timestamp update.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter is the updated timestamp. | + +**Example** + +```js +audioPlayer.on('timeUpdate', (newTime) => { // Set the 'timeUpdate' event callback. + if (newTime == null) { + console.info('audio timeUpadate fail'); + return; + } + console.log('audio timeUpadate success. seekDoneTime: ' + newTime); +}); +audioPlayer.play(); // The 'timeUpdate' event is triggered when the playback starts. +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case.
This event is triggered when an error occurs during audio playback.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +audioPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, error: ${error}`); +}); +audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. +``` + +## AudioState(deprecated) + +Enumerates the audio playback states. You can obtain the state through the **state** attribute. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead. + +**System capability**: SystemCapability.Multimedia.Media.AudioPlayer + +| Name | Type | Description | +| ------- | ------ | ---------------------------------------------- | +| idle | string | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| +| playing | string | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | +| paused | string | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | +| stopped | string | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | +| error | string | Audio playback is in the error state. | + +## VideoPlayer(deprecated) + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead. + +Provides APIs to manage and play video. Before calling any API of **VideoPlayer**, you must use [createVideoPlayer()](#createvideoplayer) to create a **VideoPlayer** instance. + +For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). + +### Attributes + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +| Name | Type | Readable| Writable| Description | +| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| url8+ | string | Yes | Yes | Video URL. The mainstream video formats (MP4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of a video file. This attribute is required when video assets of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
| +| loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | +| currentTime8+ | number | Yes | No | Current video playback position, in ms. | +| duration8+ | number | Yes | No | Video duration, in ms. The value **-1** indicates the live mode. | +| state8+ | [VideoPlayState](#videoplayerstate) | Yes | No | Video playback state. | +| width8+ | number | Yes | No | Video width, in pixels. | +| height8+ | number | Yes | No | Video height, in pixels. | + +### setDisplaySurface8+ + +setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void + +Sets **SurfaceId**. This API uses an asynchronous callback to return the result. + +**SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------------- | +| surfaceId | string | Yes | Surface ID to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let surfaceId = null; +videoPlayer.setDisplaySurface(surfaceId, (err) => { + if (err == null) { + console.info('setDisplaySurface success!'); + } else { + console.info('setDisplaySurface fail!'); + } +}); +``` + +### setDisplaySurface8+ + +setDisplaySurface(surfaceId: string): Promise\ + +Sets **SurfaceId**. This API uses a promise to return the result. + +**SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------- | +| surfaceId | string | Yes | Surface ID to set.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let surfaceId = null; +videoPlayer.setDisplaySurface(surfaceId).then(() => { + console.info('setDisplaySurface success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### prepare8+ + +prepare(callback: AsyncCallback\): void + +Prepares for video playback. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.prepare((err) => { + if (err == null) { + console.info('prepare success!'); + } else { + console.info('prepare fail!'); + } +}); +``` + +### prepare8+ + +prepare(): Promise\ + +Prepares for video playback. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +videoPlayer.prepare().then(() => { + console.info('prepare success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### play8+ + +play(callback: AsyncCallback\): void; + +Starts to play video assets. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.play((err) => { + if (err == null) { + console.info('play success!'); + } else { + console.info('play fail!'); + } +}); +``` + +### play8+ + +play(): Promise\; + +Starts to play video assets. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +videoPlayer.play().then(() => { + console.info('play success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### pause8+ + +pause(callback: AsyncCallback\): void + +Pauses video playback. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.pause((err) => { + if (err == null) { + console.info('pause success!'); + } else { + console.info('pause fail!'); + } +}); +``` + +### pause8+ + +pause(): Promise\ + +Pauses video playback. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +videoPlayer.pause().then(() => { + console.info('pause success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### stop8+ + +stop(callback: AsyncCallback\): void + +Stops video playback. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.stop((err) => { + if (err == null) { + console.info('stop success!'); + } else { + console.info('stop fail!'); + } +}); +``` + +### stop8+ + +stop(): Promise\ + +Stops video playback. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +videoPlayer.stop().then(() => { + console.info('stop success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### reset8+ + +reset(callback: AsyncCallback\): void + +Resets the video asset to be played. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.reset((err) => { + if (err == null) { + console.info('reset success!'); + } else { + console.info('reset fail!'); + } +}); +``` + +### reset8+ + +reset(): Promise\ + +Resets the video asset to be played. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +videoPlayer.reset().then(() => { + console.info('reset success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### seek8+ + +seek(timeMs: number, callback: AsyncCallback\): void + +Seeks to the specified playback position. The previous key frame at the specified position is played. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let seekTime = 5000; +videoPlayer.seek(seekTime, (err, result) => { + if (err == null) { + console.info('seek success!'); + } else { + console.info('seek fail!'); + } +}); +``` + +### seek8+ + +seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void + +Seeks to the specified playback position. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import media from '@ohos.multimedia.media' +let seekTime = 5000; +videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => { + if (err == null) { + console.info('seek success!'); + } else { + console.info('seek fail!'); + } +}); +``` + +### seek8+ + +seek(timeMs: number, mode?:SeekMode): Promise\ + +Seeks to the specified playback position. If **mode** is not specified, the previous key frame at the specified position is played. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| mode | [SeekMode](#seekmode8) | No | Seek mode. | + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------- | +| Promise\| Promise used to return the playback position, in ms.| + +**Example** + +```js +import media from '@ohos.multimedia.media' +let seekTime = 5000; +videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. + console.info('seek success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); + +videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { + console.info('seek success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### setVolume8+ + +setVolume(vol: number, callback: AsyncCallback\): void + +Sets the volume. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let vol = 0.5; +videoPlayer.setVolume(vol, (err, result) => { + if (err == null) { + console.info('setVolume success!'); + } else { + console.info('setVolume fail!'); + } +}); +``` + +### setVolume8+ + +setVolume(vol: number): Promise\ + +Sets the volume. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let vol = 0.5; +videoPlayer.setVolume(vol).then(() => { + console.info('setVolume success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### release8+ + +release(callback: AsyncCallback\): void + +Releases the video playback resources. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +videoPlayer.release((err) => { + if (err == null) { + console.info('release success!'); + } else { + console.info('release fail!'); + } +}); +``` + +### release8+ + +release(): Promise\ + +Releases the video playback resources. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +videoPlayer.release().then(() => { + console.info('release success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback\>): void + +Obtains the video track information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return a **MediaDescription** array, which records the video track information.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } +} + +videoPlayer.getTrackDescription((error, arrList) => { + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); + } + } else { + console.log(`video getTrackDescription fail, error:${error}`); + } +}); +``` + +### getTrackDescription8+ + +getTrackDescription(): Promise\> + +Obtains the video track information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | Promise used to return a **MediaDescription** array, which records the video track information.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } +} + +let arrayDescription; +videoPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('video getTrackDescription fail'); + } +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} +``` + +### setSpeed8+ + +setSpeed(speed:number, callback: AsyncCallback\): void + +Sets the video playback speed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------------------------------------------- | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import media from '@ohos.multimedia.media' +let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; + +videoPlayer.setSpeed(speed, (err, result) => { + if (err == null) { + console.info('setSpeed success!'); + } else { + console.info('setSpeed fail!'); + } +}); +``` + +### setSpeed8+ + +setSpeed(speed:number): Promise\ + +Sets the video playback speed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------------------------- | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\| Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| + +**Example** + +```js +import media from '@ohos.multimedia.media' +let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; + +videoPlayer.setSpeed(speed).then(() => { + console.info('setSpeed success'); +}).catch((error) => { + console.info(`video catchCallback, error:${error}`); +}); +``` + +### on('playbackCompleted')8+ + +on(type: 'playbackCompleted', callback: Callback\): void + +Subscribes to the video playback completion event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| type | string | Yes | Event type, which is **'playbackCompleted'** in this case.| +| callback | function | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoPlayer.on('playbackCompleted', () => { + console.info('playbackCompleted success!'); +}); +``` + +### on('bufferingUpdate')8+ + +on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void + +Subscribes to the video buffering update event. Only network playback supports this subscription. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | +| callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| + +**Example** + +```js +videoPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('video bufferingInfo type: ' + infoType); + console.log('video bufferingInfo value: ' + value); +}); +``` + +### on('startRenderFrame')8+ + +on(type: 'startRenderFrame', callback: Callback\): void + +Subscribes to the frame rendering start event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoPlayer.on('startRenderFrame', () => { + console.info('startRenderFrame success!'); +}); +``` + +### on('videoSizeChanged')8+ + +on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void + +Subscribes to the video width and height change event. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'videoSizeChanged'** in this case.| +| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | + +**Example** + +```js +videoPlayer.on('videoSizeChanged', (width, height) => { + console.log('video width is: ' + width); + console.log('video height is: ' + height); +}); +``` + +### on('error')8+ + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case.
This event is triggered when an error occurs during video playback.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +videoPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`video error called, error: ${error}`); +}); +videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. +``` + +## VideoPlayState(deprecated) + +Enumerates the video playback states. You can obtain the state through the **state** attribute. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +| Name | Type | Description | +| -------- | ------ | -------------- | +| idle | string | The video player is idle.| +| prepared | string | Video playback is being prepared.| +| playing | string | Video playback is in progress.| +| paused | string | Video playback is paused.| +| stopped | string | Video playback is stopped.| +| error | string | Video playback is in the error state. | + +## AudioRecorder(deprecated) + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder](#avrecorder9) instead. + +Implements audio recording. Before calling any API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. + +For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). + +### prepare + +prepare(config: AudioRecorderConfig): void + +Prepares for recording. + +**Required permissions:** ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| config | [AudioRecorderConfig](#audiorecorderconfigdeprecated) | Yes | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.| + +**Example** + +```js +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. + console.log('prepare success'); +}); +audioRecorder.prepare(audioRecorderConfig); +``` + + +### start + +start(): void + +Starts audio recording. This API can be called only after the [prepare](#audiorecorder_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('start', () => { // Set the 'start' event callback. + console.log('audio recorder start success'); +}); +audioRecorder.start(); +``` + +### pause + +pause():void + +Pauses audio recording. This API can be called only after the [start](#audiorecorder_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('pause', () => { // Set the 'pause' event callback. + console.log('audio recorder pause success'); +}); +audioRecorder.pause(); +``` + +### resume + +resume():void + +Resumes audio recording. This API can be called only after the [pause](#audiorecorder_on) event is triggered. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('resume', () => { // Set the 'resume' event callback. + console.log('audio recorder resume success'); +}); +audioRecorder.resume(); +``` + +### stop + +stop(): void + +Stops audio recording. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('stop', () => { // Set the 'stop' event callback. + console.log('audio recorder stop success'); +}); +audioRecorder.stop(); +``` + +### release + +release(): void + +Releases the audio recording resources. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('release', () => { // Set the 'release' event callback. + console.log('audio recorder release success'); +}); +audioRecorder.release(); +audioRecorder = undefined; +``` + +### reset + +reset(): void + +Resets audio recording. + +Before resetting audio recording, you must call [stop()](#audiorecorder_stop) to stop recording. After audio recording is reset, you must call [prepare()](#audiorecorder_prepare) to set the recording parameters for another recording. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Example** + +```js +audioRecorder.on('reset', () => { // Set the 'reset' event callback. + console.log('audio recorder reset success'); +}); +audioRecorder.reset(); +``` + +### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset') + +on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void + +Subscribes to the audio recording events. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resources are released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset. | +| callback | ()=>void | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, error: ${error}`); +}); +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. + console.log('prepare success'); + audioRecorder.start(); // Start recording and trigger the 'start' event callback. +}); +audioRecorder.on('start', () => { // Set the 'start' event callback. + console.log('audio recorder start success'); +}); +audioRecorder.on('pause', () => { // Set the 'pause' event callback. + console.log('audio recorder pause success'); +}); +audioRecorder.on('resume', () => { // Set the 'resume' event callback. + console.log('audio recorder resume success'); +}); +audioRecorder.on('stop', () => { // Set the 'stop' event callback. + console.log('audio recorder stop success'); +}); +audioRecorder.on('release', () => { // Set the 'release' event callback. + console.log('audio recorder release success'); +}); +audioRecorder.on('reset', () => { // Set the 'reset' event callback. + console.log('audio recorder reset success'); +}); +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type, which is **'error'** in this case.
This event is triggered when an error occurs during audio recording.| +| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | + +**Example** + +```js +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, +} +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, error: ${error}`); +}); +audioRecorder.prepare(audioRecorderConfig); // Do no set any parameter in prepare and trigger the 'error' event callback. +``` + +## AudioRecorderConfig(deprecated) + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorderConfig](#avrecorderconfig9) instead. + +Describes audio recording configurations. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +| Name | Type | Mandatory| Description | +| ----------------------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoderdeprecated) | No | Audio encoding format. The default value is **AAC_LC**.
**Note**: This parameter is deprecated since API version 8. Use **audioEncoderMime** instead.| +| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**. | +| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | +| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | +| format | [AudioOutputFormat](#audiooutputformatdeprecated) | No | Audio output format. The default value is **MPEG_4**.
**Note**: This parameter is deprecated since API version 8. Use **fileFormat** instead.| +| location | [Location](#location) | No | Geographical location of the recorded audio. | +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| audioEncoderMime8+ | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | +| fileFormat8+ | [ContainerFormatType](#containerformattype8) | No | Audio encoding format. | + +## AudioEncoder(deprecated) + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead. + +Enumerates the audio encoding formats. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +| Name | Value | Description | +| ------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet. | +| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| + +## AudioOutputFormat(deprecated) + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead. + +Enumerates the audio output formats. + +**System capability**: SystemCapability.Multimedia.Media.AudioRecorder + +| Name | Value | Description | +| -------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet. | +| MPEG_4 | 2 | MPEG-4. | +| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet. | +| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet. | +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index c023229badd1808170022d641415172bf2f899d0..c7b8ecb87cca8ffe72417ca65c07086c8421fae1 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -84,13 +84,13 @@ Activates an OS account. This API uses an asynchronous callback to return the re try { accountManager.activateOsAccount(localId, (err)=>{ if (err) { - console.log("activateOsAccount failed, error:" + JSON.stringify(err)); + console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`); } else { console.log("activateOsAccount successfully"); } }); } catch (err) { - console.log("activateOsAccount exception:" + JSON.stringify(err)); + console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -170,13 +170,13 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous try { accountManager.checkMultiOsAccountEnabled((err, isEnabled) => { if (err) { - console.log("checkMultiOsAccountEnabled failed, error: " + JSON.stringify(err)); + console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); } else { console.log("checkMultiOsAccountEnabled successfully, isEnabled: " + isEnabled); } }); } catch (err) { - console.log("checkMultiOsAccountEnabled exception: " + JSON.stringify(err)); + console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -208,10 +208,10 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re accountManager.checkMultiOsAccountEnabled().then((isEnabled) => { console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled); }).catch((err) => { - console.log('checkMultiOsAccountEnabled failed, error: ' + JSON.stringify(err)); + console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); }); } catch (err) { - console.log('checkMultiOsAccountEnabled exception: ' + JSON.stringify(err)); + console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -3604,7 +3604,7 @@ Obtains the type of the account to which the current process belongs. This API u getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void -Obtains the ID of the distributed virtual device. This API uses an asynchronous callback to return the result. +Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result. > **NOTE** > @@ -3634,7 +3634,7 @@ Obtains the ID of the distributed virtual device. This API uses an asynchronous getDistributedVirtualDeviceId(): Promise<string> -Obtains the ID of the distributed virtual device. This API uses a promise to return the result. +Obtains the ID of this distributed virtual device. This API uses a promise to return the result. > **NOTE** > @@ -4323,13 +4323,13 @@ Unregisters this PIN inputer. pinAuth.unregisterInputer(); ``` -### InputerManager 10+ +## InputerManager 9+ Provides APIs for managing credential inputers. -### registerInputer10+ +### registerInputer9+ -registerInputer(authType: AuthType, inputer: IInputer): void; +static registerInputer(authType: AuthType, inputer: IInputer): void Register a credential inputer. @@ -4357,11 +4357,10 @@ Register a credential inputer. **Example** ```js - let inputerMgr = new account_osAccount.InputerManager(); let authType = account_osAccount.AuthType.DOMAIN; let password = new Uint8Array([0, 0, 0, 0, 0]); try { - inputerMgr.registerInputer(authType, { + account_osAccount.InputerManager.registerInputer(authType, { onGetData: (authSubType, callback) => { callback.onSetData(authSubType, password); } @@ -4372,9 +4371,9 @@ Register a credential inputer. } ``` -### unregisterInputer10+ +### unregisterInputer9+ -unregisterInputer(authType: AuthType): void; +static unregisterInputer(authType: AuthType): void Unregisters this credential inputer. @@ -4398,16 +4397,129 @@ Unregisters this credential inputer. **Example** ```js - let inputerMgr = new account_osAccount.InputerManager(); let authType = account_osAccount.AuthType.DOMAIN; try { - inputerMgr.unregisterInputer(authType); + account_osAccount.InputerManager.unregisterInputer(authType); console.log('unregisterInputer success.'); } catch(err) { console.log("unregisterInputer err:" + JSON.stringify(err)); } ``` +## DomainPlugin9+ + +Provides APIs for domain account authentication. + +**System API**: This is a system API. + +### auth9+ + +auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUserAuthCallback): void + +Authenticates a domain account. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------------- | ---- | --------------- | +| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| +| credential | Uint8Array | Yes | Credentials of the domain account.| +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result.| + +**Example** + ```js + let plugin = { + auth: (domainInfo, credential, callback) => { + // mock authentication + callback.onResult(0, {}); + } + } + account_osAccount.DomainAccountManager.registerPlugin(plugin); + let userAuth = new account_osAccount.UserAuth(); + let challenge = new Uint8Array([0]); + let authType = account_osAccount.AuthType.PIN; + let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; + try { + userAuth.auth(challenge, authType, authTrustLevel, { + onResult: (resultCode, authResult) => { + console.log('auth resultCode = ' + resultCode); + console.log('auth authResult = ' + JSON.stringify(authResult)); + } + }); + } catch (err) { + console.log('auth exception = ' + JSON.stringify(err)); + } + ``` + +## DomainAccountManager 9+ +Provides APIs for domain account management. + +### registerPlugin9+ + +static registerPlugin(plugin: DomainPlugin): void + +Registers a domain plug-in. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| plugin | [DomainPlugin](#domainplugin9) | Yes | Domain plug-in to register.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300201 | The domain plugin has been registered. | + +**Example** + ```js + let plugin = { + auth: (domainInfo, credential, callback) => { + // mock authentication + callback.onResult(0, {}); + } + } + try { + account_osAccount.DomainAccountManager.registerPlugin(plugin); + console.log('registerPlugin success.'); + } catch(err) { + console.log("registerPlugin err:" + JSON.stringify(err)); + } + ``` + +### unregisterPlugin9+ + +static unregisterPlugin(): void + +Unregisters this domain plug-in. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**Example** + ```js + try { + account_osAccount.DomainAccountManager.unregisterPlugin(); + console.log('unregisterPlugin success.'); + } catch(err) { + console.log("unregisterPlugin err:" + JSON.stringify(err)); + } + ``` + ## UserIdentityManager8+ Provides APIs for user identity management (IDM). diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index c7da8609952d245b53e82aead09f57f97eeeedf1..7880d8a09af980bbc51635e7220738722142829b 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -120,9 +120,9 @@ try { } ``` -## privacyManager.getPermissionUsedRecords +## privacyManager.getPermissionUsedRecord -getPermissionUsedRecords(request: PermissionUsedRequest): Promise<PermissionUsedResponse> +getPermissionUsedRecord(request: PermissionUsedRequest): Promise<PermissionUsedResponse> Obtains historical permission usage records. This API uses a promise to return the result. @@ -170,19 +170,19 @@ let request = { "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { - privacyManager.getPermissionUsedRecords(request).then((data) => { - console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + privacyManager.getPermissionUsedRecord(request).then((data) => { + console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`); }).catch((err) => { - console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } ``` -## privacyManager.getPermissionUsedRecords +## privacyManager.getPermissionUsedRecord -getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void +getPermissionUsedRecord(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void Obtains historical permission usage records. This API uses an asynchronous callback to return the result. @@ -225,11 +225,11 @@ let request = { "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { - privacyManager.getPermissionUsedRecords(request, (err, data) => { + privacyManager.getPermissionUsedRecord(request, (err, data) => { if (err) { - console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`); } else { - console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`); } }); } catch(err) { diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md index 2d01a8db31a0a0f01f62ce4747ef2d6449b348e3..4250e7503f68a0ef1144531c2f2ac74c5143edd4 100644 --- a/en/application-dev/reference/apis/js-apis-promptAction.md +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | +| 100001 | if UI execution context not found. | **Example** @@ -40,7 +40,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ try { promptAction.showToast({ message: 'Message Info', - duration: 2000, + duration: 2000 }); } catch (error) { console.error(`showToast args error code is ${error.code}, message is ${error.message}`); @@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | +| 100001 | if UI execution context not found. | **Example** @@ -100,11 +100,11 @@ try { buttons: [ { text: 'button1', - color: '#000000', + color: '#000000' }, { text: 'button2', - color: '#000000', + color: '#000000' } ], }) @@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | +| 100001 | if UI execution context not found. | **Example** @@ -154,11 +154,11 @@ try { buttons: [ { text: 'button1', - color: '#000000', + color: '#000000' }, { text: 'button2', - color: '#000000', + color: '#000000' } ] }, (err, data) => { @@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | +| 100001 | if UI execution context not found. | **Example** @@ -229,11 +229,11 @@ try { buttons: [ { text: 'item1', - color: '#666666', + color: '#666666' }, { text: 'item2', - color: '#000000', + color: '#000000' }, ] }, (err, data) => { @@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | +| 100001 | if UI execution context not found. | **Example** @@ -287,11 +287,11 @@ try { buttons: [ { text: 'item1', - color: '#666666', + color: '#666666' }, { text: 'item2', - color: '#000000', + color: '#000000' }, ] }) diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 4c4b818f1cb692f8ff5256017287fc9e36d9075a..1234e81445de56ead44aaf2f118c53f0e12e7dbc 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -563,6 +563,7 @@ Describes the page routing options. > **NOTE** + > > The page routing stack supports a maximum of 32 pages. ## RouterMode9+ diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md index 59647b01e2595656e49753a120157ab0e0cae153..9e3d28d465e097d57055339534152f72d53b95fc 100644 --- a/en/application-dev/reference/apis/js-apis-statfs.md +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -4,7 +4,9 @@ The **statfs** module provides APIs for obtaining file system information, inclu > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.statvfs](js-apis-file-statvfs.md). ## Modules to Import @@ -21,15 +23,15 @@ Obtains the number of free bytes of the specified file system in asynchronous mo **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| **Return value** - | Type | Description | - | --------------------- | -------------- | - | Promise<number> | Promise used to return the number of free bytes obtained.| +| Type | Description | +| --------------------- | -------------- | +| Promise<number> | Promise used to return the number of free bytes obtained.| **Example** @@ -52,10 +54,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| - | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| **Example** @@ -79,15 +81,15 @@ Obtains the total number of bytes of the specified file system in asynchronous m **Parameters** - | Name| Type | Mandatory| Description | - | ---- | ------ | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| **Return value** - | Type | Description | - | --------------------- | ------------ | - | Promise<number> | Promise used to return the total number of bytes obtained.| +| Type | Description | +| --------------------- | ------------ | +| Promise<number> | Promise used to return the total number of bytes obtained.| **Example** @@ -110,10 +112,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| - | callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md index 5f33952a9d0d8401ae69f683f0cd4f1eb7dd43f4..831a8acabb7735d67f119370155e13d1bf929ce0 100644 --- a/en/application-dev/reference/apis/js-apis-system-prompt.md +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -38,7 +38,7 @@ export default { showToast() { prompt.showToast({ message: 'Message Info', - duration: 2000, + duration: 2000 }); } } @@ -67,11 +67,11 @@ export default { showDialog() { prompt.showDialog({ title: 'Title Info', - message: 'Message Info', + message: 'Message Info', buttons: [ { text: 'button', - color: '#666666', + color: '#666666' }, ], success: function(data) { @@ -110,12 +110,12 @@ export default { buttons: [ { text: 'item1', - color: '#666666', + color: '#666666' }, { text: 'item2', - color: '#000000', - }, + color: '#000000' + }, ], success: function(tapIndex) { console.log('dialog success callback, click button : ' + data.tapIndex); diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index 8c229cc5ec06e1bef82452420848b8175a02c22c..d738e7b69170bc84f17286594cfd98b3ff908249 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -31,7 +31,7 @@ Enumerates the match patterns supported for component attributes. | Name | Value | Description | | ----------- | ---- | -------------- | -| EQUALS | 0 | Equal to the given value. | +| EQUALS | 0 | Equals the given value. | | CONTAINS | 1 | Contains the given value. | | STARTS_WITH | 2 | Starts with the given value.| | ENDS_WITH | 3 | Ends with the given value.| @@ -70,12 +70,12 @@ Provides bounds information of a component. **System capability**: SystemCapability.Test.UiTest -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------------------- | -| leftX | number | Yes | No | X-coordinate of the upper left corner of the component bounds.| -| topY | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.| -| rightX | number | Yes | No | X-coordinate of the lower right corner of the component bounds.| -| bottomY | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.| +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ------------------------- | +| left | number | Yes | No | X-coordinate of the upper left corner of the component bounds.| +| top | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.| +| right | number | Yes | No | X-coordinate of the lower right corner of the component bounds.| +| bottom | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.| ## WindowMode9+ @@ -219,7 +219,7 @@ Specifies the clickable status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| b | boolean | No | Clickable status of the target component.
**true**: clickable.
**false**: not clickable.
Default value: **true**| +| b | boolean | No | Clickable status of the target component.
**true**: clickable.
**false**: not clickable.
Default value: **true** | **Return value** @@ -245,7 +245,7 @@ Specifies the long-clickable status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| b | boolean | No | Long-clickable status of the target component.
**true**: long-clickable.
**false**: not long-clickable.
Default value: **true**| +| b | boolean | No | Long-clickable status of the target component.
**true**: long-clickable.
**false**: not long-clickable.
Default value: **true** | **Return value** @@ -272,7 +272,7 @@ Specifies the scrollable status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------------------------------- | -| b | boolean | No | Scrollable status of the target component.
**true**: scrollable.
**false**: not scrollable.
Default value: **true**| +| b | boolean | No | Scrollable status of the target component.
**true**: scrollable.
**false**: not scrollable.
Default value: **true** | **Return value** @@ -298,7 +298,7 @@ Specifies the enabled status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | --------------------------------------------------------- | -| b | boolean | No | Enabled status of the target component.
**true**: enabled.
**false**: disabled.
Default value: **true**| +| b | boolean | No | Enabled status of the target component.
**true**: enabled.
**false**: not enabled.
Default value: **true** | **Return value** @@ -324,7 +324,7 @@ Specifies the focused status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------------------------- | -| b | boolean | No | Focused status of the target component.
**true**: focused.
**false**: not focused.
Default value: **true**| +| b | boolean | No | Focused status of the target component.
**true**: focused.
**false**: not focused.
Default value: **true** | **Return value** @@ -350,7 +350,7 @@ Specifies the selected status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| b | boolean | No | Selected status of the target component.
**true**: selected.
**false**: not selected.
Default value: **true**| +| b | boolean | No | Selected status of the target component.
**true**: selected.
**false**: not selected.
Default value: **true** | **Return value** @@ -376,7 +376,7 @@ Specifies the checked status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| b | boolean | No | Checked status of the target component.
**true**: checked.
**false**: not checked.
Default value: **false**| +| b | boolean | No | Checked status of the target component.
**true**: checked.
**false**: not checked.
Default value: **false** | **Return value** @@ -402,7 +402,7 @@ Specifies the checkable status attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| b | boolean | No | Checkable status of the target component.
**true**: checkable.
**false**: not checkable.
Default value: **false**| +| b | boolean | No | Checkable status of the target component.
**true**: checkable.
**false**: not checkable.
Default value: **false** | **Return value** @@ -2788,7 +2788,7 @@ This API is deprecated since API version 9. You are advised to use [clickable**true**: clickable.
**false**: not clickable.
Default value: **true**| +| b | boolean | No | Clickable status of the target component.
**true**: clickable.
**false**: not clickable.
Default value: **true** | **Return value** @@ -2817,7 +2817,7 @@ This API is deprecated since API version 9. You are advised to use [scrollable**true**: scrollable.
**false**: not scrollable.
Default value: **true**| +| b | boolean | No | Scrollable status of the target component.
**true**: scrollable.
**false**: not scrollable.
Default value: **true** | **Return value** @@ -2845,7 +2845,7 @@ This API is deprecated since API version 9. You are advised to use [enabled | Name| Type | Mandatory| Description | | ------ | ------- | ---- | --------------------------------------------------------- | -| b | boolean | No | Enabled status of the target component.
**true**: enabled.
**false**: not disabled.
Default value: **true**| +| b | boolean | No | Enabled status of the target component.
**true**: enabled.
**false**: not enabled.
Default value: **true** | **Return value** @@ -2873,7 +2873,7 @@ This API is deprecated since API version 9. You are advised to use [focused | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------------------------- | -| b | boolean | No | Focused status of the target component.
**true**: focused.
**false**: not focused.
Default value: **true**| +| b | boolean | No | Focused status of the target component.
**true**: focused.
**false**: not focused.
Default value: **true** | **Return value** @@ -2901,7 +2901,7 @@ This API is deprecated since API version 9. You are advised to use [selected**true**: selected.
**false**: not selected.
Default value: **true**| +| b | boolean | No | Selected status of the target component.
**true**: selected.
**false**: not selected.
Default value: **true** | **Return value** diff --git a/en/application-dev/reference/arkui-ts/figures/datePicker.gif b/en/application-dev/reference/arkui-ts/figures/datePicker.gif new file mode 100644 index 0000000000000000000000000000000000000000..52ee9ca7eb42b521cf879e364c95694ca698b834 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/datePicker.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/timePicker.gif b/en/application-dev/reference/arkui-ts/figures/timePicker.gif index 9ae06ee5b27f1b4ce369b8e90ef5602a1ea0f846..57ba2404c92ca64f11dba247f081fc2da5aacf44 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/timePicker.gif and b/en/application-dev/reference/arkui-ts/figures/timePicker.gif differ diff --git a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md index 42192691a4127493dfe94fbef0d67135f870a253..2c352ff97bc21223625ffc048353711b949e040a 100644 --- a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md +++ b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md @@ -1,10 +1,5 @@ # File Management Error Codes -The error codes of the file management subsystem consist of the following: - -- Basic file I/O error codes -- User data management error codes -- User file access error codes -- Spatial statistics error codes +The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes ## Basic File I/O Error Codes @@ -719,3 +714,41 @@ Fail to notify agent **Solution** Check whether the client is normal. + +## Error Code Adaptation +The APIs provided by the file management subsystem support exception handling. +Sample code for exception handling in a synchronous API: +```js +import fs from '@ohos.file.fs' + +try { + let file = fs.openSync(path, fs.OpenMode.READ_ONLY); +} catch (err) { + console.error("openSync errCode:" + err.code + ", errMessage:" + err.message); +} +``` +Sample code for exception handling in an asynchronous API (promise): +```js +import fs from '@ohos.file.fs' + +try { + let file = await fs.open(path, fs.OpenMode.READ_ONLY); +} catch (err) { + console.error("open promise errCode:" + err.code + ", errMessage:" + err.message); +} +``` + +Sample code for exception handling in an asynchronous API (callback): +```js +import fs from '@ohos.file.fs' + +try { + fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ // Asynchronous thread (such as the system call) errors are obtained via a callback. + if (e) { + console.error("open in async errCode:" + e.code + ", errMessage:" + e.message); + } + }); +} catch (err) {// Main thread errors (such as invalid parameters) are obtained by try catch. + console.error("open callback errCode:" + err.code + ", errMessage:" + err.message); +} +``` diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index ff90272d78f26b485b9e916e4ae91ac2ffd724c2..e77eac675a9df3d0e219b4453f7a676b4e806d13 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -534,9 +534,9 @@ Allows an application to change the telephone state. **Enable ACL**: TRUE -## ohos.permission.START_ABILIIES_FROM_BACKGROUND +## ohos.permission.START_ABILITIES_FROM_BACKGROUND -Allows an application to start Feature abilities in the background. +Allows an application to start or access other components from the background. **Permission level**: system_basic @@ -1594,6 +1594,16 @@ Allows a system application to obtain the authentication and networking capabili **Enable ACL**: TRUE +## ohos.permission.APP_TRACKING_CONSENT + +Allows an application to read advertisement identifiers. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + ## ohos.permission.RUN_ANY_CODE Allows an application to run unsigned code. diff --git a/en/device-dev/kernel/Readme-EN.md b/en/device-dev/kernel/Readme-EN.md index c4f235a182ed7c115d943f0f711e2a9bc0ceba8d..ad2bb3f9e459a3d8fbee4edf192dd74187ff7fbe 100644 --- a/en/device-dev/kernel/Readme-EN.md +++ b/en/device-dev/kernel/Readme-EN.md @@ -26,6 +26,7 @@ - [Exception Debugging](kernel-mini-memory-exception.md) - [Trace](kernel-mini-memory-trace.md) - [LMS](kernel-mini-memory-lms.md) + - [Shell](kernel-mini-debug-shell.md) - Appendix - [Kernel Coding Specification](kernel-mini-appx-code.md) - [Standard Libraries](kernel-mini-appx-lib.md) diff --git a/en/device-dev/kernel/kernel-mini-appx-lib.md b/en/device-dev/kernel/kernel-mini-appx-lib.md index 9f1021017b7ae99e88bee3430cf365076226b739..17a997d2411dc5ec5b9f9b4231c99dc526d77d2b 100644 --- a/en/device-dev/kernel/kernel-mini-appx-lib.md +++ b/en/device-dev/kernel/kernel-mini-appx-lib.md @@ -177,7 +177,7 @@ int main (void) { // ... osKernelInitialize(); // Initialize CMSIS-RTOS. - osThreadNew(app_main, NULL, NULL); // Create the main thread of the application. + osThreadNew(app_main, NULL, NULL); // Create the main thread of the application. osKernelStart(); // Start to execute the thread. for (;;) {} } @@ -196,14 +196,14 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an #### Available APIs - **Table 1** APIs for process management + **Table 11** APIs for process management | Header File| API| Description| | -------- | -------- | -------- | | \#include <stdlib.h> | void abort(void); | Terminates the thread.| | \#include <assert.h> | void assert(scalar expression); | Terminates the thread if the assertion is false.| -| \#include <pthread.h> | int pthread_cond_destroy(pthread_cond_t *cond); | Destroys a condition variable.| -| \#include <pthread.h> | int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t \*restrict attr); | Initializes a condition variable.| +| \#include <pthread.h> | int pthread_cond_destroy(pthread_cond_t \*cond); | Destroys a condition variable.| +| \#include <pthread.h> | int pthread_cond_init(pthread_cond_t \*restrict cond, const pthread_condattr_t \*restrict attr); | Initializes a condition variable.| | \#include <pthread.h> | int pthread_cond_timedwait(pthread_cond_t \*restrict cond, pthread_mutex_t \*restrict mutex, const struct timespec \*restrict abstime); | Waits for the condition.| | \#include <pthread.h> | int pthread_condattr_init(pthread_condattr_t \*attr); | Initializes the condition variable attribute.| | \#include <pthread.h> | int pthread_mutex_unlock(pthread_mutex_t \*mutex); | Unlocks a mutex.| @@ -212,13 +212,13 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <pthread.h> | pthread_t pthread_self(void); | Obtains the ID of the current thread.| | \#include <pthread.h> | int pthread_getschedparam(pthread_t thread, int \*policy, struct sched_param \*param); | Obtains the scheduling policy and parameters of a thread.| | \#include <pthread.h> | int pthread_setschedparam(pthread_t thread, intpolicy, const struct sched_param \*param); | Sets a scheduling policy and parameters for a thread.| -| \#include <pthread.h> | int pthread_mutex_init(pthread_mutex_t \* __restrict m, const pthread_mutexattr_t \*__restrict a); | Initializes a mutex.| +| \#include <pthread.h> | int pthread_mutex_init(pthread_mutex_t *\_restrict m, const pthread_mutexattr_t \*__restrict a); | Initializes a mutex.| | \#include <pthread.h> | int pthread_mutex_lock(pthread_mutex_t \*m); | Locks a mutex.| | \#include <pthread.h> | int pthread_mutex_trylock(pthread_mutex_t \*m); | Attempts to lock a mutex.| | \#include <pthread.h> | int pthread_mutex_destroy(pthread_mutex_t \*m); | Destroys a mutex.| | \#include <pthread.h> | int pthread_attr_init(pthread_attr_t \*attr); | Initializes a thread attribute object.| | \#include <pthread.h> | int pthread_attr_destroy(pthread_attr_t \*attr); | Destroys a thread attribute object.| -| \#include <pthread.h> | int pthread_attr_getstacksize(const pthread_attr_t \*attr, size_t \*stacksize); | Obtains the stack size of a thread attribute object.| +| \#include <pthread.h> | int pthread_attr_getstacksize(const pthread_attr*t \*attr, size*t \*stacksize); | Obtains the stack size of a thread attribute object.| | \#include <pthread.h> | int pthread_attr_setstacksize(pthread_attr_t \*attr, size_t stacksize); | Sets the stack size for a thread attribute object.| | \#include <pthread.h> | int pthread_attr_getschedparam(const pthread_attr_t \*attr, struct sched_param \*param); | Obtains scheduling parameter attributes of a thread attribute object.| | \#include <pthread.h> | int pthread_attr_setschedparam(pthread_attr_t \*attr, const struct sched_param \*param); | Sets scheduling parameter attributes for a thread attribute object.| @@ -226,9 +226,9 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <pthread.h> | int pthread_setname_np(pthread_t pthread, constchar \*name); | Sets the thread name.| | \#include <pthread.h> | int pthread_cond_broadcast(pthread_cond_t \*c); | Unblocks all threads that are currently blocked on the condition variable **cond**.| | \#include <pthread.h> | int pthread_cond_signal(pthread_cond_t \*c); | Unblocks a thread.| -| \#include <pthread.h> | int pthread_cond_wait(pthread_cond_t \*__restrictc, pthread_mutex_t \*__restrict m); | Waits for the condition.| +| \#include <pthread.h> | int pthread_cond_wait(pthread_cond_t *\__restrictc, pthread_mutex_t \*__restrict m); | Waits for the condition.| - **Table 2** APIs for file system management + **Table 12** APIs for file system management | Header File| API| Description| | -------- | -------- | -------- | @@ -250,7 +250,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <sys/stat.h> | int fstat(int fd, struct stat \*buf); | Obtains file status.| | \#include <sys/statfs.h> | int statfs(const char \*path, struct statfs \*buf); | Obtains the file system information for a file in a specified path.| - **Table 3** APIs for time management + **Table 13** APIs for time management | Header File| API| Description| | -------- | -------- | -------- | @@ -265,19 +265,19 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <unistd.h> | int usleep(useconds_t usec); | Goes to hibernation, in microseconds.| | \#include <time.h> | int nanosleep(const struct timespec \*tspec1, structtimespec \*tspec2); | Suspends the current thread till the specified time.| | \#include <time.h> | int clock_gettime(clockid_t id, struct timespec \*tspec); | Obtains the clock time.| -| \#include <time.h> | int timer_create(clockid_t id, struct sigevent \*__restrict evp, timer_t \*__restrict t); | Creates a timer for a thread.| +| \#include <time.h> | int timer_create(clockid_t id, struct sigevent *\__restrict evp, timer_t \*__restrict t); | Creates a timer for a thread.| | \#include <time.h> | int timer_delete(timer_t t); | Deletes the timer for a thread.| -| \#include <time.h> | int timer_settime(timer_t t, int flags, const structitimerspec \*__restrict val, struct itimerspec \*__restrict old); | Sets a timer for a thread.| +| \#include <time.h> | int timer_settime(timer_t t, int flags, const struct itimerspec *\__restrict val, struct itimerspec \*_restrict old); | Sets a timer for a thread.| | \#include <time.h> | time_t time (time_t \*t); | Obtains the time.| | \#include <time.h> | char \*strptime(const char \*s, const char \*format, struct tm \*tm); | Converts the time string into the time **tm** structure.| - **Table 4** APIs for util + **Table 14** APIs for util | Header File| API| Description| | -------- | -------- | -------- | -| \#include <stdlib.h> | int atoi(const char \*nptr); | Converts the string pointed to by **nptr** into an integer (**int** type).| -| \#include <stdlib.h> | long atol(const char \*nptr); | Converts the string pointed to by **nptr** into a long Integer (long type).| -| \#include <stdlib.h> | long long atoll(const char \*nptr); | Converts the string pointed to by **nptr** into a long long Integer (long long type).| +| \#include <stdlib.h> | int atoi(const char \*nptr); | Converts a string into an integer (**int** type).| +| \#include <stdlib.h> | long atol(const char \*nptr); | Converts the string into a long Integer (**long** type).| +| \#include <stdlib.h> | long long atoll(const char \*nptr); | Converts a string into a long longer integer (**long long** type).| | \#include <ctype.h> | int isalnum(int c); | Checks whether the passed character is alphanumeric.| | \#include <ctype.h> | int isascii(int c); | Checks whether the passed character is an ASCII character.| | \#include <ctype.h> | int isdigit(int c); | Checks whether the passed character is a digit.| @@ -302,17 +302,17 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <strings.h> | int strncasecmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings, ignoring case.| | \#include <strings.h> | int strcasecmp(const char \*s1, const char \*s2); | Compares two strings, ignoring case.| | \#include <string.h> | int strncmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings.| -| \#include <string.h> | char \*strrchr(const char \*s, int c); | Searches for the last occurrence of a character in a string.| +| \#include <string.h> | char \*strrchr(const char \*s, int c); | Searches for a character in a string.| | \#include <string.h> | char \*strstr(const char \*haystack, const char \*needle); | Searches for the specified substring in a string.| | \#include <stdlib.h> | long int strtol(const char \*nptr, char \*\*endptr, int base); | Converts the string pointed to by **nptr** into a **long int** value according to the given **base**.| -| \#include <stdlib.h> | unsigned long int strtoul(const char \*nptr, char\*\*endptr, int base); | Converts the string pointed to by **nptr** into an unsigned long integer.| -| \#include <stdlib.h> | unsigned long long int strtoull(const char \*nptr,char \*\*endptr, int base); | Converts the string pointed to by **nptr** into an unsigned long long integer.| +| \#include <stdlib.h> | unsigned long int strtoul(const char \*nptr, char\*\*endptr, int base); | Converts a string into an unsigned long integer.| +| \#include <stdlib.h> | unsigned long long int strtoull(const char \*nptr,char \*\*endptr,int base); | Converts a string into an unsigned long long integer.| | \#include <regex.h> | int regcomp(regex_t \*preg, const char \*regex,int cflags); | Compiles a regular expression.| | \#include <regex.h> | int regexec(const regex_t \*preg, const char \*string, size_t nmatch, regmatch_t pmatch[], int eflags); | Executes the compiled regular expression.| | \#include <regex.h> | void regfree(regex_t \*preg); | Releases the regular expression.| | \#include <string.h> | char \*strerror(int errnum); | Obtains an error message string of the specified error code.| - **Table 5** APIs for math operations + **Table 15** APIs for math operations | Header File| API| Description| | -------- | -------- | -------- | @@ -322,7 +322,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <math.h> | double round(double x); | Rounds off the value from zero to the nearest integer.| | \#include <math.h> | double sqrt(double x); | Obtains the square root of **x**.| - **Table 6** APIs for I/O operations + **Table 16** APIs for I/O operations | Header File| API| Description| | -------- | -------- | -------- | @@ -335,16 +335,16 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <stdio.h> | int fileno(FILE \*stream); | Obtains the file descriptor for a stream.| | \#include <stdio.h> | FILE \*fopen(const char \*path, const char \*mode); | Opens a stream.| | \#include <stdio.h> | int fputs(const char \*s, FILE \*stream); | Writes a line to the specified stream.| -| \#include <stdio.h> | size_t fread(void \*ptr, size_t size, size_t nmemb,FILE \*stream); | Reads a stream.| +| \#include <stdio.h> | size_t fread(void \*ptr, size_t size, size_t nmemb, FILE \*stream); | Reads a stream.| | \#include <stdio.h> | int fseek(FILE \*stream, long offset, int whence); | Sets the position of the stream pointer.| | \#include <stdio.h> | long ftell(FILE \*stream); | Obtains the position of the stream pointer.| -| \#include <stdio.h> | size_t fwrite(const void \*ptr, size_t size, size_tnmemb,FILE \*stream); | Writes data to a stream.| +| \#include <stdio.h> | size_t fwrite(const void \*ptr, size_t size, size_tnmemb, FILE \*stream); | Writes data to a stream.| | \#include <stdio.h> | void perror(const char \*s); | Prints system error information.| | \#include <stdio.h> | void rewind(FILE \*stream); | Sets the position to the beginning of the file of the specified stream.| | \#include <unistd.h> | ssize_t write(int fd, const void \*buf, size_t size); | Writes data a file.| | \#include <unistd.h> | ssize_t read(int fd, void \*buf, size_t size); | Reads data from a file.| - **Table 7** APIs for network + **Table 17** APIs for network | Header File| API| Description| | -------- | -------- | -------- | @@ -363,7 +363,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <sys/socket.h> | ssize_t sendto(int sockfd, const void \*buf, size_t len, intflags,const struct sockaddr \*dest_addr, socklen_t addrlen); | Sends a message on a socket.| | \#include <sys/socket.h> | int setsockopt(int sockfd, int level, int optname,constvoid \*optval, socklen_t optlen); | Sets options associated with a socket.| - **Table 8** APIs for memory management + **Table 18** APIs for memory management | Header File| API| Description| | -------- | -------- | -------- | @@ -374,7 +374,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <stdlib.h> | void \*malloc(size_t size); | Dynamically allocates memory blocks.| | \#include <stdlib.h> | void free(void \*ptr); | Release the memory space pointed to by **ptr**.| - **Table 9** APIs for IPC + **Table 19** APIs for IPC | Header File| API| Description| | -------- | -------- | -------- | @@ -386,11 +386,11 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an | \#include <mqueue.h> | mqd_t mq_open(const char \*mqName, int openFlag, ...); | Opens an existing message queue with the specified name or creates a message queue.| | \#include <mqueue.h> | int mq_close(mqd_t personal); | Closes a message queue with the specified descriptor.| | \#include <mqueue.h> | int mq_unlink(const char \*mqName); | Deletes the message queue of the specified name.| -| \#include <mqueue.h> | int mq_send(mqd_t personal, const char \*msg,size_t msgLen, unsigned int msgPrio); | Puts a message with the specified content and length into a message queue.| -| \#include <mqueue.h> | ssize_t mq_receive(mqd_t personal, char \*msg,size_t msgLen, unsigned int \*msgPrio); | Deletes the oldest message from a message queue and puts it in the buffer pointed to by **msg_ptr**.| +| \#include <mqueue.h> | int mq_send(mqd_t personal, const char \*msg, size_t msgLen, unsigned int msgPrio); | Puts a message with the specified content and length into a message queue.| +| \#include <mqueue.h> | ssize_t mq_receive(mqd_t personal, char \*msg, size_t msgLen, unsigned int \*msgPrio); | Deletes the oldest message from a message queue and puts it in the buffer pointed to by **msg_ptr**.| | \#include <mqueue.h> | int mq_timedsend(mqd_t personal, const char\*msg, size_t msgLen, unsigned int msgPrio, const struct timespec \*absTimeout) | Puts a message with the specified content and length into a message queue at the specified time.| | \#include <mqueue.h> | ssize_t mq_timedreceive(mqd_t personal, char\*msg, size_t msgLen, unsigned int \*msgPrio, const struct timespec \*absTimeout); | Obtains a message with the specified content and length from a message queue.| -| \#include <mqueue.h> | int mq_setattr(mqd_t mqdes, const struct mq_attr \*__restrict newattr, struct mq_attr \*__restrict oldattr); | Sets the message queue attributes specified by the descriptor.| +| \#include <mqueue.h> | int mq_setattr(mqd_t mqdes, const struct mq_attr \*\_\_restrict newattr, struct mq_attr *\__restrict oldattr); | Sets the message queue attributes specified by the descriptor.| | \#include <libc.h> | const char \*libc_get_version_string(void); | Obtains the libc version string.| | \#include <libc.h> | int libc_get_version(void); | Obtains the libc version.| @@ -459,6 +459,8 @@ Example: Creates a thread, transfers the information in the parent thread to the child thread, and prints the transferred information and the thread ID in the child thread. +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **DemoForTest** function is called in **TestTaskEntry**. + ``` #include diff --git a/en/device-dev/kernel/kernel-mini-basic-ipc-event.md b/en/device-dev/kernel/kernel-mini-basic-ipc-event.md index a39a68606f1a780ea75b05fe788f4d577ac554a5..3339899d1e1b04c94513c64692c93aeb1bea8b0a 100644 --- a/en/device-dev/kernel/kernel-mini-basic-ipc-event.md +++ b/en/device-dev/kernel/kernel-mini-basic-ipc-event.md @@ -1,15 +1,15 @@ -# Events +# Event ## Basic Concepts -An event is a mechanism for communication between tasks. It can be used to synchronize tasks. The events have the following features: +An event is a communication mechanism used to synchronize tasks. Events have the following features: - Events can be synchronized in one-to-many or many-to-many mode. In one-to-many mode, a task can wait for multiple events. In many-to-many mode, multiple tasks can wait for multiple events. However, a write event wakes up only one task from the block. - Event read timeout mechanism is used. -- Events are used only for task synchronization, but not for data transmission. +- Events are used for task synchronization, but not for data transmission. APIs are provided to initialize, read/write, clear, and destroy events. @@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events. ### Event Control Block -The event control block is a struct configured in the event initialization function. It is passed in as an input parameter to identify the event for operations such as event read and write. The data structure of the event control block is as follows: +The event control block is a structure in the event initialization function. It passes in event identifies for operations such as event read and write. The data structure of the event control block is as follows: ``` @@ -31,23 +31,33 @@ typedef struct tagEvent { ### Working Principles -**Initializing an event**: An event control block is created to maintain a collection of processed events and a linked list of tasks waiting for specific events. +**Initializing an Event** -**Writing an event**: When a specified event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the task conditions. +An event control block is created to maintain a set of processed events and a linked list of tasks waiting for specific events. -**Reading an event**: If the read event already exists, it is returned synchronously. In other cases, the return time is determined based on the timeout period and event triggering status. If the wait event condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired. +**Writing an Event** -The input parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** indicates the mask of the event. **mode** indicates the handling mode, which can be any of the following: +When an event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related tasks based on the task conditions. -- **LOS_WAITMODE_AND**: Event reading is successful only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. +**Reading an Event** -- **LOS_WAITMODE_OR**: Event reading is successful when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. +If the event to read already exists, it is returned synchronously. In other cases, the event is returned based on the timeout period and event triggering conditions. If the wait condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired. + +The parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** specifies the event mask. **mode** specifies the handling mode, which can be any of the following: + +- **LOS_WAITMODE_AND**: Read the event only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. + +- **LOS_WAITMODE_OR**: Read the event only when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. - **LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared. -**Clearing events**: Clear the event set of the event control block based on the specified mask. If the mask is **0**, the event set will be cleared. If the mask is **0xffff**, no event will be cleared, and the event set remains unchanged. +**Clearing Events** + +The events in the event set of the event control block can be cleared based on the specified mask. The mask **0** means to clear the event set; the mask **0xffff** means the opposite. + +**Destroying Events** -**Destroying an event**: Destroy the specified event control block. +The event control block can be destroyed to release resources. **Figure 1** Event working mechanism for a mini system @@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition | Category| API| Description| | -------- | -------- | -------- | -| Event check| LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.
**NOTICE**

If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter.| -| Initialization| LOS_EventInit | Initializes an event control block.| -| Event read| LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).
If no event is read, **0** is returned.
If an event is successfully read, a positive value (event set) is returned.
In other cases, an error code is returned.| -| Event write| LOS_EventWrite | Writes an event to the event control block.| -| Event clearance| LOS_EventClear | Clears an event in the event control block based on the event mask.| -| Event destruction| LOS_EventDestroy | Destroys an event control block.| +| Checking an event | LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.
**NOTE**
If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter. | +| Initializing an event control block | LOS_EventInit | Initializes an event control block.| +| Reading an event | LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).
If no event is read, **0** is returned.
If an event is successfully read, a positive value (event set) is returned.
In other cases, an error code is returned.| +| Writing an event | LOS_EventWrite | Writes an event to the event control block.| +| Clearing events | LOS_EventClear | Clears events in the event control block based on the event mask. | +| Destroying events | LOS_EventDestroy | Destroys an event control block.| ## How to Develop @@ -72,11 +82,11 @@ The typical event development process is as follows: 1. Initialize an event control block. -2. Block a read event control block. +2. Block a read event. -3. Write related events. +3. Write events. -4. Wake up a blocked task, read the event, and check whether the event meets conditions. +4. Wake up the blocked task, read the event, and check whether the event meets conditions. 5. Handle the event control block. @@ -84,7 +94,7 @@ The typical event development process is as follows: > **NOTE** -> - When an event is read or written, the 25th bit of the event is reserved and cannot be set. +> - For event read and write operations, the 25th bit (`0x02U << 24`) of the event is reserved and cannot be set. > > - Repeated writes of the same event are treated as one write. @@ -111,7 +121,7 @@ In the **ExampleEvent** task, create an **EventReadTask** task with a timout per The sample code is as follows: -The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleEvent()** in **TestTaskEntry**. +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleEvent()** function is called in **TestTaskEntry**. ``` diff --git a/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md b/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md index 3f874e55624965233b940bf1a33d378120a47762..b0677e6d8074ee0d0fbed29d74074cbc582fe543 100644 --- a/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md +++ b/en/device-dev/kernel/kernel-mini-basic-ipc-queue.md @@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin ## Available APIs -| Category| Description| +| Category| API Description | | -------- | -------- | | Creating or deleting a message queue| **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.
**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.
**LOS_QueueDelete**: deletes a message queue. After a static message queue is deleted, you need to release the queue space.| | Reading or writing data (address without the content) in a queue| **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.
**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.
**LOS_QueueWriteHead**: writes the **bufferAddr** (buffer address) to the head node of the specified queue.| @@ -136,7 +136,7 @@ Create a queue and two tasks. Enable task 1 to write data to the queue, and task The sample code is as follows: -The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleQueue** in **TestTaskEntry**. +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**. ``` diff --git a/en/device-dev/kernel/kernel-mini-debug-shell.md b/en/device-dev/kernel/kernel-mini-debug-shell.md new file mode 100644 index 0000000000000000000000000000000000000000..142bf85cec273294fd71c69fc420ccdf77788406 --- /dev/null +++ b/en/device-dev/kernel/kernel-mini-debug-shell.md @@ -0,0 +1,258 @@ +# Shell + +The shell provided by the OpenHarmony kernel supports basic debugging functions and provides commands related to the system, files, and network. It also supports commands customized based on service requirements. + +The shell function is used for debugging only. Currently, it does not support the functions such as tab completion and undo with a key. + +Some commands can be used only after the corresponding options are enabled by using **make menuconfig**. + +## Common Shell Commands + +### cat + +Displays the content of a text file. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +cat [FILE] + +#### Parameters + +| Parameter| Description | Value Range | +| ---- | ---------- | -------------- | +| FILE | File path.| An existing file.| + +### cd + +Changes the current directory. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +cd [path] + +#### Parameters + +| Parameter| Description | Value Range | +| ---- | ---------- | -------------- | +| path | File path.| Path of the new directory.| + +### cp + +Copies a file. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +cp [SOURCEFILE] [DESTFILE] + +#### Parameters + +| Parameter | Description | Value Range | +| ---------- | -------------- | ----------------------------------------- | +| SOURCEFILE | Path of the file to copy. | Currently, only files are supported. Directories are not supported. The file cannot be empty.| +| DESTFILE | Path of the file created.| Directory and file names are supported. The directory must exist. | + +### date + +Queries the system date and time. + +#### Format + +date + +#### Parameters + +None. + +### free + +Displays the memory usage of the system. + +#### Format + +free [ -k | -m ] + +#### Parameters + +| Parameter| Description | Value Range| +| ---- | ----------------- | -------- | +| -k | Display the memory usage in KiB.| N/A | +| -m | Display the memory usage in MiB.| N/A | + +### help + +Displays all commands in this operating system. + +#### Format + +help + +#### Parameters + +None. + +### ifconfig + +Displays the IP address, network mask, gateway, and MAC address of a network adapter. This command can be used only after **LWIP_SHELLCMD_ENABLE** is enabled. + +#### Format + +ifconfig + +#### Parameters + +None. + +### ls + +Displays the content of a directory. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +ls [DIRECTORY] + +#### Parameters + +| Parameter | Description | Value Range | +| --------- | ---------- | ------------------------------------------------------------ | +| DIRECTORY | Path of the directory.| If **DIRECTORY** is not specified, the content of the current directory is displayed.
If **DIRECTORY** is a valid directory, the content of the specified directory is displayed.
Currently, LiteOS-M does not support the root directory /.| + +### memusage + +Displays the memory waterline. + +#### Format + +memusage [-k/-m] + +#### Parameters + +| Parameter| Description | Value Range| +| ---- | ----------------- | -------- | +| -k | Display the memory usage in KiB.| N/A | +| -m | Display the memory usage in MiB.| N/A | + +### mkdir + +Creates a directory. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +mkdir [DIRECTORY] + +#### Parameters + +| Parameter | Description | Value Range | +| --------- | ---------- | ------------------------------------- | +| DIRECTORY | Path of the directory.| The value of **DIRECTORY** can be an absolute path or a relative path.| + +### ping + +Checks whether the network is connected. This command can be used only after **LWIP_SHELLCMD_ENABLE** is enabled. + +#### Format + +ping [ip] + +#### Parameters + +| Parameter| Description | Value Range| +| ---- | ------------------------------ | -------- | +| ip | IPv4 address of the network to test.| N/A | + +### pwd + +Displays the current path. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +pwd + +### rm + +Deletes a file or folder. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +rm [FILE] or rm [-r/-R] [FILE] + +#### Parameters + +| Parameter | Description | Value Range | +| ----- | ------------------------------- | -------------------------------- | +| FILE | File or folder name.| The value of **FILE** can be an absolute path or a relative path.| +| -r/-R | If **FILE** is a folder, -r/-R needs to be set. | N/A | + +### rmdir + +Deletes a folder. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +rmdir [DIRECTORY] + +#### Parameters + +| Parameter | Description | Value Range | +| --------- | ---------- | ------------------------------------- | +| DIRECTORY | Path of the directory.| The value of **DIRECTORY** can be an absolute path or a relative path.| + +### task + +Displays the status of each task. + +#### Format + +task + +The displayed information includes the task No., priority, status, stack information, signal, event, CPU usage, and task name. + +### touch + +Creates a file. This command can be used only after **LOSCFG_FS_VFS** is enabled. + +#### Format + +touch [FILE] + +#### Parameters + +| Parameter| Description| Value Range | +| ---- | -------- | -------------------------------- | +| FILE | File name.| The value of **FILE** can be an absolute path or a relative path.| + +### stack + +Displays the stack information of a task. This command can be used only after **LOSCFG_DEBUG_TOOLS** is enabled. Enabling this function affects the performance. + +#### Format + +stack [ID] + +#### Parameters + +| Parameter| Description| Value Range | +| ---- | -------- | ------------------------ | +| ID | Task ID.| The task corresponding to the task ID must exist.| + +### hwi + +Queries the interrupt usage. This command can be used only after **LOSCFG_DEBUG_TOOLS** is enabled. Enabling this function affects the performance. + +#### Format + +hwi + +### st + +Queries scheduling information. This command can be used only afterf **LOSCFG_DEBUG_TOOLS** is enabled. Enabling this function affects the performance. + +#### Format + +st -s | st -e + +#### Parameters + +| Parameter| Description | Value Range| +| ---- | ---------------------- | -------- | +| -s | Start to record scheduling information. | N/A | +| -e | Stop recording and print scheduling information.| N/A | diff --git a/en/device-dev/kernel/kernel-mini-extend-cpup.md b/en/device-dev/kernel/kernel-mini-extend-cpup.md index a5d10352b390a3610804eaf10e70b3d021193322..f6c1e97c7bf8b46ddfcb1b318b220dcc8c5315a7 100644 --- a/en/device-dev/kernel/kernel-mini-extend-cpup.md +++ b/en/device-dev/kernel/kernel-mini-extend-cpup.md @@ -1,27 +1,41 @@ # CPUP + ## Basic Concepts -The central processing unit percent \(CPUP\) includes the system CPUP and task CPUP. +The central processing unit percent (CPUP) includes the system CPUP and task CPUP. -The system CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status \(idle or busy\) in the given period of time. The valid range of the system CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the system runs with full load. +**System CPUP** -Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The valid range of task CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the task is being executed for the given period of time. +The system CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status (idle or busy) in the given period of time. The CPUP ranges from 0 to 100, in percentage. The value **100** indicates that the system runs with full load. With the system CPUP, you can determine whether the current system load exceeds the designed specifications. +**Task CPUP** + +Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The task CPUP ranges from 0 to 100, in percentage. The value **100** indicates that the task is being executed for the given period of time. + With the CPUP of each task, you can determine whether the CPU usage of each task meets expectations of the design. +**Interrupt CPUP** + +In addition, you can enable the interrupt usage statistics function after the CPUP function is enabled. + +Interrupt CPUP indicates the CPU usage of a single interrupt out of the total interrupt duration. The interrupt CPUP ranges from 0 to 100. The value **100** indicates that only the interrupt is triggered within a period of time. + + ## Working Principles The OpenHarmony LiteOS-M CPUP records the system CPU usage on a task basis. When task switching occurs, the task start time and task switch-out or exit time are recorded. Each time when a task exits, the system accumulates the CPU time used by the task. -You can configure this function in **target\_config.h**. +You can configure this function in **target_config.h**. The OpenHarmony LiteOS-M provides the following types of CPUP information: -- System CPUP -- Task CPUP +- System CPUP +- Task CPUP + +In addition, the system provides the capability of querying the interrupt CPUP (the CPUP and timer must be enabled). The CPUP is calculated as follows: @@ -29,156 +43,148 @@ System CPUP = Total running time of all tasks except idle tasks/Total running ti Task CPUP = Total running time of the task/Total running time of the system -## Available APIs - -**Table 1** Functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Obtaining the system CPU usage

-

LOS_SysCpuUsage

-

Obtains the current system CPUP.

-

LOS_HistorySysCpuUsage

-

Obtains the historical CPUP of the system.

-

Obtaining the task CPUP

-

LOS_TaskCpuUsage

-

Obtains the CPUP of a specified task.

-

LOS_HistoryTaskCpuUsage

-

Obtains the historical CPUP of a specified task.

-

LOS_AllCpuUsage

-

Obtains the CPUP of all tasks.

-

Outputting the task CPUP

-

LOS_CpupUsageMonitor

-

Outputs the historical CPUP of a task.

-
+Interrupt CPUP = Running time of a single interrupt/Total running time of all interrupts + + +## Available APIs + + **Table 1** APIs for CPUP + +| Category| Description| +| -------- | -------- | +| Obtaining the system CPUP| **LOS_SysCpuUsage**: obtains the current system CPUP.
**LOS_HistorySysCpuUsage**: obtains the historical CPUP of the system.| +| Obtaining the task CPUP| **LOS_TaskCpuUsage**: obtains the CPUP of a task.
**LOS_HistoryTaskCpuUsage**: obtains the historical CPUP of a task.
**LOS_AllTaskCpuUsage**: obtains the CPUP of all tasks.| +| Outputting the task CPUP| **LOS_CpupUsageMonitor**: outputs the historical CPUP of a task.| +| Obtaining the interrupt CPUP| **LOS_GetAllIrqCpuUsage**: obtains the CPUP of all interrupts.| ## How to Develop +In the **kernel/liteos_m** directory, run the **make menuconfig** command and choose **Kernel > Enable Cpup** to enable CPUP. + +Choose **Enable Cpup include irq** to enable interrupt CPUP. + The typical CPUP development process is as follows: -1. Call **LOS\_SysCpuUsage** to obtain the system CPUP. -2. Call **LOS\_HistorySysCpuUsage** to obtain the historical CPUP of the system. -3. Call **LOS\_TaskCpuUsage** to obtain the CPUP of a specified task. - - If the task has been created, disable interrupt, obtain the CPUP, and then enable interrupt. - - If the task is not created, return an error code. +1. Call **LOS_SysCpuUsage** to obtain the system CPUP. + +2. Call **LOS_HistorySysCpuUsage** to obtain the historical CPUP of the system. -4. Call **LOS\_HistoryTaskCpuUsage** to obtain the historical CPUP of a specified task. - - If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. - - If the task is not created, return an error code. +3. Call **LOS_TaskCpuUsage** to obtain the CPUP of a task. + - If the task has been created, disable interrupt, obtain the CPUP, and then enable interrupt. + - If the task is not created, return an error code. -5. Call **LOS\_AllCpuUsage** to obtain the CPUP of all tasks. - - If the CPUP is initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. - - If CPUP is not initialized or has invalid input parameters, return an error code. +4. Call **LOS_HistoryTaskCpuUsage** to obtain the historical CPUP of a task. + - If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. + - If the task is not created, return an error code. + +5. Call **LOS_AllCpuUsage** to obtain the CPUP of all tasks. + - If CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. + - If CPUP is not initialized or has invalid input parameters, return an error code. ## Development Example + ### Example Description This example implements the following: -1. Create a task for the CPUP test. -2. Obtain the CPUP of the current system. -3. Obtain the historical system CPUP in different modes. -4. Obtain the CPUP of the created test task. -5. Obtain the CPUP of the created test task in different modes. +1. Create a task for the CPUP test. + +2. Obtain the CPUP of the current system. + +3. Obtain the historical system CPUP in different modes. + +4. Obtain the CPUP of the created task. + +5. Obtain the CPUP of the created task in different modes. + ### Sample Code -Prerequisites +**Prerequisites** -In **target\_config.h**, the **LOSCFG\_BASE\_CORE\_CPUP** parameter is enabled. +CPUP is enabled.
To enable CPUP, run **make menuconfig** in the **kernel/liteos_m** directory and choose **Kernel->Enable Cpup** to enable CPUP. The sample code is as follows: +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleCpup** function is called in **TestTaskEntry**. + + ``` #include "los_task.h" -#include "los_cpup.h" -#define MODE 4 -UINT32 g_cpuTestTaskID; -VOID ExampleCpup(VOID) -{ +#include "los_cpup.h" + +#define TEST_TASK_PRIO 5 +#define TASK_DELAY_TIME 100 +VOID CpupTask(VOID) +{ printf("entry cpup test example\n"); - while(1) { - usleep(100); - } + usleep(TASK_DELAY_TIME); + usleep(TASK_DELAY_TIME); + printf("exit cpup test example\n"); } -UINT32 ItCpupTest(VOID) -{ + +UINT32 ExampleCpup(VOID) +{ UINT32 ret; UINT32 cpupUse; + UINT32 taskID; TSK_INIT_PARAM_S cpupTestTask = { 0 }; - memset(&cpupTestTask, 0, sizeof(TSK_INIT_PARAM_S)); - cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleCpup; - cpupTestTask.pcName = "TestCpupTsk"; - cpupTestTask.uwStackSize = 0x800; - cpupTestTask.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_cpuTestTaskID, &cpupTestTask); + + cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)CpupTask; + cpupTestTask.pcName = "TestCpupTsk"; + cpupTestTask.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + cpupTestTask.usTaskPrio = TEST_TASK_PRIO; + ret = LOS_TaskCreate(&taskID, &cpupTestTask); if(ret != LOS_OK) { printf("cpupTestTask create failed .\n"); return LOS_NOK; } - usleep(100); + usleep(TASK_DELAY_TIME); - /* Obtain the current CPUP of the system. */ + /* Obtain the current system CPUP. */ cpupUse = LOS_SysCpuUsage(); printf("the current system cpu usage is: %u.%u\n", - cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); + cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S); - /* Obtain the CPUP of the specified task (cpupTestTask in this example).*/ - printf("the history system CPUP in all time: %u.%u\n", + /* Obtain the historical CPUP of the system. */ + cpupUse = LOS_HistorySysCpuUsage(CPUP_LESS_THAN_1S); + printf("the history system cpu usage in all time: %u.%u\n", cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - cpupUse = LOS_TaskCpuUsage(g_cpuTestTaskID); - /* Obtain the CPUP of the specified historical task (cpupTestTask in this example) since the system startup. */ + + /* Obtain the CPUP of a specified task. */ + cpupUse = LOS_TaskCpuUsage(taskID); printf("cpu usage of the cpupTestTask:\n TaskID: %d\n usage: %u.%u\n", - g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPU_LESS_THAN_1S); + taskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); + + /* Obtain the CPUP of a specified task since the system starts. */ + cpupUse = LOS_HistoryTaskCpuUsage(taskID, CPUP_LESS_THAN_1S); printf("cpu usage of the cpupTestTask in all time:\n TaskID: %d\n usage: %u.%u\n", - g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - return LOS_OK; + taskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); + + return LOS_OK; } ``` + ### Verification -The development is successful if the return result is as follows: + The development is successful if the return result is as follows: ``` -entry cpup test example -the current system cpu usage is : 1.5 - the history system cpu usage in all time: 3.0 - cpu usage of the cpupTestTask: TaskID:10 usage: 0.0 - cpu usage of the cpupTestTask in all time: TaskID:10 usage: 0.0 +entry cpup test example +the current system cpu usage is: 8.2 +the history system cpu usage in all time: 8.9 +cpu usage of the cpupTestTask: + TaskID: 5 + usage: 0.5 +cpu usage of the cpupTestTask in all time: + TaskID: 5 + usage: 0.5 + +exit cpup test example + +The preceding data may vary depending on the running environment. ``` - diff --git a/en/device-dev/kernel/kernel-mini-extend-file.md b/en/device-dev/kernel/kernel-mini-extend-file.md index 5d0656dd59a90ea3fd9b6aade4acae18a932d4b9..ff10e418ada3317e8ff5c5e4eefc6e2e892ea31f 100644 --- a/en/device-dev/kernel/kernel-mini-extend-file.md +++ b/en/device-dev/kernel/kernel-mini-extend-file.md @@ -1,27 +1,32 @@ -# File System +# File Systems -The OpenHarmony LiteOS-M kernel supports File Allocation Table file system (FATFS) and LittleFS file systems. Like the OpenHarmony LiteOS-A kernel, the OpenHarmony LiteOS-M kernel provides POSIX over the virtual file system (VFS) to ensure interface consistency. However, the VFS of the LiteOS-M kernel is light due to insufficient resources and does not provide advanced functions (such as pagecache). Therefore, the VFS of the LiteOS-M kernel implements only API standardization and adaptation. The file systems handle specific transactions. +## VFS -The following tables list the APIs supported by the file systems of the LiteOS-M kernel. +### Basic Concepts - **Table 1** File management operations +The Virtual File System (VFS) is not a real file system. It is an abstract layer on top of a heterogeneous file system and provides you with a unified Unix-like interface for file operations. Different types of file systems use different file operation interfaces. If there are multiple types of file systems in a system, different and non-standard interfaces are required for accessing these file systems. The VFS is introduced as an abstract layer to shield the differences between these heterogeneous file systems. With the VFS, you do not need to care about the underlying storage medium and file system type. -| API| Description| FATFS | LITTLEFS | +The OpenHarmony LiteOS-M kernel supports the File Allocation Table (FAT) and LittleFS file systems. It provides the Portable Operating System Interface (POSIX) over the VFS to ensure interface consistency. However, the VFS of the LiteOS-M kernel is light and does not provide advanced functions (such as pagecache) due to insufficient resources. Therefore, the VFS of the LiteOS-M kernel implements only API standardization and adaptation. The file systems handle specific transactions. The following tables describe the APIs supported by the file systems of the LiteOS-M kernel. + +### Available APIs + +**Table 1** APIs for file operations + +| API| Description| FAT | LittleFS | | -------- | -------- | -------- | -------- | | open | Opens a file.| Supported| Supported| | close | Closes a file.| Supported| Supported| -| read | Reads the file content.| Supported| Supported| -| write | Writes data to a file.| Supported| Supported| -| lseek | Sets the file offset.| Supported| Supported| +| read | Reads the file content. | Supported | Supported | +| write | Writes data to a file. | Supported | Supported | +| lseek | Sets the file offset. | Supported | Supported | +| stat | Obtains file information based on the file path name.| Supported | Supported | | unlink | Deletes a file.| Supported| Supported| | rename | Renames the file.| Supported| Supported| -| fstat | Obtains file information based on the file handle.| Supported| Supported| -| stat | Obtains file information based on the file path name.| Supported| Supported| -| fsync | Saves file updates to a storage device.| Supported| Supported| - +| fstat | Obtains file information based on the file handle. | Supported | Supported | +| fsync | Saves a file to a storage device. | Supported | Supported | - **Table 2** Directory management operations +**Table 2** APIs for directory operations | API| Description| FATFS | LITTLEFS | | -------- | -------- | -------- | -------- | @@ -31,8 +36,7 @@ The following tables list the APIs supported by the file systems of the LiteOS-M | closedir | Closes a directory.| Supported| Supported| | rmdir | Deletes a directory.| Supported| Supported| - - **Table 3** Partition operations +**Table 3** APIs for partition operations | API| Description| FATFS | LITTLEFS | | -------- | -------- | -------- | -------- | @@ -41,14 +45,18 @@ The following tables list the APIs supported by the file systems of the LiteOS-M | umount2 | Forcibly unmounts a partition using the **MNT_FORCE** parameter.| Supported| Not supported| | statfs | Obtains partition information.| Supported| Not supported| +Interfaces, such as **ioctl** and **fcntl**, are supported by different libraries and are irrelevant to the underlying file system. + ## FAT ### Basic Concepts -File Allocation Table (FAT) is a file system developed for personal computers. It consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system supports multiple media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). The FAT file system ensures good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management. +As a file system designed for personal computers, the FAT file system consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. + +The FAT file system supports a variety of formats, including FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system also supports diversified storage media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). It features good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management. -The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary partition and logical partition. +The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary and logical partitions. ### Development Guidelines @@ -56,11 +64,13 @@ The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file #### Driver Adaptation -The use of the FAT file system requires support from the underlying MultiMediaCard (MMC) drivers. To run FatFS on a board with an MMC storage device, you must: +The use of a FAT file system requires support from the underlying MultiMediaCard (MMC) driver. Before using a FAT file system on a board with an MMC, you must perform the following operations: + +1. Implement the **disk_status**, **disk_initialize**, **disk_read**, **disk_write**, and **disk_ioctl** APIs to adapt to the embedded MMC (eMMC) driver on the board. -1. Implement the **disk_status**, **disk_initialize**, **disk_read**, **disk_write**, and **disk_ioctl** APIs to adapt to the embedded MMC (eMMC) drivers on the board. +2. Add the **fs_config.h** file with information such as **FS_MAX_SS** (maximum sector size of the storage device) and **FF_VOLUME_STRS** (partition names) configured. -2. Add the **fs_config.h** file with information such as **FS_MAX_SS** (maximum sector size of the storage device) and **FF_VOLUME_STRS** (partition names) configured. The following is an example: + The following is an example: ``` @@ -69,29 +79,115 @@ The use of the FAT file system requires support from the underlying MultiMediaCa #define FAT_MAX_OPEN_FILES 50 ``` - +#### Mounting Partitions + +Before using a FAT file system on a device, you need to initialize the flash drive and partition the device storage. + +API for partitioning the storage: + +**int LOS_DiskPartition(const char \*dev, const char \*fsType, int \*lengthArray, int \*addrArray, int partNum);** + +- **dev**: pointer to the device name, for example, **spinorblk0**. +- **fsType**: pointer to the file system type, which is **vfat** for the FAT file system. +- **lengthArray**: pointer to a list of partition lengths (in percentage for a FAT file system) of the device. +- **addrArray**: pointer to a list of partition start addresses of the device. +- **partNum**: number of partitions. + +API for formatting a partition: + +**int LOS_PartitionFormat(const char \*partName, char \*fsType, void \*data);** + +- **partName**: pointer to the partition name, in the *Device_name*+**p**+*Partition_ number* format. For example, **spinorblk0p0**. +- **fsType**: pointer to the file system type, which is **vfat** for the FAT file system. +- **data**: pointer to the private data that passes in **(VOID \*) formatType**, for example, **FMT_FAT** or **FMT_FAT32**. + +API for mounting a partition: + +**int mount(const char \*source, const char \*target, const char \*filesystemtype, unsigned long mountflags, const void \*data);** + +- **source**: pointer to the partition name, in the *Device_name*+**p**+*Partition_ number* format. For example, **spinorblk0p0**. +- **target**: pointer to the target path to mount. +- **filesystemtype**: pointer to the file system type, which is **vfat** for the FAT file system. +- **mountflags**: parameters used for the mount operation. +- **data**: pointer to the private data that passes in **(VOID \*) formatType**, for example, **FMT_FAT** or **FMT_FAT32**. + +The sample code is implemented in **./device/qemu/arm_mps2_an386/liteos_m/board/fs/fs_init.c** and can be directly used on the Quick EMUlator (QEMU) that uses the LiteOS-M kernel. You can modify the code based on the hardware you use. + + #include "fatfs_conf.h" + #include "fs_config.h" + #include "los_config.h" + #include "ram_virt_flash.h" + #include "los_fs.h" + + struct fs_cfg { + CHAR *mount_point; + struct PartitionCfg partCfg; + }; + + INT32 FatfsLowLevelInit() + { + INT32 ret; + INT32 i; + UINT32 addr; + int data = FMT_FAT32; + + const char * const pathName[FF_VOLUMES] = {FF_VOLUME_STRS}; + HalLogicPartition *halPartitionsInfo = getPartitionInfo(); /* Function for obtaining the partition lengths and start addresses. Modify it as required. */ + INT32 lengthArray[FF_VOLUMES] = {25, 25, 25, 25}; + INT32 addrArray[FF_VOLUMES]; + + /* Set the address and length for each partition. */ + for (i = 0; i < FF_VOLUMES; i++) { + addr = halPartitionsInfo[FLASH_PARTITION_DATA1].partitionStartAddr + i * 0x10000; + addrArray[i] = addr; + FlashInfoInit(i, addr); + } + + /* Set partition information. */ + SetupDefaultVolToPartTable(); + + ret = LOS_DiskPartition("spinorblk0", "vfat", lengthArray, addrArray, FF_VOLUMES); + printf("%s: DiskPartition %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + + ret = LOS_PartitionFormat("spinorblk0p0", "vfat", &data); + printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + + ret = mount("spinorblk0p0", "/system", "vfat", 0, &data); + printf("%s: mount fs on '%s' %s\n", __func__, pathName[0], (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + return 0; + } #### How to Develop -Note the following when managing FatFS files and directories: +Observe the following when managing files and directories in a FAT file system: - A file cannot exceed 4 GB. - - **FAT_MAX_OPEN_FILES** specifies the maximum number files you can open at a time, and **FAT_MAX_OPEN_DIRS** specifies the maximum number of folders you can open at a time. -- Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the file or directory **testfile** in the **user** partition. -- To open a file multiple times, use **O_RDONLY** (read-only mode). **O_RDWR** or **O_WRONLY** (writable mode) can open a file only once. +- Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the **testfile** file or directory in the **user** partition. +- To open a file multiple times at the same time, use **O_RDONLY** (read-only mode). **O_RDWR** or **O_WRONLY** (writable mode) can open a file only once at a time. - The read and write pointers are not separated. If a file is open in **O_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer. - File and directory permission management is not supported. - The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980. -Note the following when mounting and unmounting FatFS partitions: -- Partitions can be mounted with the read-only attribute. When the input parameter of the **mount** function is **MS_RDONLY**, all APIs with the write attribute, such as **write**, **mkdir**, **unlink**, and **open** with **non-O_RDONLY** attributes, will be rejected. -- You can use the **MS_REMOUNT** flag with **mount** to modify the permission for a mounted partition. +Observe the following when managing files and directories in a FAT file system: + +- Partitions can be mounted with the read-only attribute. If the input parameter of **mount()** is **MS_RDONLY**, all APIs with the write attribute, such as **write()**, **mkdir()**, **unlink()**, and **open()** with **non-O_RDONLY** attributes, will be rejected. +- You can use the **MS_REMOUNT** flag in **mount()** to modify the permissions for a mounted partition. - Before unmounting a partition, ensure that all directories and files in the partition are closed. -- You can use **umount2** with the **MNT_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when running **umount2**. +- You can use **umount2** with the **MNT_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when using **umount2**. + +You can use **fatfs_fdisk()** and **fatfs_format()** to re-partition the device storage and format the partitions. Observe the following: -The FAT file system supports re-partitioning and formatting of storage devices using **fatfs_fdisk** and **fatfs_format**. -- If a partition is mounted before being formatted using **fatfs_format**, you must close all directories and files in the partition and unmount the partition first. -- Before calling **fatfs_fdisk**, ensure that all partitions in the device are unmounted. +- Before using **fatfs_format()**, ensure that the target partition is unmounted and all directories and files in the partition are closed. +- Before using **fatfs_fdisk**, ensure that all partitions in the device are unmounted. - Using **fatfs_fdisk** and **fatfs_format** may cause data loss. Exercise caution when using them. @@ -102,9 +198,9 @@ The FAT file system supports re-partitioning and formatting of storage devices u This example implements the following: -1. Create the **user/test** directory. +1. Create a **system/test** directory. -2. Create the **file.txt** file in the **user/test** directory. +2. Create a **file.txt** file in the **system/test** directory. 3. Write **Hello OpenHarmony!** at the beginning of the file. @@ -123,99 +219,103 @@ This example implements the following: #### Sample Code - **Prerequisites** +**Prerequisites** - The MMC device partition is mounted to the **user** directory. +- The **system** partition is mounted to the QEMU. +- FAT is enabled. + 1. In the **kernel/liteos_m** directory, run the **make menuconfig** command and choose **FileSystem->Enable FS VFS** to enable VFS. + 2. Select **Enable FAT** to enable the FAT file system. - The sample code is as follows: - - ``` - #include - #include - #include "sys/stat.h" - #include "fcntl.h" - #include "unistd.h" +**Implementation** - #define LOS_OK 0 - #define LOS_NOK -1 +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleFatfs** function is called in **TestTaskEntry**. - int FatfsTest(void) - { + ``` +#include +#include +#include "sys/stat.h" +#include "fcntl.h" +#include "unistd.h" + +#define BUF_SIZE 20 +#define TEST_ROOT "system" /* Set the test root directory. */ +VOID ExampleFatfs(VOID) +{ int ret; - int fd = -1; + int fd; ssize_t len; off_t off; - char dirName[20] = "user/test"; - char fileName[20] = "user/test/file.txt"; - char writeBuf[20] = "Hello OpenHarmony!"; - char readBuf[20] = {0}; + char dirName[BUF_SIZE] = TEST_ROOT"/test"; + char fileName[BUF_SIZE] = TEST_ROOT"/test/file.txt"; + char writeBuf[BUF_SIZE] = "Hello OpenHarmony!"; + char readBuf[BUF_SIZE] = {0}; - /* Create the user/test directory. */ + /* Create a test directory. */ ret = mkdir(dirName, 0777); if (ret != LOS_OK) { printf("mkdir failed.\n"); - return LOS_NOK; + return; } - /* Create a readable and writable file named file.txt in the user/test/ directory. */ + /* Create a file that is readable and writable. */ fd = open(fileName, O_RDWR | O_CREAT, 0777); if (fd < 0) { printf("open file failed.\n"); - return LOS_NOK; + return; } /* Write the content from writeBuf to the file. */ len = write(fd, writeBuf, strlen(writeBuf)); if (len != strlen(writeBuf)) { printf("write file failed.\n"); - return LOS_NOK; + return; } /* Save the file to a storage device. */ ret = fsync(fd); if (ret != LOS_OK) { printf("fsync failed.\n"); - return LOS_NOK; + return; } /* Move the read/write pointer to the beginning of the file. */ off = lseek(fd, 0, SEEK_SET); if (off != 0) { printf("lseek failed.\n"); - return LOS_NOK; + return; } /* Read the file content with the length of readBuf to readBuf. */ len = read(fd, readBuf, sizeof(readBuf)); if (len != strlen(writeBuf)) { printf("read file failed.\n"); - return LOS_NOK; + return; } printf("%s\n", readBuf); - /* Close the file. */ + /* Close the test file. */ ret = close(fd); if (ret != LOS_OK) { printf("close failed.\n"); - return LOS_NOK; + return; } - /* Delete file.txt from the user/test directory. */ + /* Delete the test file. */ ret = unlink(fileName); if (ret != LOS_OK) { printf("unlink failed.\n"); - return LOS_NOK; + return; } - /* Delete the user/test directory. */ + /* Delete the test directory. */ ret = rmdir(dirName); if (ret != LOS_OK) { printf("rmdir failed.\n"); - return LOS_NOK; + return; } - return LOS_OK; - } + return; +} ``` @@ -232,102 +332,219 @@ Hello OpenHarmony! ### Basic Concepts -LittleFS is a small file system designed for flash. By combining the log-structured file system and the copy-on-write (COW) file system, LittleFS stores metadata in log structure and data in the COW structure. This special storage empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size (configurable). That is, the RAM usage does not grow with the file system. +LittleFS is a small file system designed for the flash drive. It stores metadata in log structure and data in the copy-on-write (COW) structure. This feature empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size (configurable). That is, the RAM usage does not grow with the file system. LittleFS is a good choice when you look for a flash file system that is power-cut resilient and has wear leveling support on a small device with limited resources. ### Development Guidelines -Before porting LittleFS to a new hardware device, you need to declare **lfs_config**: +Before using a LittleFS to a device, you need to initialize the flash drive and partition the device storage + +API for partitioning the storage: + +**int LOS_DiskPartition(const char \*dev, const char \*fsType, int \*lengthArray, int \*addrArray, int partNum);** + +- **dev**: pointer to the device name. +- **fsType**: pointer to the file system type, which is **littlefs** for LittleFS. +- **lengthArray**: pointer to a list of partition lengths of the device. +- **addrArray**: pointer to a list of partition start addresses of the device. +- **partNum**: number of partitions. + +API for formatting a partition: + +**int LOS_PartitionFormat(const char \*partName, char \*fsType, void \*data);** + +- **partName**: pointer to the partition name. +- **fsType**: pointer to the file system type, which is **littlefs** for LittleFS. +- **data**: pointer to the private data that passes in **void pass (VOID \*) struct fs_cfg**. + +API for mounting a partition: + +**int mount(const char \*source, const char \*target, const char \*filesystemtype, unsigned long mountflags, const void \*data);** + +- **source**: pointer to the partition name. +- **target**: pointer to the target path to mount. +- **filesystemtype**: pointer to the file system type, which is **littlefs** for LittleFS. +- **mountflags**: parameters used for the mount operation. +- **data**: pointer to the private data that passes in **void pass (VOID \*) struct fs_cfg**. + +The sample code is implemented in **./device/qemu/arm_mps2_an386/liteos_m/board/fs/fs_init.c** and can be directly used on the QEMU that uses the LiteOS-M kernel. You can modify the code based on the hardware you use. ``` -const struct lfs_config cfg = { - // block device operations - .read = user_provided_block_device_read, - .prog = user_provided_block_device_prog, - .erase = user_provided_block_device_erase, - .sync = user_provided_block_device_sync, - - // block device configuration - .read_size = 16, - .prog_size = 16, - .block_size = 4096, - .block_count = 128, - .cache_size = 16, - .lookahead_size = 16, - .block_cycles = 500, +#include "los_config.h" +#include "ram_virt_flash.h" +#include "los_fs.h" + +struct fs_cfg { + CHAR *mount_point; + struct PartitionCfg partCfg; }; + +INT32 LfsLowLevelInit() +{ + INT32 ret; + struct fs_cfg fs[LOSCFG_LFS_MAX_MOUNT_SIZE] = {0}; + HalLogicPartition *halPartitionsInfo = getPartitionInfo(); /* Function for obtaining the partition lengths and start addresses. You can modify the function to match your development. */ + + INT32 lengthArray[2]; + lengthArray[0]= halPartitionsInfo[FLASH_PARTITION_DATA0].partitionLength; + + INT32 addrArray[2]; + addrArray[0] = halPartitionsInfo[FLASH_PARTITION_DATA0].partitionStartAddr; + + ret = LOS_DiskPartition("flash0", "littlefs", lengthArray, addrArray, 2); + printf("%s: DiskPartition %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + fs[0].mount_point = "/littlefs"; + fs[0].partCfg.partNo = 0; + fs[0].partCfg.blockSize = 4096; /* 4096, lfs block size */ + fs[0].partCfg.blockCount = 1024; /* 2048, lfs block count */ + fs[0].partCfg.readFunc = virt_flash_read; /* Function for reading data from the flash drive. You can modify it to match your development. */ + fs[0].partCfg.writeFunc = virt_flash_write; /* Function for writing data to the flash drive. You can modify it to match your development. */ + fs[0].partCfg.eraseFunc = virt_flash_erase; /* Function for erasing the flash driver. You can modify it to match your development. */ + + fs[0].partCfg.readSize = 256; /* 256, lfs read size */ + fs[0].partCfg.writeSize = 256; /* 256, lfs prog size */ + fs[0].partCfg.cacheSize = 256; /* 256, lfs cache size */ + fs[0].partCfg.lookaheadSize = 16; /* 16, lfs lookahead size */ + fs[0].partCfg.blockCycles = 1000; /* 1000, lfs block cycles */ + + ret = LOS_PartitionFormat("flash0", "littlefs", &fs[0].partCfg); + printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + ret = mount(NULL, fs[0].mount_point, "littlefs", 0, &fs[0].partCfg); + printf("%s: mount fs on '%s' %s\n", __func__, fs[0].mount_point, (ret == 0) ? "succeed" : "failed"); + if (ret != 0) { + return -1; + } + return 0; +} ``` -**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively. +The **.readFunc**, **.writeFunc**, and **.eraseFunc** functions correspond to **read()**, **write()**, and **erase()** of the underlying hardware platform. -**read_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed. +**readSize** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed. -**prog_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read_size**. However, if the value is too large, more memory is consumed. +**writeSize** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **readSize**. However, if the value is too large, more memory is consumed. -**block_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog_size**. +**blockSize** indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **writeSize**. -**block_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased (**block_size**). +**blockCount** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased (**blockSize**). ### Sample Code - The sample code is as follows: +**Prerequisites** + +- **/littlefs** is mounted to the QEMU. +- LittleFS is enabled. + 1. In the **kernel/liteos_m** directory, run the **make menuconfig** command and choose **FileSystem->Enable FS VFS** to enable VFS. + 2. Select **Enable Little FS** to enable the LittleFS. + +The sample code is as follows: + +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleLittlefs** function is called in **TestTaskEntry**. ``` -#include "lfs.h" -#include "stdio.h" -lfs_t lfs; -lfs_file_t file; -const struct lfs_config cfg = { - // block device operations - .read = user_provided_block_device_read, - .prog = user_provided_block_device_prog, - .erase = user_provided_block_device_erase, - .sync = user_provided_block_device_sync, - // block device configuration - .read_size = 16, - .prog_size = 16, - .block_size = 4096, - .block_count = 128, - .cache_size = 16, - .lookahead_size = 16, - .block_cycles = 500, -}; -int main(void) { - // mount the filesystem - int err = lfs_mount(&lfs, &cfg); - // reformat if we can't mount the filesystem - // this should only happen on the first boot - if (err) { - lfs_format(&lfs, &cfg); - lfs_mount(&lfs, &cfg); +#include +#include +#include "sys/stat.h" +#include "fcntl.h" +#include "unistd.h" + +#define BUF_SIZE 20 +#define TEST_ROOT "/littlefs" /* Set the test root directory. */ +VOID ExampleLittlefs(VOID) +{ + int ret; + int fd; + ssize_t len; + off_t off; + char dirName[BUF_SIZE] = TEST_ROOT"/test"; + char fileName[BUF_SIZE] = TEST_ROOT"/test/file.txt"; + char writeBuf[BUF_SIZE] = "Hello OpenHarmony!"; + char readBuf[BUF_SIZE] = {0}; + + /* Create a test directory. */ + ret = mkdir(dirName, 0777); + if (ret != LOS_OK) { + printf("mkdir failed.\n"); + return; } - // read current count - uint32_t boot_count = 0; - lfs_file_open(&lfs, &file, "boot_count", LFS_O_RDWR | LFS_O_CREAT); - lfs_file_read(&lfs, &file, &boot_count, sizeof(boot_count)); - // update boot count - boot_count += 1; - lfs_file_rewind(&lfs, &file); - lfs_file_write(&lfs, &file, &boot_count, sizeof(boot_count)); - // remember the storage is not updated until the file is closed successfully - lfs_file_close(&lfs, &file); - // release any resources we were using - lfs_unmount(&lfs); - // print the boot count - printf("boot_count: %d\n", boot_count); + + /* Create a file that is readable and writable. */ + fd = open(fileName, O_RDWR | O_CREAT, 0777); + if (fd < 0) { + printf("open file failed.\n"); + return; + } + + /* Write the content from writeBuf to the file. */ + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return; + } + + /* Save the file to a storage device. */ + ret = fsync(fd); + if (ret != LOS_OK) { + printf("fsync failed.\n"); + return; + } + + /* Move the read/write pointer to the beginning of the file. */ + off = lseek(fd, 0, SEEK_SET); + if (off != 0) { + printf("lseek failed.\n"); + return; + } + + /* Read the file content with the length of readBuf to readBuf. */ + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(writeBuf)) { + printf("read file failed.\n"); + return; + } + printf("%s\n", readBuf); + + /* Close the test file. */ + ret = close(fd); + if (ret != LOS_OK) { + printf("close failed.\n"); + return; + } + + /* Delete the test file. */ + ret = unlink(fileName); + if (ret != LOS_OK) { + printf("unlink failed.\n"); + return; + } + + /* Delete the directory. */ + ret = rmdir(dirName); + if (ret != LOS_OK) { + printf("rmdir failed.\n"); + return; + } + + return LOS_OK; } ``` - - **Verification** +**Verification** The development is successful if the return result is as follows: ``` -Say hello 1 times. +Hello OpenHarmony! ``` + diff --git a/en/device-dev/kernel/kernel-mini-memory-debug.md b/en/device-dev/kernel/kernel-mini-memory-debug.md index 4cb0f39bba4e3a86a09238de86431d4541f8d051..c23372f9f0ffdd1b55e3eb818cb0f5acb78c942f 100644 --- a/en/device-dev/kernel/kernel-mini-memory-debug.md +++ b/en/device-dev/kernel/kernel-mini-memory-debug.md @@ -11,16 +11,16 @@ The purpose of memory debugging is to locate problems related to dynamic memory. Memory information includes the memory pool size, memory usage, remaining memory size, maximum free memory, memory waterline, number of memory nodes, and fragmentation rate. -- Memory waterline: indicates the maximum memory used in a memory pool. The waterline value is updated upon each memory allocation and release. The memory pool size can be optimized based on this value. +- Memory waterline indicates the maximum memory used in a memory pool. The waterline value is updated upon each memory allocation and release. The memory pool size can be optimized based on this value. -- Fragmentation rate: indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size +- Fragmentation rate indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size -- Other parameters: You can call APIs described in [Memory Management](../kernel/kernel-mini-basic-memory.md) to scan node information in the memory pool and collect statistics. +- You can use [APIs for memory management](kernel-mini-basic-memory.md) to scan node information in the memory pool and collect statistics. ### Function Configuration -**LOSCFG_MEM_WATERLINE**: specifies the setting of the memory information statistics function. This function is enabled by default. To disable the function, set this macro to **0** in **target_config.h**. If you want to obtain the memory waterline, you must enable this macro. +**LOSCFG_MEM_WATERLINE** specifies the setting of the memory information statistics function. This function is enabled by default. To disable the function, set this macro to **0** in **target_config.h**. If you want to obtain the memory waterline, you must enable this macro. ### Development Guidelines @@ -33,20 +33,20 @@ Key structure: ``` typedef struct { - UINT32 totalUsedSize; // Memory usage of the memory pool. - UINT32 totalFreeSize; // Remaining size of the memory pool. - UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool. - UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool. - UINT32 freeNodeNum; // Number of free memory blocks in the memory pool. -#if (LOSCFG_MEM_WATERLINE == 1) //The function is enabled by default. To disable it, set this macro to 0 in target_config.h. - UINT32 usageWaterLine; // Waterline of the memory pool. + UINT32 totalUsedSize; // Memory usage of the memory pool. + UINT32 totalFreeSize; // Remaining size of the memory pool. + UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool. + UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool. + UINT32 freeNodeNum; // Number of free memory blocks in the memory pool. +#if (LOSCFG_MEM_WATERLINE == 1) // The function is enabled by default. To disable it, set this macro to 0 in target_config.h. + UINT32 usageWaterLine; // Waterline of the memory pool. #endif } LOS_MEM_POOL_STATUS; ``` -- To obtain the memory waterline, call **LOS_MemInfoGet**. The first parameter in the API is the start address of the memory pool, and the second parameter is the handle of the **LOS_MEM_POOL_STATUS** type. The **usageWaterLine** field indicates the waterline. +To obtain the memory waterline, call **LOS_MemInfoGet**. The first parameter in the API is the start address of the memory pool, and the second parameter is the handle of the **LOS_MEM_POOL_STATUS** type. The **usageWaterLine** field indicates the waterline. -- To calculate the memory fragmentation rate, call **LOS_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows:
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size +To calculate the memory fragmentation rate, call **LOS_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows:
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size #### Development Example @@ -62,7 +62,9 @@ This example implements the following: #### Sample Code - The sample code is as follows: +The sample code is as follows: + +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **MemTest** function is called in **TestTaskEntry**. ``` #include @@ -71,20 +73,20 @@ This example implements the following: #include "los_memory.h" #include "los_config.h" - +#define TEST_TASK_PRIO 5 void MemInfoTaskFunc(void) { LOS_MEM_POOL_STATUS poolStatus = {0}; - /* pool is the memory address of the information to be collected. OS_SYS_MEM_ADDR is used as an example. */ + /* pool is the memory address of the information to be collected. OS_SYS_MEM_ADDR is used as an example. */ void *pool = OS_SYS_MEM_ADDR; LOS_MemInfoGet(pool, &poolStatus); /* Calculate the fragmentation rate of the memory pool. */ - unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize; + float fragment = 100 - poolStatus.maxFreeNodeSize * 100.0 / poolStatus.totalFreeSize; /* Calculate the memory usage of the memory pool. */ - unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool); - printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, - poolStatus.totalFreeSize, poolStatus.usageWaterLine); + float usage = LOS_MemTotalUsedGet(pool) * 100.0 / LOS_MemPoolSizeGet(pool); + printf("usage = %f, fragment = %f, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, + poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine); } int MemTest(void) @@ -93,9 +95,9 @@ int MemTest(void) unsigned int taskID; TSK_INIT_PARAM_S taskStatus = {0}; taskStatus.pfnTaskEntry = (TSK_ENTRY_FUNC)MemInfoTaskFunc; - taskStatus.uwStackSize = 0x1000; + taskStatus.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; taskStatus.pcName = "memInfo"; - taskStatus.usTaskPrio = 10; + taskStatus.usTaskPrio = TEST_TASK_PRIO; ret = LOS_TaskCreate(&taskID, &taskStatus); if (ret != LOS_OK) { printf("task create failed\n"); @@ -112,7 +114,9 @@ The result is as follows: ``` -usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414 +usage = 0.458344, fragment = 0.000000, maxFreeSize = 16474928, totalFreeSize = 16474928, waterLine = 76816 + +The preceding data may vary depending on the running environment. ``` ## Memory Leak Check @@ -124,14 +128,15 @@ As an optional function of the kernel, memory leak check is used to locate dynam ### Function Configuration -1. **LOSCFG_MEM_LEAKCHECK**: specifies the setting of the memory leak check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**. +**LOSCFG_MEM_LEAKCHECK** specifies the setting of the memory leak check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**. -2. **LOSCFG_MEM_RECORD_LR_CNT**: specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void\*)** bytes. +**LOSCFG_MEM_RECORD_LR_CNT** specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void \*)** bytes. -3. **LOSCFG_MEM_OMIT_LR_CNT**: specifies the number of ignored LRs. The default value is **4**, which indicates that LRs are recorded from the time when **LOS_MemAlloc** is called. You can change the value based on actual requirements. This macro is configured because: - - **LOS_MemAlloc** is also called internally. - - **LOS_MemAlloc** may be encapsulated externally. - - The number of LRs configured by **LOSCFG_MEM_RECORD_LR_CNT** is limited. +**LOSCFG_MEM_OMIT_LR_CNT** specifies the number of ignored LRs. The default value is **4**, which indicates that LRs are recorded from the time when **LOS_MemAlloc** is called. You can change the value based on actual requirements. This macro is configured because: + +- **LOS_MemAlloc** is also called internally. +- **LOS_MemAlloc** may be encapsulated externally. +- The number of LRs configured by **LOSCFG_MEM_RECORD_LR_CNT** is limited. Correctly setting this macro can ignore invalid LRs and reduce memory consumption. @@ -156,7 +161,8 @@ node size LR[0] LR[1] LR[2] 0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0 ``` -> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**
+> **CAUTION** +> > Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead. @@ -179,6 +185,12 @@ This example implements the following: The sample code is as follows: +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **MemLeakTest** function is called in **TestTaskEntry**. + +When QEMU is running, ensure that the value of **LOSCFG_MEM_FREE_BY_TASKID** in **target_config.h** is **0**. + +After the memory check function is enabled, other tasks running on certain platforms may frequently print memory-related information such as "psp, start = xxxxx, end = xxxxxxx". Ignore the information or delete the print information called by **OsStackAddrGet**. + ``` #include @@ -216,7 +228,9 @@ node size LR[0] LR[1] LR[2] 0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a 0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 + +The preceding data may vary depending on the running environment. ``` The difference between the two logs is as follows. The following memory nodes are suspected to have blocks with a memory leak. @@ -224,7 +238,9 @@ The difference between the two logs is as follows. The following memory nodes ar ``` 0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 + +The preceding data may vary depending on the running environment. ``` The following is part of the assembly file: @@ -246,6 +262,8 @@ The following is part of the assembly file: 0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a 0x80041f4: 0xbd10 POP {R4, PC} 0x80041f6: 0x0000 MOVS R0, R0 + + The preceding data may vary depending on the running environment. ``` The memory node addressed by **0x080041ee** is not released after being requested in **MemLeakTest**. @@ -260,15 +278,16 @@ As an optional function of the kernel, memory corruption check is used to check ### Function Configuration -**LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK**: specifies the setting of the memory corruption check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**. +**LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** specifies the setting of the memory corruption check. This function is disabled by default. To enable the function, set this macro to **1** in **target_config.h**. 1. If this macro is enabled, the memory pool integrity will be checked in real time upon each memory allocation. -2. If this macro is not enabled, you can call **LOS_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS_MemIntegrityCheck** does not affect the system performance. In addition, the check accuracy decreases because the node header does not contain the magic number (which is available only when **LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** is enabled). +2. If this macro is not enabled, you can call **LOS_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS_MemIntegrityCheck** does not affect the system performance. However, the check accuracy decreases because the node header does not contain the magic number (which is available only when **LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** is enabled). This check only detects the corrupted memory node and provides information about the previous node (because memory is contiguous, a node is most likely corrupted by the previous node). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault. -> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**
+> **CAUTION** +> > If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS_MemIntegrityCheck** to check the memory pool integrity. @@ -295,6 +314,12 @@ This example implements the following: The sample code is as follows: +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **MemIntegrityTest** function is called in **TestTaskEntry**. + +When QEMU is running, ensure that the value of **LOSCFG_MEM_FREE_BY_TASKID** in **target_config.h** is **0**. + +Because the exception is triggered intentionally, you need to restart QEMU when the execution is complete. For example, open a new terminal and run **killall qemu-system-arm**. + ``` #include @@ -320,20 +345,28 @@ The log is as follows: ``` -[ERR][OsMemMagicCheckPrint], 2028, memory check error! -memory used but magic num wrong, magic num = 0x00000000 /* Error information, indicating that the first four bytes, that is, the magic number, of the next node are corrupted. */ - - broken node head: 0x20003af0 0x00000000 0x80000020, prev node head: 0x20002ad4 0xabcddcba 0x80000020 -/* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */ - - broken node head LR info: /* The node LR information can be output only after the memory leak check is enabled. */ - LR[0]:0x0800414e - LR[1]:0x08000cc2 - LR[2]:0x00000000 - - pre node head LR info: /* Based on the LR information, you can find where the previous node is requested in the assembly file and then perform further analysis. */ - LR[0]:0x08004144 - LR[1]:0x08000cc2 - LR[2]:0x00000000 -[ERR]Memory integrity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node */ + +/* Error information indicating the field corrupted. In this example, the first four bytes of the next node are cleared, that is, the magic number field is corrupted. */ +[ERR][IT_TST_INI][OsMemMagicCheckPrint], 1664, memory check error! +memory used but magic num wrong, magic num = 0x0 + + /* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */ + broken node head: 0x2103d7e8 0x0 0x80000020, prev node head: 0x2103c7cc 0xabcddcba 0x80000020 + + /*The node LR information can be output only after the memory leak check is enabled. */ + broken node head LR info: + LR[0]:0x2101906c + LR[1]:0x0 + LR[2]:0x0 + + /* Based on the LR information, you can determine where the previous node in requsted in the assembly file and check the use of the node. */ + pre node head LR info: + LR[0]:0x2101906c + LR[1]:0x0 + LR[2]:0x0 + + /* Addresses of the corrupted node and its previous node. */ +[ERR][IT_TST_INI]Memory integrity check error, cur node: 0x2103d784, pre node: 0x0 + + The preceding data may vary depending on the running environment. ``` diff --git a/en/device-dev/kernel/kernel-mini-memory-exception.md b/en/device-dev/kernel/kernel-mini-memory-exception.md index a5fa385993177947d5884643fd3186cb65d2bfa8..599623cbb364b7fc93cd1b6a9cd6d11cc338053d 100644 --- a/en/device-dev/kernel/kernel-mini-memory-exception.md +++ b/en/device-dev/kernel/kernel-mini-memory-exception.md @@ -1,321 +1,277 @@ # Exception Debugging + ## Basic Concepts The OpenHarmony LiteOS-M provides exception handling and debugging measures to help locate and analyze problems. Exception handling involves a series of actions taken by the OS to respond to exceptions occurred during the OS running, for example, printing the exception type, system status, call stack information of the current function, CPU information, and call stack information of tasks. + ## Working Principles -A stack frame contains information such as function parameters, variables, and return value in a function call process. When a function is called, a stack frame of the subfunction is created, and the input parameters, local variables, and registers of the function are stored into the stack. Stack frames grow towards lower addresses. The ARM32 CPU architecture is used as an example. Each stack frame stores the historical values of the program counter \(PC\), LR \(link register\), stack pointer \(SP\), and frame pointer \(FP\) registers. The LR points to the return address of a function, and the FP points to the start address of the stack frame of the function's parent function. The FP helps locate the parent function's stack frame, which further helps locate the parent function's FP. The parent function's FP helps locate the grandparent function's stack frame and FP... In this way, the call stack of the program can be traced to obtain the relationship between the functions called. +A stack frame contains information such as function parameters, variables, and return value in a function call process. When a function is called, a stack frame of the subfunction is created, and the input parameters, local variables, and registers of the function are stored into the stack. Stack frames grow towards lower addresses. The ARM32 CPU architecture is used as an example. Each stack frame stores the historical values of the program counter (PC), link register (LR), stack pointer (SP), and frame pointer (FP) registers. The LR points to the return address of a function, and the FP points to the start address of the stack frame of the function's parent function. The FP helps locate the parent function's stack frame, which further helps locate the parent function's FP. The parent function's FP helps locate the grandparent function's stack frame and FP... In this way, the call stack of the program can be traced to obtain the relationship between the functions called. When an exception occurs in the system, the system prints the register information in the stack frame of the abnormal function as well as the LRs and FPs in the stack frames of its parent function and grandfather function. The relationships between the functions help you locate the cause of the exception. The following figure illustrates the stack analysis mechanism for your reference. The actual stack information varies depending on the CPU architecture. -**Figure 1** Stack analysis mechanism +**Figure 1** Stack analysis mechanism + ![](figures/stack-analysis-mechanism.png "stack-analysis-mechanism") In the figure, the registers in different colors indicate different functions. The registers save related data when functions are called. The FP register helps track the stack to the parent function of the abnormal function and further presents the relationships between the functions called. + ## Available APIs The following table describes APIs available for the OpenHarmony LiteOS-M stack trace module. For more details about the APIs, see the API reference. -**Table 1** APIs of the stack trace module - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Stack trace

-

LOS_BackTrace

-

Prints the call stack relationship at the function calling point.

-

LOS_RecordLR

-

Obtains the call stack relationship at the function calling point when print is unavailable.

-
- -## Usage Guidelines + **Table 1** APIs of the stack trace module + +| Category| API| +| -------- | -------- | +| Stack tracing| **LOS_BackTrace**: prints the call stack relationship at the calling point.
**LOS_RecordLR**: obtains the call stack relationship at the calling point when print is unavailable.| + + +## Development Guidelines + ### How to Develop The typical process for enabling exception debugging is as follows: -1. Configure the macros related to exception handling. - - Modify the configuration in the **target\_config.h** file. - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

Value

-

LOSCFG_BACKTRACE_DEPTH

-

Depth of the function call stack. The default value is 15.

-

15

-

LOSCFG_BACKTRACE_TYPE

-

Type of the stack trace.

-

0: disabled

-

1: supports function call stack analysis of the Cortex-m series hardware.

-

2: supports function call stack analysis of the RISC-V series hardware.

-

Set this parameter to 1 or 2 based on the toolchain type.

-
- - -1. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions. - - The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows: - - ``` - #include - #include "los_config.h" - #include "los_interrupt.h" - #include "los_task.h" - - UINT32 g_taskExcId; - #define TSK_PRIOR 4 - - /* Simulate an abnormal function. */ - - UINT32 Get_Result_Exception_0(UINT16 dividend){ - UINT32 divisor = 0; - UINT32 result = dividend / divisor; - return result; - } - - UINT32 Get_Result_Exception_1(UINT16 dividend){ - return Get_Result_Exception_0(dividend); - } - - UINT32 Get_Result_Exception_2(UINT16 dividend){ - return Get_Result_Exception_1(dividend); - } - - UINT32 Example_Exc(VOID) - { - UINT32 ret; - - printf("Enter Example_Exc Handler.\r\n"); - - /* Simulate the function calling. */ - ret = Get_Result_Exception_2(TSK_PRIOR); - printf("Divided result =%u.\r\n", ret); - - printf("Exit Example_Exc Handler.\r\n"); - return ret; - } - - - /* Task entry function used to create a task with an exception. */ - UINT32 Example_Exc_Entry(VOID) - { - UINT32 ret; - TSK_INIT_PARAM_S initParam; - - /* Lock task scheduling to prevent newly created tasks from being scheduled prior to this task due to higher priority.*/ - LOS_TaskLock(); - - printf("LOS_TaskLock() Success!\r\n"); - - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Exc; - initParam.usTaskPrio = TSK_PRIOR; - initParam.pcName = "Example_Exc"; - initParam.uwStackSize = LOSCFG_SECURE_STACK_DEFAULT_SIZE; - /* Create a task with higher priority. The task will not be executed immediately after being created, because task scheduling is locked.*/ - ret = LOS_TaskCreate(&g_taskExcId, &initParam); - if (ret != LOS_OK) { - LOS_TaskUnlock(); - - printf("Example_Exc create Failed!\r\n"); - return LOS_NOK; - } - - printf("Example_Exc create Success!\r\n"); - - /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed.*/ - LOS_TaskUnlock(); - - return LOS_OK; - } - ``` - - -1. The error information displayed on the serial port terminal is as follows: - - ``` - entering kernel init... - LOS_TaskLock() Success! - Example_Exc create Success! - Entering scheduler - Enter Example_Exc Handler. - *************Exception Information************** - Type = 10 - ThrdPid = 4 - Phase = exc in task - FaultAddr = 0xabababab - Current task info: - Task name = Example_Exc - Task ID = 4 - Task SP = 0x200051ac - Task ST = 0x20004ff0 - Task SS = 0x200 - Exception reg dump: - PC = 0x80037da - LR = 0x80037fe - SP = 0x20005190 - R0 = 0x4 - R1 = 0x40 - R2 = 0x4 - R3 = 0x0 - R4 = 0x4040404 - R5 = 0x5050505 - R6 = 0x6060606 - R7 = 0x20005190 - R8 = 0x8080808 - R9 = 0x9090909 - R10 = 0x10101010 - R11 = 0x11111111 - R12 = 0x12121212 - PriMask = 0x0 - xPSR = 0x41000000 - ----- backtrace start ----- - backtrace 0 -- lr = 0x800381a - backtrace 1 -- lr = 0x8003836 - backtrace 2 -- lr = 0x8005a4e - backtrace 3 -- lr = 0x8000494 - backtrace 4 -- lr = 0x8008620 - backtrace 5 -- lr = 0x800282c - backtrace 6 -- lr = 0x80008a0 - backtrace 7 -- lr = 0x80099f8 - backtrace 8 -- lr = 0x800a01a - backtrace 9 -- lr = 0x800282c - backtrace 10 -- lr = 0x80008a0 - backtrace 11 -- lr = 0x80099f8 - backtrace 12 -- lr = 0x8009bf0 - backtrace 13 -- lr = 0x8009c52 - backtrace 14 -- lr = 0x80099aa - ----- backtrace end ----- - - TID Priority Status StackSize WaterLine StackPoint TopOfStack EventMask SemID name - --- -------- -------- --------- ---------- ---------- ---------- --------- ----- ---- - 0 0 Pend 0x2d0 0x104 0x200029bc 0x200027f0 0x0 0xffff Swt_Task - 1 31 Ready 0x500 0x44 0x20002f84 0x20002ac8 0x0 0xffff IdleCore000 - 2 6 Ready 0x1000 0x44 0x20003f94 0x20002fd8 0x0 0xffff TaskSampleEntry1 - 3 7 Ready 0x1000 0x44 0x20004f9c 0x20003fe0 0x0 0xffff TaskSampleEntry2 - 4 4 Running 0x200 0xec 0x200051ac 0x20004ff0 0x0 0xffff Example_Exc - - OS exception NVIC dump: - interrupt enable register, base address: 0xe000e100, size: 0x20 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt pending register, base address: 0xe000e200, size: 0x20 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt active register, base address: 0xe000e300, size: 0x20 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt priority register, base address: 0xe000e400, size: 0xf0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 - interrupt exception register, base address: 0xe000ed18, size: 0xc - 0x0 0x0 0xf0f00000 - interrupt shcsr register, base address: 0xe000ed24, size: 0x4 - 0x70008 - interrupt control register, base address: 0xe000ed04, size: 0x4 - 0x400f806 - - memory pools check: - system heap memcheck over, all passed! - memory pool check end! - ``` +1. Configure the macros related to exception handling + in the **target_config.h** file. + | Configuration Item| Description| Value| + | -------- | -------- | -------- | + | LOSCFG_BACKTRACE_DEPTH | Depth of the function call stack. The default value is **15**.| 15 | + | LOSCFG_BACKTRACE_TYPE | Type of the stack tracing.
**0**: The stack tracing is disabled.
**1**: supports call stack analysis of the Cortex-M series hardware.
**2**: supports call stack analysis of the RISC-V series hardware.| Set this parameter to **1** or **2** based on the toolchain type.| + +1. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions. + The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows: + + The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleExcEntry** function is called in **TestTaskEntry**. + + ``` + #include + #include "los_config.h" + #include "los_interrupt.h" + #include "los_task.h" + + UINT32 g_taskExcId; + #define TSK_PRIOR 4 + + /* Simulate an exception. */ + UINT32 GetResultException0(UINT16 dividend){ + UINT32 result = *(UINT32 *)(0xffffffff); + printf("Enter GetResultException0. %u\r\n", result); + return result; + } + + UINT32 GetResultException1(UINT16 dividend){ + printf("Enter GetResultException1.\r\n"); + return GetResultException0(dividend); + } + + UINT32 GetResultException2(UINT16 dividend){ + printf("Enter GetResultException2.\r\n"); + return GetResultException1(dividend); + } + + UINT32 ExampleExc(VOID) + { + UINT32 ret; + + printf("Enter Example_Exc Handler.\r\n"); + + /* Simulate the triggering of the exception. */ + ret = GetResultException2(TSK_PRIOR); + printf("Divided result =%u.\r\n", ret); + + printf("Exit Example_Exc Handler.\r\n"); + return ret; + } + + + /* Create a task with an exception in the task entry function. */ + UINT32 ExampleExcEntry(VOID) + { + UINT32 ret; + TSK_INIT_PARAM_S initParam = { 0 }; + + /* Lock task scheduling to prevent newly created tasks from being scheduled prior to this task due to higher priority. */ + LOS_TaskLock(); + + printf("LOS_TaskLock() Success!\r\n"); + + initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleExc; + initParam.usTaskPrio = TSK_PRIOR; + initParam.pcName = "Example_Exc"; + initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + /* Create a task with a higher priority. The task will not be executed because task scheduling is locked. */ + ret = LOS_TaskCreate(&g_taskExcId, &initParam); + if (ret != LOS_OK) { + LOS_TaskUnlock(); + + printf("Example_Exc create Failed!\r\n"); + return LOS_NOK; + } + + printf("Example_Exc create Success!\r\n"); + + /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed. */ + LOS_TaskUnlock(); + + return LOS_OK; + } + ``` + + The error information output by the serial port terminal is as follows: + + ``` + LOS_TaskLock() Success! + Example_Exc create Success! + Enter Example_Exc Handler. + Enter GetResultException2. + Enter GetResultException1. + *************Exception Information************** + Type = 4 + ThrdPid = 5 + Phase = exc in task + FaultAddr = 0xfffffffc + Current task info: + Task name = Example_Exc + Task ID = 5 + Task SP = 0x210549bc + Task ST = 0x21053a00 + Task SS = 0x1000 + Exception reg dump: + PC = 0x2101c61a + LR = 0x2101c64d + SP = 0x210549a8 + R0 = 0x4 + R1 = 0xa + R2 = 0x0 + R3 = 0xffffffff + R4 = 0x2103fb20 + R5 = 0x5050505 + R6 = 0x6060606 + R7 = 0x210549a8 + R8 = 0x8080808 + R9 = 0x9090909 + R10 = 0x10101010 + R11 = 0x11111111 + R12 = 0x0 + PriMask = 0x0 + xPSR = 0x41000000 + ----- backtrace start ----- + backtrace 0 -- lr = 0x2101c64c + backtrace 1 -- lr = 0x2101c674 + backtrace 2 -- lr = 0x2101c696 + backtrace 3 -- lr = 0x2101b1ec + ----- backtrace end ----- + + TID Priority Status StackSize WaterLine StackPoint TopOfStack EventMask SemID CPUUSE CPUUSE10s CPUUSE1s TaskEntry name + --- -------- -------- --------- --------- ---------- ---------- --------- ------ ------- --------- -------- ---------- ---- + 0 0 Pend 0x1000 0xdc 0x2104730c 0x210463e8 0 0xffff 0.0 0.0 0.0 0x2101a199 Swt_Task + 1 31 Ready 0x500 0x44 0x210478e4 0x21047428 0 0xffff 0.0 0.0 0.0 0x2101a9c9 IdleCore000 + 2 5 PendTime 0x6000 0xd4 0x2104e8f4 0x210489c8 0 0xffff 5.7 5.7 0.0 0x21016149 tcpip_thread + 3 3 Pend 0x1000 0x488 0x2104f90c 0x2104e9e8 0x1 0xffff 8.6 8.6 0.0 0x21016db5 ShellTaskEntry + 4 25 Ready 0x4000 0x460 0x21053964 0x2104f9f0 0 0xffff 9.0 8.9 0.0 0x2101c765 IT_TST_INI + 5 4 Running 0x1000 0x458 0x210549bc 0x21053a00 0 0xffff 76.5 76.6 0.0 0x2101c685 Example_Exc + + OS exception NVIC dump: + interrupt enable register, base address: 0xe000e100, size: 0x20 + 0x2001 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt pending register, base address: 0xe000e200, size: 0x20 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt active register, base address: 0xe000e300, size: 0x20 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt priority register, base address: 0xe000e400, size: 0xf0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 + interrupt exception register, base address: 0xe000ed18, size: 0xc + 0x0 0x0 0xf0f00000 + interrupt shcsr register, base address: 0xe000ed24, size: 0x4 + 0x70002 + interrupt control register, base address: 0xe000ed04, size: 0x4 + 0x1000e805 + + memory pools check: + system heap memcheck over, all passed! + memory pool check end! + + The preceding data may vary depending on the running environment. + ``` ### How to Locate Exceptions The procedure for locating the exception is as follows: -1. Open the image disassembly file \(.asm\) generated after compilation. If the file is not generated by default, use the objdump tool to generate it. Run the following command: - - ``` - arm-none-eabi-objdump -S -l XXX.elf - ``` - - -1. Search for the PC \(pointing to the instruction being executed\) in the ASM file to locate the abnormal function. - - The PC address directs to the instruction being executed when the exception occurs. In the ASM file corresponding to the currently executed binary file, search for the PC value **0x80037da** and locate the instruction being executed by the CPU. Disassemble the code as follows: - - ``` - UINT32 Get_Result_Exception_0(UINT16 dividend){ - 80037c8: b480 push {r7} - 80037ca: b085 sub sp, #20 - 80037cc: af00 add r7, sp, #0 - 80037ce: 4603 mov r3, r0 - 80037d0: 80fb strh r3, [r7, #6] - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:10 - UINT32 divisor = 0; - 80037d2: 2300 movs r3, #0 - 80037d4: 60fb str r3, [r7, #12] - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:11 - UINT32 result = dividend / divisor; - 80037d6: 88fa ldrh r2, [r7, #6] - 80037d8: 68fb ldr r3, [r7, #12] - 80037da: fbb2 f3f3 udiv r3, r2, r3 - 80037de: 60bb str r3, [r7, #8] - ``` - - -1. As indicated by the code: - 1. When the exception occurs, the CPU is executing **udiv r3, r2, r3**. The value of **r3** is **0**, which causes the divide-by-zero error. - 2. The exception occurs in the **Get\_Result\_Exception\_0** function. - -2. Locate the parent function of the abnormal function based on the LR value. - - The code disassembly of the LR value **0x80037fe** is as follows: - - ``` - 080037ec : - Get_Result_Exception_1(): - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:15 - UINT32 Get_Result_Exception_1(UINT16 dividend){ - 80037ec: b580 push {r7, lr} - 80037ee: b082 sub sp, #8 - 80037f0: af00 add r7, sp, #0 - 80037f2: 4603 mov r3, r0 - 80037f4: 80fb strh r3, [r7, #6] - kernel_liteos_m\targets\cortex-m7_nucleo_f767zi_gcc/Core/Src/exc_example.c:16 - return Get_Result_Exception_0(dividend); - 80037f6: 88fb ldrh r3, [r7, #6] - 80037f8: 4618 mov r0, r3 - 80037fa: f7ff ffe5 bl 80037c8 - 80037fe: 4603 mov r3, r0 - ``` - - -1. The previous line of LR **80037fe** is **bl 80037c8 **, which calls the abnormal function. The parent function that calls the abnormal function is **Get\_Result\_Exception\_1\(\)**. -2. Repeat [3](#li18973161743110) to analyze the LR values between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship and find the exception cause. - +1. Ensure that the compiler optimization is disabled. Otherwise, the following problems may be optimized during the compilation process. + +2. Open the image disassembly file (.asm) generated. If the file is not generated, use the objdump tool to generate it. The command is as follows: + + ``` + arm-none-eabi-objdump -S -l XXX.elf + ``` + +3. Search for the PC (pointing to the instruction being executed) in the .asm file to locate the abnormal function. + + The PC address directs to the instruction being executed when the exception occurs. In the .asm file corresponding to the currently executed binary file, search for the PC value **0x2101c61a** and locate the instruction being executed by the CPU. Disassemble the code as follows: + + ``` + 2101c60c : + 2101c60c: b580 push {r7, lr} + 2101c60e: b084 sub sp, #16 + 2101c610: af00 add r7, sp, #0 + 2101c612: 4603 mov r3, r0 + 2101c614: 80fb strh r3, [r7, #6] + 2101c616: f04f 33ff mov.w r3, #4294967295 ; 0xffffffff + 2101c61a: 681b ldr r3, [r3, #0] + 2101c61c: 60fb str r3, [r7, #12] + 2101c61e: 68f9 ldr r1, [r7, #12] + 2101c620: 4803 ldr r0, [pc, #12] ; (2101c630 ) + 2101c622: f001 f92b bl 2101d87c + 2101c626: 68fb ldr r3, [r7, #12] + 2101c628: 4618 mov r0, r3 + 2101c62a: 3710 adds r7, #16 + 2101c62c: 46bd mov sp, r7 + 2101c62e: bd80 pop {r7, pc} + 2101c630: 21025f90 .word 0x21025f90 + ``` + + As indicated by the information displayed: + + - The CPU is executing **ldr r3, [r3, #0]** when an exception occurs. The value of **r3** is **0xffffffff**, which causes an invalid address. + - The exception occurs in the **GetResultException0** function. + +4. Search for the parent function of the abnormal function based on the LR value. + The code disassembly of the LR value **0x2101c64d** is as follows: + + ``` + 2101c634 : + 2101c634: b580 push {r7, lr} + 2101c636: b082 sub sp, #8 + 2101c638: af00 add r7, sp, #0 + 2101c63a: 4603 mov r3, r0 + 2101c63c: 80fb strh r3, [r7, #6] + 2101c63e: 4806 ldr r0, [pc, #24] ; (2101c658 ) + 2101c640: f001 f91c bl 2101d87c + 2101c644: 88fb ldrh r3, [r7, #6] + 2101c646: 4618 mov r0, r3 + 2101c648: f7ff ffe0 bl 2101c60c + 2101c64c: 4603 mov r3, r0 + 2101c64e: 4618 mov r0, r3 + 2101c650: 3708 adds r7, #8 + 2101c652: 46bd mov sp, r7 + 2101c654: bd80 pop {r7, pc} + 2101c656: bf00 nop + 2101c658: 21025fb0 .word 0x21025fb0 + ``` + + The previous line of LR **2101c648** is **bl2101c60c **, which calls the abnormal function. The parent function is **GetResultException1**. + +5. Parse the LR value between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship where the exception occurs and find the cause of the exception. \ No newline at end of file diff --git a/en/device-dev/kernel/kernel-mini-memory-lms.md b/en/device-dev/kernel/kernel-mini-memory-lms.md index afce67ceeabce8acadfd993eebd32f7e968280b9..eb6f913d03dd05d67d02f852c9975c53918a8a24 100644 --- a/en/device-dev/kernel/kernel-mini-memory-lms.md +++ b/en/device-dev/kernel/kernel-mini-memory-lms.md @@ -1,180 +1,117 @@ # LMS + ## Basic Concepts -Lite Memory Sanitizer \(LMS\) is a tool used to detect memory errors on a real-time basis. LMS can detect buffer overflow, Use-After-Free \(UAF\), and double free errors in real time, and notify the operating system immediately. Together with locating methods such as Backtrace, LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors. +Lite Memory Sanitizer (LMS) is a tool used to detect memory errors on a real-time basis. It can detect buffer overflow, Use-After-Free (UAF), and double free errors in real time, and notify the operating system immediately. Together with Backtrace, the LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors. The LMS module of the OpenHarmony LiteOS-M kernel provides the following functions: -- Supports check of multiple memory pools. -- Checks the memory allocated by **LOS\_MemAlloc**, **LOS\_MemAllocAlign**, and **LOS\_MemRealloc**. -- Checks the memory when bounds-checking functions are called \(enabled by default\). -- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called. +- Supports check of multiple memory pools. + +- Checks the memory allocated by **LOS_MemAlloc**, **LOS_MemAllocAlign**, and **LOS_MemRealloc**. + +- Checks the memory when bounds-checking functions are called (enabled by default). + +- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called. + ## Working Principles -LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool. +The LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool. + +- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state. + +- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state. + +- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported. + +- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported. -- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state. -- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state. -- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported. -- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported. ## Available APIs -The LMS module of the OpenHarmony LiteOS-M kernel provides the following APIs. For more details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_m/blob/master/components/lms/los_lms.h) reference. - -**Table 1** LMS module APIs - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Adding a memory pool to be checked

-

LOS_LmsCheckPoolAdd

-

Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, LOS_MemInit calls this API to add the initialized memory pool to the LMS check linked list by default.

-

Deleting a memory pool from the LMS check linked list

-

LOS_LmsCheckPoolDel

-

Cancels the validity check on the specified memory pool.

-

Protecting a specified memory chunk

-

LOS_LmsAddrProtect

-

Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.

-

Disabling protection of a specified memory chunk

-

LOS_LmsAddrDisableProtect

-

Unlocks a memory chunk to make it readable and writable.

-
+The LMS module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_m/blob/master/components/lms/los_lms.h). + +**Table 1** APIs of the LMS module + +| Category| API | Description| +| -------- | -------- | -------- | +| Adding a memory pool to be checked| LOS_LmsCheckPoolAdd | Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, **LOS_MemInit** calls this API to add the initialized memory pool to the LMS check linked list by default.| +| Deleting a memory pool from the LMS check linked list| LOS_LmsCheckPoolDel | Cancels the validity check on the specified memory pool.| +| Protecting a specified memory chunk| LOS_LmsAddrProtect | Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.| +| Disabling protection of a specified memory chunk| LOS_LmsAddrDisableProtect | Unlocks a memory chunk to make it readable and writable.| + ## Development Guidelines + ### How to Develop The typical process for enabling LMS is as follows: -1. Configure the macros related to the LMS module. - - Configure the LMS macro **LOSCFG\_KERNEL\_LMS**, which is disabled by default. Run the **make update\_config** command in the **kernel/liteos\_m** directory, choose **Kernel**, and set **Enable Lite Memory Sanitizer** to **Yes**. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Macro

-

menuconfig Option

-

Description

-

Value

-

LOSCFG_KERNEL_LMS

-

Enable Lms Feature

-

Whether to enable LMS.

-

YES/NO

-

LOSCFG_LMS_MAX_RECORD_POOL_NUM

-

Lms check pool max num

-

Maximum number of memory pools that can be checked by LMS.

-

INT

-

LOSCFG_LMS_LOAD_CHECK

-

Enable lms read check

-

Whether to enable LMS read check.

-

YES/NO

-

LOSCFG_LMS_STORE_CHECK

-

Enable lms write check

-

Whether to enable LMS write check.

-

YES/NO

-

LOSCFG_LMS_CHECK_STRICT

-

Enable lms strict check, byte-by-byte

-

Whether to enable LMS byte-by-byte check.

-

YES/NO

-
- -2. Modify the compile script of the target module. - - Add "-fsanitize=kernel-address" to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler. - - The modifications vary depending on the compiler \(GCC or Clang\) used. The following is an example: - - ``` - if ("$ohos_build_compiler_specified" == "gcc") { - cflags_c = [ - "-O0", - "-fsanitize=kernel-address", - ] - } else { - cflags_c = [ - "-O0", - "-fsanitize=kernel-address", - "-mllvm", - "-asan-instrumentation-with-call-threshold=0", - "-mllvm", - "-asan-stack=0", - "-mllvm", - "-asan-globals=0", - ] - } - ``` +1. Configure the macros related to the LMS module. + Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default. + + Run the **make menuconfig** command in the **kernel/liteos_m** directory, and set **Kernel->Enable Lite Memory Sanitizer** to **YES**. If this option is unavailable, select **Enable Backtrace**. + + | Macro| menuconfig Option| Description| Value| + | -------- | -------- | -------- | -------- | + | LOSCFG_KERNEL_LMS | Enable Lms Feature | Whether to enable LMS.| YES/NO | + | LOSCFG_LMS_MAX_RECORD_POOL_NUM | Lms check pool max num | Maximum number of memory pools that can be checked by LMS.| INT | + | LOSCFG_LMS_LOAD_CHECK | Enable lms read check | Whether to enable LMS read check.| YES/NO | + | LOSCFG_LMS_STORE_CHECK | Enable lms write check | Whether to enable LMS write check.| YES/NO | + | LOSCFG_LMS_CHECK_STRICT | Enable lms strict check, byte-by-byte | Whether to enable LMS byte-by-byte check.| YES/NO | + +2. Modify the build script of the target module. + Add **-fsanitize=kernel-address** to insert memory access checks, and add **-O0** to disable optimization performed by the compiler. + + The modifications vary depending on the compiler (GCC or Clang) used. The following is an example: + + ``` + if ("$ohos_build_compiler_specified" == "gcc") { + cflags_c = [ + "-O0", + "-fsanitize=kernel-address", + ] + } else { + cflags_c = [ + "-O0", + "-fsanitize=kernel-address", + "-mllvm", + "-asan-instrumentation-with-call-threshold=0", + "-mllvm", + "-asan-stack=0", + "-mllvm", + "-asan-globals=0", + ] + } + ``` + +3. Recompile the code and check the serial port output. + + The memory problem detected will be displayed. -3. Recompile the code and check the serial port output. The memory problem detected will be displayed. ### Development Example This example implements the following: -1. Create a task for LMS. -2. Construct a buffer overflow error and a UAF error. -3. Add "-fsanitize=kernel-address", execute the compilation, and check the output. +1. Create a task for LMS. + +2. Construct a buffer overflow error and a UAF error. + +3. Add "-fsanitize=kernel-address", execute the compilation, and check the output. + ### Sample Code The code is as follows: +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **Example_Lms_test** function is called in **TestTaskEntry**. + +Modify **./kernel/liteos_m/testsuites/BUILD.gn** corresponding to **osTest.c**. + ``` #define PAGE_SIZE (0x1000U) #define INDEX_MAX 20 @@ -214,10 +151,10 @@ VOID LmsTestCaseTask(VOID) UINT32 Example_Lms_test(VOID){ UINT32 ret; TSK_INIT_PARAM_S lmsTestTask; - /* Create a task for LMS. */ + /* Create a task for LMS. */ memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask; - lmsTestTask.pcName = "TestLmsTsk"; /* Task name. */ + lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */ lmsTestTask.uwStackSize = 0x800; lmsTestTask.usTaskPrio = 5; lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; @@ -230,89 +167,137 @@ UINT32 Example_Lms_test(VOID){ } ``` + ### Verification -The output is as follows: + The following is an example of the command output. The data may vary depending on the running environment. ``` ######LmsTestOsmallocOverflow start ###### -[ERR]***** Kernel Address Sanitizer Error Detected Start ***** -[ERR]Heap buffer overflow error detected -[ERR]Illegal READ address at: [0x4157a3c8] -[ERR]Shadow memory address: [0x4157be3c : 4] Shadow memory value: [2] -OsBackTrace fp = 0x402c0f88 -runTask->taskName = LmsTestCaseTask -runTask->taskID = 2 -*******backtrace begin******* -traceback fp fixed, trace using fp = 0x402c0fd0 -traceback 0 -- lr = 0x400655a4 fp = 0x402c0ff8 -traceback 1 -- lr = 0x40065754 fp = 0x402c1010 -traceback 2 -- lr = 0x40044bd0 fp = 0x402c1038 -traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca -[LMS] Dump info around address [0x4157a3c8]: - [0x4157a3a0]: 00 00 00 00 00 00 00 00 | [0x4157be3a | 0]: 1 1 - [0x4157a3a8]: ba dc cd ab 00 00 00 00 | [0x4157be3a | 4]: 2 2 - [0x4157a3b0]: 20 00 00 80 00 00 00 00 | [0x4157be3b | 0]: 2 0 - [0x4157a3b8]: 00 00 00 00 00 00 00 00 | [0x4157be3b | 4]: 0 0 - [0x4157a3c0]: 00 00 00 00 00 00 00 00 | [0x4157be3c | 0]: 0 0 - [0x4157a3c8]: [ba] dc cd ab a8 a3 57 41 | [0x4157be3c | 4]: [2] 2 - [0x4157a3d0]: 2c 1a 00 00 00 00 00 00 | [0x4157be3d | 0]: 2 3 - [0x4157a3d8]: 00 00 00 00 00 00 00 00 | [0x4157be3d | 4]: 3 3 - [0x4157a3e0]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 0]: 3 3 - [0x4157a3e8]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 4]: 3 3 - [0x4157a3f0]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 0]: 3 3 -[ERR]***** Kernel Address Sanitizer Error Detected End ***** -str[20]=0xffffffba +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected Start ***** +[ERR][TestLmsTsk]Heap buffer overflow error detected +[ERR][TestLmsTsk]Illegal READ address at: [0x21040414] +[ERR][TestLmsTsk]Shadow memory address: [0x21041e84 : 6] Shadow memory value: [2] +psp, start = 21057d88, end = 21057e80 +taskName = TestLmsTsk +taskID = 5 +----- traceback start ----- +traceback 0 -- lr = 0x210099f4 +traceback 1 -- lr = 0x2101da6e +traceback 2 -- lr = 0x2101db38 +traceback 3 -- lr = 0x2101c494 +----- traceback end ----- + +[LMS] Dump info around address [0x21040414]: + + [0x21040390]: 00 00 00 00 00 00 00 00 | [0x21041e7c | 4]: 1 1 + [0x21040398]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 0]: 1 1 + [0x210403a0]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 4]: 1 1 + [0x210403a8]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 0]: 1 1 + [0x210403b0]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 4]: 1 1 + [0x210403b8]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 0]: 1 1 + [0x210403c0]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 4]: 1 1 + [0x210403c8]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 0]: 1 1 + [0x210403d0]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 4]: 1 1 + [0x210403d8]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 0]: 1 1 + [0x210403e0]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 4]: 1 1 + [0x210403e8]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 0]: 1 1 + [0x210403f0]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 4]: 1 1 + [0x210403f8]: 40 1e 04 21 05 07 00 80 | [0x21041e83 | 0]: 2 2 + [0x21040400]: 00 00 00 00 00 00 00 00 | [0x21041e83 | 4]: 0 0 + [0x21040408]: 00 00 00 00 00 00 00 00 | [0x21041e84 | 0]: 0 0 + [0x21040410]: 00 00 00 00 [f8] 03 04 21 | [0x21041e84 | 4]: 0 [2] + [0x21040418]: 00 8b 06 00 00 00 00 00 | [0x21041e85 | 0]: 2 3 + [0x21040420]: 00 00 00 00 00 00 00 00 | [0x21041e85 | 4]: 3 3 + [0x21040428]: 00 00 00 00 00 00 00 00 | [0x21041e86 | 0]: 3 3 + [0x21040430]: 00 00 00 00 00 00 00 00 | [0x21041e86 | 4]: 3 3 + [0x21040438]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 0]: 3 3 + [0x21040440]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 4]: 3 3 + [0x21040448]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 0]: 3 3 + [0x21040450]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 4]: 3 3 + [0x21040458]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 0]: 3 3 + [0x21040460]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 4]: 3 3 + [0x21040468]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 0]: 3 3 + [0x21040470]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 4]: 3 3 + [0x21040478]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 0]: 3 3 + [0x21040480]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 4]: 3 3 + [0x21040488]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 0]: 3 3 + [0x21040490]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 4]: 3 3 +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected End ***** +str[20]=0xfffffff8 ######LmsTestOsmallocOverflow stop ###### -###### LmsTestUseAfterFree start ###### -[ERR]***** Kernel Address Sanitizer Error Detected Start ***** -[ERR]Use after free error detected -[ERR]Illegal READ address at: [0x4157a3d4] -[ERR]Shadow memory address: [0x4157be3d : 2] Shadow memory value: [3] -OsBackTrace fp = 0x402c0f90 -runTask->taskName = LmsTestCaseTask -runTask->taskID = 2 -*******backtrace begin******* -traceback fp fixed, trace using fp = 0x402c0fd8 -traceback 0 -- lr = 0x40065680 fp = 0x402c0ff8 -traceback 1 -- lr = 0x40065758 fp = 0x402c1010 -traceback 2 -- lr = 0x40044bd0 fp = 0x402c1038 -traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca -[LMS] Dump info around address [0x4157a3d4]: - [0x4157a3a8]: ba dc cd ab 00 00 00 00 | [0x4157be3a | 4]: 2 2 - [0x4157a3b0]: 20 00 00 80 00 00 00 00 | [0x4157be3b | 0]: 2 0 - [0x4157a3b8]: 00 00 00 00 00 00 00 00 | [0x4157be3b | 4]: 0 0 - [0x4157a3c0]: 00 00 00 00 00 00 00 00 | [0x4157be3c | 0]: 0 0 - [0x4157a3c8]: ba dc cd ab a8 a3 57 41 | [0x4157be3c | 4]: 2 2 - [0x4157a3d0]: 2c 1a 00 00 [00] 00 00 00 | [0x4157be3d | 0]: 2 [3] - [0x4157a3d8]: 00 00 00 00 00 00 00 00 | [0x4157be3d | 4]: 3 3 - [0x4157a3e0]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 0]: 3 3 - [0x4157a3e8]: ba dc cd ab c8 a3 57 41 | [0x4157be3e | 4]: 2 2 - [0x4157a3f0]: 0c 1a 00 00 00 00 00 00 | [0x4157be3f | 0]: 2 3 - [0x4157a3f8]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 4]: 3 3 -[ERR]***** Kernel Address Sanitizer Error Detected End ***** + +######LmsTestUseAfterFree start ###### +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected Start ***** +[ERR][TestLmsTsk]Use after free error detected +[ERR][TestLmsTsk]Illegal READ address at: [0x2104041c] +[ERR][TestLmsTsk]Shadow memory address: [0x21041e85 : 2] Shadow memory value: [3] +psp, start = 21057d90, end = 21057e80 +taskName = TestLmsTsk +taskID = 5 +----- traceback start ----- +traceback 0 -- lr = 0x210099f4 +traceback 1 -- lr = 0x2101daec +traceback 2 -- lr = 0x2101db3c +traceback 3 -- lr = 0x2101c494 +----- traceback end ----- + +[LMS] Dump info around address [0x2104041c]: + + [0x21040398]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 0]: 1 1 + [0x210403a0]: 00 00 00 00 00 00 00 00 | [0x21041e7d | 4]: 1 1 + [0x210403a8]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 0]: 1 1 + [0x210403b0]: 00 00 00 00 00 00 00 00 | [0x21041e7e | 4]: 1 1 + [0x210403b8]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 0]: 1 1 + [0x210403c0]: 00 00 00 00 00 00 00 00 | [0x21041e7f | 4]: 1 1 + [0x210403c8]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 0]: 1 1 + [0x210403d0]: 00 00 00 00 00 00 00 00 | [0x21041e80 | 4]: 1 1 + [0x210403d8]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 0]: 1 1 + [0x210403e0]: 00 00 00 00 00 00 00 00 | [0x21041e81 | 4]: 1 1 + [0x210403e8]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 0]: 1 1 + [0x210403f0]: 00 00 00 00 00 00 00 00 | [0x21041e82 | 4]: 1 1 + [0x210403f8]: 40 1e 04 21 05 07 00 80 | [0x21041e83 | 0]: 2 2 + [0x21040400]: 00 00 00 00 00 00 00 00 | [0x21041e83 | 4]: 0 0 + [0x21040408]: 00 00 00 00 00 00 00 00 | [0x21041e84 | 0]: 0 0 + [0x21040410]: 00 00 00 00 f8 03 04 21 | [0x21041e84 | 4]: 0 2 + [0x21040418]: 05 8b 06 00 [00] 00 00 00 | [0x21041e85 | 0]: 2 [3] + [0x21040420]: 00 00 00 00 00 00 00 00 | [0x21041e85 | 4]: 3 3 + [0x21040428]: 00 00 00 00 00 00 00 00 | [0x21041e86 | 0]: 3 3 + [0x21040430]: 14 04 04 21 00 84 06 00 | [0x21041e86 | 4]: 2 2 + [0x21040438]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 0]: 3 3 + [0x21040440]: 00 00 00 00 00 00 00 00 | [0x21041e87 | 4]: 3 3 + [0x21040448]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 0]: 3 3 + [0x21040450]: 00 00 00 00 00 00 00 00 | [0x21041e88 | 4]: 3 3 + [0x21040458]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 0]: 3 3 + [0x21040460]: 00 00 00 00 00 00 00 00 | [0x21041e89 | 4]: 3 3 + [0x21040468]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 0]: 3 3 + [0x21040470]: 00 00 00 00 00 00 00 00 | [0x21041e8a | 4]: 3 3 + [0x21040478]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 0]: 3 3 + [0x21040480]: 00 00 00 00 00 00 00 00 | [0x21041e8b | 4]: 3 3 + [0x21040488]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 0]: 3 3 + [0x21040490]: 00 00 00 00 00 00 00 00 | [0x21041e8c | 4]: 3 3 + [0x21040498]: 00 00 00 00 00 00 00 00 | [0x21041e8d | 0]: 3 3 +[ERR][TestLmsTsk]***** Kernel Address Sanitizer Error Detected End ***** str[ 0]=0x 0 ######LmsTestUseAfterFree stop ###### ``` The key output information is as follows: -- Error type: - - Heap buffer overflow - - UAF - -- Incorrect operations: - - Illegal read - - Illegal write - - Illegal double free - -- Context: - - Task information \(**taskName** and **taskId**\) - - Backtrace +- Error type: + - Heap buffer overflow + - UAF -- Memory information of the error addresses: - - Memory value and the value of the corresponding shadow memory - - Memory address: memory value|\[shadow memory address|shadow memory byte offset\]: shadow memory value - - Shadow memory value. **0** \(Accessible\), **3** \(Freed\), **2** \(RedZone\), and **1** \(filled value\) +- Incorrect operations: + - Illegal read + - Illegal write + - Illegal double free +- Context: + - Task information (**taskName** and **taskId**) + - Backtrace +- Memory information of the error addresses: + - Memory value and the value of the corresponding shadow memory + - Memory address: memory value|[shadow memory address|shadow memory byte offset]: shadow memory value + - Shadow memory value. **0** (Accessible), **3** (Freed), **2** (RedZone), and **1** (filled value) diff --git a/en/device-dev/kernel/kernel-mini-memory-perf.md b/en/device-dev/kernel/kernel-mini-memory-perf.md deleted file mode 100644 index 95d097792307376342a55eefcfde96f7f921952b..0000000000000000000000000000000000000000 --- a/en/device-dev/kernel/kernel-mini-memory-perf.md +++ /dev/null @@ -1,449 +0,0 @@ -# perf - - -## Basic Concepts - -perf is a performance analysis tool. It uses the performance monitoring unit (PMU) to count sampling events and collect context information and provides hot spot distribution and hot paths. - - -## Working Principles - -When a performance event occurs, the corresponding event counter overflows and triggers an interrupt. The interrupt handler records the event information, including the current PC, task ID, and call stack. - -perf provides two working modes: counting mode and sampling mode. - -In counting mode, perf collects only the number of event occurrences and duration. In sampling mode, perf also collects context data and stores the data in a circular buffer. The IDE then analyzes the data and provides information about hotspot functions and paths. - - -## Available APIs - - -### Kernel Mode - -The Perf module of the OpenHarmony LiteOS-A kernel provides the following functions. For details about the interfaces, see the [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h). - - **Table 1** APIs of the perf module - -| API| Description| -| -------- | -------- | -| LOS_PerfStart| Starts sampling.| -| LOS_PerfStop| Stops sampling.| -| LOS_PerfConfig| Sets the event type and sampling interval.| -| LOS_PerfDataRead| Reads the sampling data.| -| LOS_PerfNotifyHookReg| Registers the hook to be called when the buffer waterline is reached.| -| LOS_PerfFlushHookReg| Registers the hook for flushing the cache in the buffer.| - -- The structure of the perf sampling event is **PerfConfigAttr**. For details, see **kernel\include\los_perf.h**. - -- The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten. - -- The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size. - - Example: - - ``` - VOID Example_PerfNotifyHook(VOID) - { - CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0}; - UINT32 len; - PRINT_DEBUG("perf buffer reach the waterline!\n"); - len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE); - OsPrintBuff(buf, len); /* print data */ - } - LOS_PerfNotifyHookReg(Example_PerfNotifyHook); - ``` - -- If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency. - - Example: - - ``` - VOID Example_PerfFlushHook(VOID *addr, UINT32 size) - { - OsCacheFlush(addr, size); /* platform interface */ - } - LOS_PerfNotifyHookReg(Example_PerfFlushHook); - ``` - - The API for flushing the cache is configured based on the platform. - - -### User Mode - - -The perf character device is located in **/dev/perf**. You can read, write, and control the user-mode perf by running the following commands on the device node: - - -- **read**: reads perf data in user mode. - -- **write**: writes user-mode sampling events. - -- **ioctl**: controls the user-mode perf, which includes the following: - - ``` - #define PERF_IOC_MAGIC 'T' - #define PERF_START _IO(PERF_IOC_MAGIC, 1) - #define PERF_STOP _IO(PERF_IOC_MAGIC, 2) - ``` - - The operations correspond to **LOS_PerfStart** and **LOS_PerfStop**. - - -For details, see [User-Mode Development Example](#user-mode-development-example). - - -## How to Develop - - -### Kernel-Mode Development Process - -The typical process of enabling perf is as follows: - -1. Configure the macros related to the perf module. - - Configure the perf control macro **LOSCFG_KERNEL_PERF**, which is disabled by default. In the **kernel/liteos_a** directory, run the **make update_config** command, choose **Kernel**, and select **Enable Perf Feature**. - - | Item| menuconfig Option| Description| Value| - | -------- | -------- | -------- | -------- | - | LOSCFG_KERNEL_PERF | Enable Perf Feature | Whether to enable perf.| YES/NO | - | LOSCFG_PERF_CALC_TIME_BY_TICK | Time-consuming Calc Methods->By Tick | Whether to use tick as the perf timing unit.| YES/NO | - | LOSCFG_PERF_CALC_TIME_BY_CYCLE | Time-consuming Calc Methods->By Cpu Cycle | Whether to use cycle as the perf timing unit.| YES/NO | - | LOSCFG_PERF_BUFFER_SIZE | Perf Sampling Buffer Size | Size of the buffer used for perf sampling.| INT | - | LOSCFG_PERF_HW_PMU | Enable Hardware Pmu Events for Sampling | Whether to enable hardware PMU events. The target platform must support the hardware PMU.| YES/NO | - | LOSCFG_PERF_TIMED_PMU | Enable Hrtimer Period Events for Sampling | Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).| YES/NO | - | LOSCFG_PERF_SW_PMU | Enable Software Events for Sampling | Whether to enable software events. **LOSCFG_KERNEL_HOOK** must also be enabled.| YES/NO | - -2. Call **LOS_PerfConfig** to configure the events to be sampled. - - perf provides two working modes and three types of events. - - Working modes: counting mode (counts only the number of event occurrences) and sampling mode (collects context information such as task IDs, PC, and backtrace) - - Events: CPU hardware events (such as cycle, branch, icache, and dcache), high-precision periodical events (such as CPU clock), and OS software events (such as task switch, mux pend, and IRQ) - -3. Call **LOS_PerfStart(UINT32 sectionId)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs. - -4. Call **LOS_PerfStop** at the end of the code to be sampled. - -5. Call **LOS_PerfDataRead** to read the sampling data and use IDE to analyze the collected data. - - -#### Kernel-Mode Development Example - -This example implements the following: - -1. Create a perf task. - -2. Configure sampling events. - -3. Start perf. - -4. Execute algorithms for statistics. - -5. Stop perf. - -6. Export the result. - - -#### Kernel-Mode Sample Code - -Prerequisites: The perf module configuration is complete in **menuconfig**. - -The sample code is as follows: - -``` -#include "los_perf.h" -STATIC VOID OsPrintBuff(const CHAR *buf, UINT32 num) -{ - UINT32 i = 0; - PRINTK("num: "); - for (i = 0; i < num; i++) { - PRINTK(" %02d", i); - } - PRINTK("\n"); - PRINTK("hex: "); - for (i = 0; i < num; i++) { - PRINTK(" %02x", buf[i]); - } - PRINTK("\n"); -} -STATIC VOID perfTestHwEvent(VOID) -{ - UINT32 ret; - CHAR *buf = NULL; - UINT32 len; - PerfConfigAttr attr = { - .eventsCfg = { - .type = PERF_EVENT_TYPE_HW, - .events = { - [0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF}, - [1] = {PERF_COUNT_HW_BRANCH_INSTRUCTIONS, 0xFFFFFF00}, - }, - .eventsNr = 2, - .predivided = 1, /* cycle counter increase every 64 cycles */ - }, - .taskIds = {0}, - .taskIdsNr = 0, - .needSample = 0, - .sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN, - }; - ret = LOS_PerfConfig(&attr); - if (ret != LOS_OK) { - PRINT_ERR("perf config error %u\n", ret); - return; - } - PRINTK("------count mode------\n"); - LOS_PerfStart(0); - test(); /* this is any test function*/ - LOS_PerfStop(); - PRINTK("--------sample mode------ \n"); - attr.needSample = 1; - LOS_PerfConfig(&attr); - LOS_PerfStart(2); - test(); /* this is any test function*/ - LOS_PerfStop(); - buf = LOS_MemAlloc(m_aucSysMem1, LOSCFG_PERF_BUFFER_SIZE); - if (buf == NULL) { - PRINT_ERR("buffer alloc failed\n"); - return; - } - /* get sample data */ - len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE); - OsPrintBuff(buf, len); /* print data */ - (VOID)LOS_MemFree(m_aucSysMem1, buf); -} -UINT32 Example_Perf_test(VOID){ - UINT32 ret; - TSK_INIT_PARAM_S perfTestTask; - /* Create a perf task. */ - memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S)); - perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent; - perfTestTask.pcName = "TestPerfTsk"; /* Test task name. */ - perfTestTask.uwStackSize = 0x800; - perfTestTask.usTaskPrio = 5; - perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED; - ret = LOS_TaskCreate(&g_perfTestTaskId, &perfTestTask); - if(ret != LOS_OK){ - PRINT_ERR("PerfTestTask create failed.\n"); - return LOS_NOK; - } - return LOS_OK; -} -LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED); -``` - - -#### Kernel-Mode Verification - - The output is as follows: - -``` ---------count mode---------- -[EMG] [cycles] eventType: 0xff: 5466989440 -[EMG] [branches] eventType: 0xc: 602166445 -------- sample mode---------- -[EMG] dump section data, addr: 0x8000000 length: 0x800000 -num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ... -hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 -``` - -- For the counting mode, the following information is displayed after perf is stopped: - Event name (cycles), event type (0xff), and number of event occurrences (5466989440) - - For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**. - -- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped: - dump section data, addr: (0x8000000) length: (0x5000) - - You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data. - - You can also call **LOS_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte. - - -### User-Mode Development Process - -Choose **Driver** > **Enable PERF DRIVER** in **menuconfig** to enable the perf driver. This option is available in **Driver** only after **Enable Perf Feature** is selected in the kernel. - -1. Open the **/dev/perf** file and perform read, write, and ioctl operations. - -2. Run the **perf** commands in user mode in the **/bin** directory. - - After running **cd bin**, you can use the following commands: - - - **./perf start [*id*]**: starts perf sampling. *id* is optional and is **0** by default. - - **./perf stop**: stops perf sampling. - - **./perf read <*nBytes*>**: reads n-byte data from the sampling buffer and displays the data. - - **./perf list**: lists the events supported by **-e**. - - **./perf stat/record [*option*] <*command*>**: sets counting or sampling parameters. - - The [*option*] can be any of the following: - - -**-e**: sets sampling events. Events of the same type listed in **./perf list** can be used. - - -**-p**: sets the event sampling interval. - - -**-o**: specifies the path of the file for saving the perf sampling data. - - -**-t**: specifies the task IDs for data collection. Only the contexts of the specified tasks are collected. If this parameter is not specified, all tasks are collected by default. - - -**-s**: specifies the context type for sampling. For details, see **PerfSampleType** defined in **los_perf.h**. - - -**-P**: specifies the process IDs for data collection. Only the contexts of the specified processes are collected. If this parameter is not specified, all processes are collected by default. - - -**-d**: specifies whether to divide the frequency (the value is incremented by 1 each time an event occurs 64 times). This option is valid only for hardware cycle events. - - *command* specifies the program to be checked by perf. - -Examples: - -Run the **./perf list** command to display available events. - -The output is as follows: - - -``` -cycles [Hardware event] -instruction [Hardware event] -dcache [Hardware event] -dcache-miss [Hardware event] -icache [Hardware event] -icache-miss [Hardware event] -branch [Hardware event] -branch-miss [Hardware event] -clock [Timed event] -task-switch [Software event] -irq-in [Software event] -mem-alloc [Software event] -mux-pend [Software event] -``` - -Run **./perf stat -e cycles os_dump**. - -The output is as follows: - - -``` -type: 0 -events[0]: 255, 0xffff -predivided: 0 -sampleType: 0x0 -needSample: 0 -usage os_dump [--help | -l | SERVICE] - --help: shows this help - -l: only list services, do not dump them - SERVICE: dumps only service SERVICE -time used: 0.058000(s) -[cycles] eventType: 0xff [core 0]: 21720647 -[cycles] eventType: 0xff [core 1]: 13583830 -``` - -Run **./perf record -e cycles os_dump**. - -The output is as follows: - - -``` -type: 0 -events[0]: 255, 0xffff -predivided: 0 -sampleType: 0x60 -needSample: 1 -usage os_dump [--help | -l | SERVICE] - --help: shows this help - -l: only list services, do not dump them - SERVICE: dumps only service SERVICE -dump perf data, addr: 0x408643d8 length: 0x5000 -time used: 0.059000(s) -save perf data success at /storage/data/perf.data -``` - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> After running the **./perf stat/record** command, you can run the **./perf start** and **./perf stop** commands multiple times. The sampling event configuration is as per the parameters set in the latest **./perfstat/record** command. - - -#### User-Mode Development Example - -This example implements the following: - -1. Open the perf character device. - -2. Write the perf events. - -3. Start perf. - -4. Stop perf. - -5. Read the perf sampling data. - - -#### User-Mode Sample Code - - The code is as follows: - -``` -#include "fcntl.h" -#include "user_copy.h" -#include "sys/ioctl.h" -#include "fs/driver.h" -#include "los_dev_perf.h" -#include "los_perf.h" -#include "los_init.h" -/* perf ioctl */ -#define PERF_IOC_MAGIC 'T' -#define PERF_START _IO(PERF_IOC_MAGIC, 1) -#define PERF_STOP _IO(PERF_IOC_MAGIC, 2) -int main(int argc, char **argv) -{ - char *buf = NULL; - ssize_t len; - int fd = open("/dev/perf", O_RDWR); - if (fd == -1) { - printf("Perf open failed.\n"); - exit(EXIT_FAILURE); - } - PerfConfigAttr attr = { - .eventsCfg = { -#ifdef LOSCFG_PERF_HW_PMU - .type = PERF_EVENT_TYPE_HW, - .events = { - [0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF}, - }, -#elif defined LOSCFG_PERF_TIMED_PMU - .type = PERF_EVENT_TYPE_TIMED, - .events = { - [0] = {PERF_COUNT_CPU_CLOCK, 100}, - }, -#elif defined LOSCFG_PERF_SW_PMU - .type = PERF_EVENT_TYPE_SW, - .events = { - [0] = {PERF_COUNT_SW_TASK_SWITCH, 1}, - }, -#endif - .eventsNr = 1, /* 1 event */ - .predivided = 0, - }, - .taskIds = {0}, - .taskIdsNr = 0, - .processIds = {0}, - .processIdsNr = 0, - .needSample = 1, - .sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN, - }; - (void)write(fd, &attr, sizeof(PerfConfigAttr)); /* perf config */ - ioctl(fd, PERF_START, NULL); /* perf start */ - test(); - ioctl(fd, PERF_STOP, NULL); /* perf stop */ - buf = (char *)malloc(LOSCFG_PERF_BUFFER_SIZE); - if (buf == NULL) { - printf("no memory for read perf 0x%x\n", LOSCFG_PERF_BUFFER_SIZE); - return -1; - } - len = read(fd, buf, LOSCFG_PERF_BUFFER_SIZE); - OsPrintBuff(buf, len); /* print data */ - free(buf); - close(fd); - return 0; -} -``` - - -#### User-Mode Verification - - The output is as follows: - -``` -[EMG] dump section data, addr: 0x8000000 length: 0x800000 -num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ... -hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 -``` diff --git a/en/device-dev/kernel/kernel-mini-memory-trace.md b/en/device-dev/kernel/kernel-mini-memory-trace.md index 1417442602eee705b8541acd9547f3dd55267d23..a60e3656c477f26c58cc135304fb343bb4c34730 100644 --- a/en/device-dev/kernel/kernel-mini-memory-trace.md +++ b/en/device-dev/kernel/kernel-mini-memory-trace.md @@ -1,8 +1,10 @@ # Trace + ## Basic Concepts -Trace helps you learn about the kernel running process and the execution sequence of modules and tasks. With the information, you can better understand the code running process of the kernel and locate time sequence problems. +Trace helps you learn about the kernel running process and the execution sequence of modules and tasks. With the traced information, you can better understand the code running process of the kernel and locate time sequence problems. + ## Working Principles @@ -16,265 +18,168 @@ In offline mode, trace frames are stored in a circular buffer. If too many frame ![](figures/kernel-small-mode-process.png) -The online mode must be used with the integrated development environment \(IDE\). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner. +The online mode must be used with the integrated development environment (IDE). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner. -## Available APIs -The trace module of the OpenHarmony LiteOS-M kernel provides the following functions. For more details about the APIs, see the API reference. - -**Table 1** Trace module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Starting and stopping trace

-

LOS_TraceStart

-

Starts trace.

-

LOS_TraceStop

-

Stops trace.

-

Managing trace records

-

LOS_TraceRecordDump

-

Exports data in the trace buffer.

-

LOS_TraceRecordGet

-

Obtains the start address of the trace buffer.

-

LOS_TraceReset

-

Clears events in the trace buffer.

-

Filtering trace records

-

LOS_TraceEventMaskSet

-

Sets the event mask to trace only events of the specified modules.

-

Masking events of specified interrupt IDs

-

LOS_TraceHwiFilterHookReg

-

Registers a hook to filter out events of specified interrupt IDs.

-

Performing function instrumentation

-

LOS_TRACE_EASY

-

Performs simple instrumentation.

-

LOS_TRACE

-

Performs standard instrumentation.

-
- -- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation: - - **LOS\_TRACE\_EASY\(TYPE, IDENTITY, params...\)** for simple instrumentation - - You only need to insert this API into the source code. - - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined. - - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type. - - **Params** specifies the event parameters. The value is of the **UIntPtr** type. - - Example: - - ``` - Perform simple instrumentation for reading and writing files fd1 and fd2. - Set TYPE to 1 for read operations and 2 for write operations. - Insert the following to the position where the fd1 file is read: - LOS_TRACE_EASY(1, fd1, flag, size); - Insert the following to the position where the fd2 file is read: - LOS_TRACE_EASY(1, fd2, flag, size); - Insert the following to the position where the fd1 file is written: - LOS_TRACE_EASY(2, fd1, flag, size); - Insert the following in the position where the fd2 file is written: - LOS_TRACE_EASY(2, fd2, flag, size); - ``` - - - **LOS\_TRACE\(TYPE, IDENTITY, params...\)** for standard instrumentation. - - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules. - - **TYPE** specifies the event type. You can define the event type in **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**. For details about methods and rules for defining events, see other event types. - - The **IDENTITY** and **Params** are the same as those of simple instrumentation. - - Example: - - ``` - 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK. - Format: TRACE_#MOD#_FLAG (MOD indicates the module name) - Example: - TRACE_FS_FLAG = 0x4000 - 2. Define the event type in enum LOS_TRACE_TYPE. - Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER - Example: - FS_READ = TRACE_FS_FLAG | 0; // Read files - FS_WRITE = TRACE_FS_FLAG | 1; // Write files - 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format. - #TYPE# is the #TYPE# defined in step 2. - Example: - #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size - The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required. - If no parameter is specified, events of this type are not traced. - #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced. - 4. Insert a code stub in a proper position. - Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) - LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files - The parameters following #TYPE# are the input parameter of the FS_READ_PARAMS function in step 3. - ``` - - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\\include\\los\_trace.h**. - - - -- For **LOS\_TraceEventMaskSet\(UINT32 mask\)**, only the most significant 28 bits \(corresponding to the enable bit of the module in **LOS\_TRACE\_MASK**\) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS\_TraceEventMaskSet\(0x202\)**, the effective mask is **0x200 \(TRACE\_QUE\_FLAG\)** and all events of the QUE module are collected. The recommended method is **LOS\_TraceEventMaskSet\(TRACE\_EVENT\_FLAG | TRACE\_MUX\_FLAG | TRACE\_SEM\_FLAG | TRACE\_QUE\_FLAG\);**. -- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE\_MAX\_FLAG**. -- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS\_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**. -- The typical trace operation process includes **LOS\_TraceStart**, **LOS\_TraceStop**, and **LOS\_TraceRecordDump**. -- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules. +## Available APIs +The trace module of the OpenHarmony LiteOS-M kernel provides the following APIs. For more details about the APIs, see the API reference. + + **Table 1** APIs of the trace module + +| Category| API| +| -------- | -------- | +| Starting/Stopping trace| - **LOS_TraceStart**: starts a trace.
- **LOS_TraceStop**: stops the trace.| +| Managing trace records| - **LOS_TraceRecordDump**: dumps data from the trace buffer.
- **LOS_TraceRecordGet**: obtains the start address of the trace buffer.
- **LOS_TraceReset**: clears events in the trace buffer.| +| Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.| +| Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.| +| Performing function instrumentation| - **LOS_TRACE_EASY**: performs simple instrumentation.
- **LOS_TRACE**: performs standard instrumentation.| + +- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation: + - **LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation + - You only need to insert this API into the source code. + - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined. + - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type. + - **Params** specifies the event parameters. The value is of the **UIntPtr** type. + - Example of simple instrumentation for reading and writing data based on the file FDs: + + ``` + /* Set TYPE to 1 for read operation and 2 for write operations. */ + LOS_TRACE_EASY(1, fd, flag, size); /* Add it to a proper position. */ + LOS_TRACE_EASY(2, fd, flag, size); /* Add it to a proper position. */ + ``` + - **LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation. + - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules. + - **TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types. + - The **IDENTITY** and **Params** are the same as those of simple instrumentation. + - Example: + 1. Define the type of the FS module (event mask of the FS module) in **enum LOS_TRACE_MASK**. + + ``` + /* Define the event mask in the format of TRACE_#MOD#_FLAG, where #MOD# indicates the module name. */ + TRACE_FS_FLAG = 0x4000 + ``` + + 2. Define the event types of the FS module. + + + ``` + /* Define the event type in the format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER */ + FS_READ = TRACE_FS_FLAG | 0; /* Read data. */ + FS_WRITE = TRACE_FS_FLAG | 1; /* Write data. */ + ``` + + 3. Define event parameters. + + + ``` + /* Define the parameters in the format: #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... */ + #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size /* The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can tailor the parameters as required. */ + #define FS_READ_PARAMS(fp, fd, flag, size) /* If no parameters are defined, events of this type are not traced. */ + ``` + + 4. Add the code stubs in the code. + + + ``` + /* Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) */ + LOS_TRACE(FS_READ, fp, fd, flag, size); /* Code stub for reading data. */ + ``` + + > **NOTE**
+ > You can modify the traced event types and parameters as required. For details about the parameters, see **kernel\include\los_trace.h**. + +- For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**. + +- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**. + +- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**. + +- The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**. + +- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
The sample code is as follows: + + ``` + BOOL Example_HwiNumFilter(UINT32 hwiNum) + { + if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { + return TRUE; + } + return FALSE; + } + LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); + ``` - ``` - BOOL Example_HwiNumFilter(UINT32 hwiNum) - { - if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { - return TRUE; - } - return FALSE; - } - LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); - ``` - - The interrupt events with interrupt ID of **TIMER\_INT** or **DMA\_INT** are not traced. + The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced. ## Development Guidelines + ### How to Develop -The typical trace process is as follows: - -1. Configure the macro related to the trace module. - - Modify the configuration in the **target\_config.h** file. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Configuration

-

Description

-

Value

-

LOSCFG_KERNEL_TRACE

-

Specifies whether to enable the trace feature.

-

YES/NO

-

LOSCFG_RECORDER_MODE_OFFLINE

-

Specifies whether to enable the online trace mode.

-

YES/NO

-

LOSCFG_RECORDER_MODE_ONLINE

-

Specifies whether to enable the offline trace mode.

-

YES/NO

-

LOSCFG_TRACE_CLIENT_INTERACT

-

Specifies whether to enable interaction with Trace IDE (dev tools), including data visualization and process control.

-

YES/NO

-

LOSCFG_TRACE_FRAME_CORE_MSG

-

Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.

-

YES/NO

-

LOSCFG_TRACE_FRAME_EVENT_COUNT

-

Specifies whether to enables recording of the event sequence number.

-

YES/NO

-

LOSCFG_TRACE_FRAME_MAX_PARAMS

-

Specifies the maximum number of parameters for event recording.

-

INT

-

LOSCFG_TRACE_BUFFER_SIZE

-

Specifies the trace buffer size.

-

INT

-
- -2. \(Optional\) Preset event parameters and stubs \(or use the default event parameter settings and event stubs\). -3. \(Optional\) Call **LOS\_TraceStop** to stop trace and call **LOS\_TraceReset** to clear the trace buffer. \(Trace is started by default.\) -4. \(Optional\) Call **LOS\_TraceEventMaskSet** to set the event mask for trace \(only the interrupts and task events are enabled by default\). For details about the event mask, see **LOS\_TRACE\_MASK** in **los\_trace.h**. -5. Call **LOS\_TraceStart** at the start of the code where the event needs to be traced. -6. Call **LOS\_TraceStop** at the end of the code where the event needs to be traced. -7. Call **LOS\_TraceRecordDump** to output the data in the buffer. \(The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to a Windows client.\) +The typical development process is as follows: + +1. Configure the macros related to the trace module in the **target_config.h** file. + | Configuration Item| Description| Value| + | -------- | -------- | -------- | + | LOSCFG_KERNEL_TRACE | Whether to enable the trace feature. | YES/NO | + | LOSCFG_RECORDER_MODE_OFFLINE | Whether to enable the online trace mode. | YES/NO | + | LOSCFG_RECORDER_MODE_ONLINE | Whether to enable the offline trace mode. | YES/NO | + | LOSCFG_TRACE_CLIENT_INTERACT | Whether to enable interaction with Trace IDE (dev tools), including data visualization and process control. | YES/NO | + | LOSCFG_TRACE_FRAME_CORE_MSG | Whether to enable trace of the CPU ID, interruption state, and lock task state. | YES/NO | + | LOSCFG_TRACE_FRAME_EVENT_COUNT | Whether to enable trace of the event sequence number. | YES/NO | + | LOSCFG_TRACE_FRAME_MAX_PARAMS | Specifies the maximum number of parameters for event tracing. | INT | + | LOSCFG_TRACE_BUFFER_SIZE | Specifies the trace buffer size.| INT | + +2. (Optional) Preset event parameters and stubs (or use the default event parameter settings and event stubs). + +3. (Optional) Call **LOS_TraceStop** to stop trace and **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.) + +4. (Optional) Call **LOS_TraceEventMaskSet** to set the event mask for trace (only the interrupts and task events are enabled by default). For details about the event mask, see **LOS_TRACE_MASK** in **los_trace.h**. + +5. Call **LOS_TraceStart** at the start of the code where the event needs to be traced. + +6. Call **LOS_TraceStop** at the end of the code where the event needs to be traced. + +7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to a Windows client.) The methods in steps 3 to 7 are encapsulated with shell commands. After the shell is enabled, the corresponding commands can be executed. The mapping is as follows: -- LOS\_TraceReset —— trace\_reset -- LOS\_TraceEventMaskSet —— trace\_mask -- LOS\_TraceStart —— trace\_start -- LOS\_TraceStop —— trace\_stop -- LOS\_TraceRecordDump —— trace\_dump +- LOS_TraceReset —— trace_reset + +- LOS_TraceEventMaskSet —— trace_mask + +- LOS_TraceStart —— trace_start + +- LOS_TraceStop —— trace_stop + +- LOS_TraceRecordDump —— trace_dump + ### Development Example This example implements the following: -1. Create a trace task. -2. Set the event mask. -3. Start trace. -4. Stop trace. -5. Output trace data in the specified format. +1. Create a trace task. + +2. Set the event mask. + +3. Start trace. + +4. Stop trace. + +5. Output trace data in the specified format. + ### Sample Code The sample code is as follows: +The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleTraceTest** function is called in **TestTaskEntry**. + + ``` #include "los_trace.h" UINT32 g_traceTestTaskId; @@ -288,21 +193,21 @@ VOID Example_Trace(VOID) dprintf("trace start error\n"); return; } - /* Trigger a task switching event.*/ + /* Trigger a task switching event. */ LOS_TaskDelay(1); LOS_TaskDelay(1); LOS_TaskDelay(1); - /* Stop trace.*/ + /* Stop trace. */ LOS_TraceStop(); LOS_TraceRecordDump(FALSE); } -UINT32 Example_Trace_test(VOID){ +UINT32 ExampleTraceTest(VOID){ UINT32 ret; - TSK_INIT_PARAM_S traceTestTask; - /* Create a trace task. */ + TSK_INIT_PARAM_S traceTestTask = { 0 }; + /* Create a trace task. */ memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; - traceTestTask.pcName = "TestTraceTsk"; /* Trace task name*/ + traceTestTask.pcName = "TestTraceTsk"; /* Trace task name. */ traceTestTask.uwStackSize = 0x800; traceTestTask.usTaskPrio = 5; traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; @@ -311,21 +216,23 @@ UINT32 Example_Trace_test(VOID){ dprintf("TraceTestTask create failed .\n"); return LOS_NOK; } - /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then restart trace. */ + /* Trace is started by default. You can stop trace, clear the buffer, and restart trace. */ LOS_TraceStop(); LOS_TraceReset(); - /* Enable trace of the Task module events. */ + /* Enable trace of the Task module events. */ LOS_TraceEventMaskSet(TRACE_TASK_FLAG); return LOS_OK; } ``` + ### Verification The output is as follows: + ``` -*******TraceInfo begin******* +***TraceInfo begin*** clockFreq = 50000000 CurEvtIndex = 7 Index Time(cycles) EventType CurTask Identity params @@ -337,36 +244,43 @@ Index Time(cycles) EventType CurTask Identity params 5 0x36eec810 0x45 0xc 0x1 0x9 0x8 0x1f 6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0 7 0x37070e59 0x45 0x0 0x1 0x0 0x8 0x1f -*******TraceInfo end******* +***TraceInfo end*** + +The preceding data may vary depending on the running environment. ``` The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event. -- **EventType**: event type. For details, see **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**. -- **CurrentTask**: ID of the running task. -- **Identity**: object of the event operation. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**. -- **params**: event parameters. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**. +- **EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. + +- **CurrentTask**: ID of the running task. + +- **Identity**: object of the event operation. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**. + +- **params**: event parameters. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**. The following uses output No. 0 as an example. + ``` Index Time(cycles) EventType CurTask Identity params 0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4 ``` -- **Time \(cycles\)** can be converted into time \(in seconds\) by dividing the cycles by clockFreq. -- **0x45** indicates the task switching event. **0x1** is the ID of the task in running. -- For details about the meanings of **Identity** and **params**, see the **TASK\_SWITCH\_PARAMS** macro. +- **Time (cycles)** can be converted into time (in seconds) by dividing the cycles by clockFreq. +- **0x45** indicates the task switching event. **0x1** is the ID of the task in running. + +- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro. + + ``` #define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \ taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus ``` -Because of **\#TYPE\#\_PARAMS\(IDENTITY, parma1...\) IDENTITY, ...**, **Identity** is **taskId \(0x0\)** and the first parameter is **oldPriority \(0x1f\)**. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->The number of parameters in **params** is specified by the **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** parameter. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** based on service requirements. - -Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**. + **Identity** is **taskId (0x0)**, and the first parameter is **oldPriority (0x1f)**. +> **NOTE**
+> The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. Set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements. +Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of task 0x0 is **0x0**. diff --git a/en/device-dev/kernel/kernel-small-apx-bitwise.md b/en/device-dev/kernel/kernel-small-apx-bitwise.md index a3760fc0c586a410de798654e2d4c3f75c2c39ce..7d2021ff322d40f8bccd7ad3cccb8742b0de1503 100644 --- a/en/device-dev/kernel/kernel-small-apx-bitwise.md +++ b/en/device-dev/kernel/kernel-small-apx-bitwise.md @@ -1,80 +1,42 @@ # Bitwise Operation - ## Basic Concepts -A bitwise operation operates on a binary number at the level of its individual bits. For example, a variable can be set as a program status word \(PSW\), and each bit \(flag bit\) in the PSW can have a self-defined meaning. - -## Available APIs - -The system provides operations for setting the flag bit to **1** or **0**, changing the flag bit content, and obtaining the most significant bit and least significant bit of the flag bit 1 in a PSW. You can also perform bitwise operations on system registers. The following table describes the APIs available for the bitwise operation module. For more details about the APIs, see the API reference. - -**Table 1** Bitwise operation module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Setting the flag bit to 1 or 0

-

LOS_BitmapSet

-

Sets a flag bit of a PSW to 1.

-

LOS_BitmapClr

-

Sets a flag bit of a PSW to 0.

-

Obtaining the bit whose flag bit is 1

-

LOS_HighBitGet

-

Obtains the most significant bit of 1 in the PSW.

-

LOS_LowBitGet

-

Obtains the least significant bit of 1 in the PSW.

-

Operating continuous bits

-

LOS_BitmapSetNBits

-

Sets the continuous flag bits of a PSW to 1.

-

LOS_BitmapClrNBits

-

Sets the continuous flag bits of a PSW to 0.

-

LOS_BitmapFfz

-

Obtains the first 0 bit starting from the least significant bit (LSB).

-
- -## Development Example - -### Example Description +A bitwise operation operates on the bits of a binary number. A variable can be set as a program status word (PSW), and each bit (flag bit) in the PSW can have a self-defined meaning. + + +## **Available APIs** + +The system provides operations for setting the flag bit to **1** or **0**, changing the flag bit content, and obtaining the most significant bit (MSB) and least significant bit (LSB) of the flag bit 1 in a PSW. You can also perform bitwise operations on system registers. The following table describes the APIs available for the bitwise operation module. For more details about the APIs, see the API reference. + + **Table 1** APIs of the bitwise operation module + +| Category | API Description | +| -------- | -------- | +| Setting a flag bit| - **LOS_BitmapSet**: sets a flag bit of a PSW to **1**.
- **LOS_BitmapClr**: sets a flag bit of a PSW to **0**. | +| Obtaining the bit whose flag bit is **1**| -**LOS_HighBitGet**: obtains the most significant bit of 1 in a PSW.
- **LOS_LowBitGet**: obtains the least significant bit of 1 in a PSW. | +| Operating continuous bits| - **LOS_BitmapSetNBits**: sets the consecutive flag bits of a PSW to **1**.
- **LOS_BitmapClrNBits**: sets the consecutive flag bits of a PSW to **0**.
- **LOS_BitmapFfz**: obtains the first 0 bit starting from the LSB. | + + +## Development Example + + +### Example Description This example implements the following: -1. Set a flag bit to **1**. -2. Obtain the most significant bit of flag bit 1. -3. Set a flag bit to **0**. -4. Obtain the least significant bit of the flag bit 1. +1. Set a flag bit to **1**. + +2. Obtain the MSB of flag bit 1. + +3. Set a flag bit to **0**. + +4. Obtain the LSB of flag bit 1. + +### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **BitSample** function is called in **TestTaskEntry**. ``` #include "los_bitmap.h" @@ -105,10 +67,12 @@ static UINT32 BitSample(VOID) } ``` + ### Verification The development is successful if the return result is as follows: + ``` Bitmap Sample! The flag is 0x10101010 @@ -117,4 +81,3 @@ LOS_HighBitGet:The highest one bit is 28, the flag is 0x10101110 LOS_BitmapClr: pos : 28, the flag is 0x00101110 LOS_LowBitGet: The lowest one bit is 4, the flag is 0x00101110 ``` - diff --git a/en/device-dev/kernel/kernel-small-apx-dll.md b/en/device-dev/kernel/kernel-small-apx-dll.md index e33e8e55d65e6a5e39fbb33e154557e2751148e9..1baa754b958dfbc5613eb7058e8ed4e24edfa376 100644 --- a/en/device-dev/kernel/kernel-small-apx-dll.md +++ b/en/device-dev/kernel/kernel-small-apx-dll.md @@ -8,19 +8,18 @@ A doubly linked list (DLL) is a linked data structure that consists of a set of ## Available APIs -The table below describes the DLL APIs. For more details about the APIs, see the API reference. - -| **Category**| **API**| -| -------- | -------- | -| Initializing a DLL| - **LOS_ListInit**: initializes a node as a DLL node.
- **LOS_DL_LIST_HEAD**: defines a node and initializes it as a DLL node.| -| Adding a node| - **LOS_ListAdd**: adds a node to the head of a DLL.
- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.
- **LOS_ListTailInsert**: inserts a node to the tail of a DLL.| -| Adding a DLL| - **LOS_ListAddList**: adds the head of a DLL to the head of this DLL.
- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.
- **LOS_ListTailInsertList**: Inserts the end of a DLL to the head of this DLL.| -| Deleting a node| - **LOS_ListDelete**: deletes a node from this DLL.
- **LOS_ListDelInit**: deletes a node from this DLL and uses this node to initialize the DLL.| -| Checking a DLL| - **LOS_ListEmpty**: checks whether a DLL is empty.
- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.
- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.| -| Obtains structure information.| - **LOS_OFF_SET_OF**: obtains the offset of a member in the specified structure relative to the start address of the structure.
- **LOS_DL_LIST_ENTRY**: obtains the address of the structure that contains the first node in the DLL. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.
- **LOS_ListPeekHeadType**: obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListRemoveHeadType**: obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListNextType**: obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL will be returned.| -| Traversing a DLL| - **LOS_DL_LIST_FOR_EACH**: traverses a DLL.
- **LOS_DL_LIST_FOR_EACH_SAFE**: traverses the DLL and stores the subsequent nodes of the current node for security verification.| -| Traversing the structure that contains the DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.
- **LOS_DL_LIST_FOR_EACH_ENTRY_SAFE**: traverses a DLL, obtains the address of the structure that contains the linked list node, and stores the address of the structure that contains the subsequent node of the current node.| - +The table below describes APIs available for the DLL. For more details about the APIs, see the API reference. + +| Category | API Description | +| ------------------------ | ------------------------------------------------------------ | +| Initializing a DLL | - **LOS_ListInit**: initializes a node as a DLL node.
- **LOS_DL_LIST_HEAD**: defines a node and initializes it as a DLL node.| +| Adding a node | - **LOS_ListAdd**: adds a node to the head of a DLL.
- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.
- **LOS_ListTailInsert**: inserts a node to the tail of a DLL.| +| Adding a DLL | - **LOS_ListAddList**: adds the head of a DLL to the head of this DLL.
- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.
- **LOS_ListTailInsertList**: inserts the end of a DLL to the head of this DLL.| +| Deleting a node | - **LOS_ListDelete**: deletes a node from this DLL.
- **LOS_ListDelInit**: deletes a node from this DLL and uses this node to initialize the DLL.| +| Checking a DLL | - **LOS_ListEmpty**: checks whether a DLL is empty.
- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.
- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.| +| Obtaining structure information | - **LOS_OFF_SET_OF**: obtains the offset of a member in the specified structure relative to the start address of the structure.
- **LOS_DL_LIST_ENTRY**: obtains the address of the structure that contains the first node in the DLL. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.
- **LOS_ListPeekHeadType**: obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListRemoveHeadType**: obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListNextType**: obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL will be returned.| +| Traversing a DLL | - **LOS_DL_LIST_FOR_EACH**: traverses a DLL.
- **LOS_DL_LIST_FOR_EACH_SAFE**: traverses the DLL and stores the subsequent nodes of the current node for security verification.| +| Traversing the structure that contains a DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.
- **LOS_DL_LIST_FOR_EACH_ENTRY_SAFE**: traverses a DLL, obtains the address of the structure that contains the linked list node, and stores the address of the structure that contains the subsequent node of the current node.| ## How to Develop @@ -30,7 +29,7 @@ The typical development process of the DLL is as follows: 2. Call **LOS_ListAdd** to add a node into the DLL. -3. Call **LOS_ListTailInsert** to insert a node to the tail of the DLL. +3. Call **LOS_ListTailInsert** to insert a node into the tail of the DLL. 4. Call **LOS_ListDelete** to delete the specified node. @@ -39,18 +38,19 @@ The typical development process of the DLL is as follows: 6. Call **LOS_ListDelInit** to delete the specified node and initialize the DLL based on the node. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> - Pay attention to the operations operations of the front and back pointer of the node. -> +> **NOTE**
+> +> - Pay attention to the operations before and after the node pointer. +> > - The DLL APIs are underlying interfaces and do not check whether the input parameters are empty. You must ensure that the input parameters are valid. -> +> > - If the memory of a linked list node is dynamically allocated, release the memory when deleting the node. - **Development Example** +## Development Example -**Example Description** +### Example Description This example implements the following: @@ -63,7 +63,11 @@ This example implements the following: 4. Check the operation result. +### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ListSample** function is called in **TestTaskEntry**. +The sample code is as follows: ``` #include "stdio.h" @@ -109,6 +113,8 @@ static UINT32 ListSample(VOID) The development is successful if the return result is as follows: + + ``` Initial head Add listNode1 success diff --git a/en/device-dev/kernel/kernel-small-apx-library.md b/en/device-dev/kernel/kernel-small-apx-library.md index c99d339880983a28403409a2caf157a20875c47b..dbbc0a9d9b872a5a0fe0a2c703c1d8783d05b59f 100644 --- a/en/device-dev/kernel/kernel-small-apx-library.md +++ b/en/device-dev/kernel/kernel-small-apx-library.md @@ -1,45 +1,49 @@ # Standard Library -The OpenHarmony kernel uses the musl libc library that supports the Portable Operating System Interface \(POSIX\). You can develop components and applications working on the kernel based on the POSIX. +The OpenHarmony kernel uses the musl libc library that supports the Portable Operating System Interface (POSIX). You can develop components and applications working on the kernel based on the POSIX. + ## Standard Library API Framework -**Figure 1** POSIX framework +**Figure 1** POSIX framework + ![](figures/posix-framework.png "posix-framework") The musl libc library supports POSIX standards. The OpenHarmony kernel adapts the related system call APIs to implement external functions. For details about the APIs supported by the standard library, see the API document of the C library, which also covers the differences between the standard library and the POSIX standard library. -## Development Example -In this example, the main thread creates **THREAD\_NUM** child threads. Once a child thread is started, it enters the standby state. After the main thread successfully wakes up all child threads, they continue to execute until the lifecycle ends. The main thread uses the **pthread\_join** method to wait until all child threads are executed. +### Development Example + + +#### Example Description + +In this example, the main thread creates THREAD_NUM child threads. Once a child thread is started, it enters the standby state. After the main thread successfully wakes up all child threads, they continue to execute until the lifecycle ends. The main thread uses the **pthread_join** method to wait until all child threads are executed. + +#### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExamplePosix** function is called in **TestTaskEntry**. + +The sample code is as follows: ``` #include #include #include -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif /* __cplusplus */ -#endif /* __cplusplus */ - #define THREAD_NUM 3 -int g_startNum = 0; /* Number of started threads */ -int g_wakenNum = 0; /* Number of wakeup threads */ +int g_startNum = 0; /* Number of threads to start */ +int g_wakenNum = 0; /* Number of threads to wake up */ struct testdata { pthread_mutex_t mutex; pthread_cond_t cond; } g_td; -/* - * Entry function of child threads. - */ -static void *ChildThreadFunc(void *arg) +/* Entry function of the child thread */ +static VOID *ChildThreadFunc(VOID *arg) { int rc; pthread_t self = pthread_self(); @@ -47,17 +51,17 @@ static void *ChildThreadFunc(void *arg) /* Acquire a mutex. */ rc = pthread_mutex_lock(&g_td.mutex); if (rc != 0) { - printf("ERROR:take mutex lock failed, error code is %d!\n", rc); + dprintf("ERROR:take mutex lock failed, error code is %d!\n", rc); goto EXIT; } /* The value of g_startNum is increased by 1. The value indicates the number of child threads that have acquired a mutex. */ g_startNum++; - /* Wait for the cond variable. */ + /* Wait for the cond variable. */ rc = pthread_cond_wait(&g_td.cond, &g_td.mutex); if (rc != 0) { - printf("ERROR: pthread condition wait failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition wait failed, error code is %d!\n", rc); (void)pthread_mutex_unlock(&g_td.mutex); goto EXIT; } @@ -65,52 +69,53 @@ static void *ChildThreadFunc(void *arg) /* Attempt to acquire a mutex, which is failed in normal cases. */ rc = pthread_mutex_trylock(&g_td.mutex); if (rc == 0) { - printf("ERROR: mutex gets an abnormal lock!\n"); + dprintf("ERROR: mutex gets an abnormal lock!\n"); goto EXIT; } /* The value of g_wakenNum is increased by 1. The value indicates the number of child threads that have been woken up by the cond variable. */ g_wakenNum++; - /* Unlock a mutex. */ + /* Release a mutex. */ rc = pthread_mutex_unlock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex release failed, error code is %d!\n", rc); + dprintf("ERROR: mutex release failed, error code is %d!\n", rc); goto EXIT; } EXIT: return NULL; } -static int testcase(void) +static int ExamplePosix(VOID) { int i, rc; pthread_t thread[THREAD_NUM]; - /* Initialize a mutex. */ + /* Initialize the mutex. */ rc = pthread_mutex_init(&g_td.mutex, NULL); if (rc != 0) { - printf("ERROR: mutex init failed, error code is %d!\n", rc); + dprintf("ERROR: mutex init failed, error code is %d!\n", rc); goto ERROROUT; } /* Initialize the cond variable. */ rc = pthread_cond_init(&g_td.cond, NULL); if (rc != 0) { - printf("ERROR: pthread condition init failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition init failed, error code is %d!\n", rc); goto ERROROUT; } - /* Create child threads in batches. The number is specified by THREAD_NUM. */ + /* Create child threads in batches. */ for (i = 0; i < THREAD_NUM; i++) { rc = pthread_create(&thread[i], NULL, ChildThreadFunc, NULL); if (rc != 0) { - printf("ERROR: pthread create failed, error code is %d!\n", rc); + dprintf("ERROR: pthread create failed, error code is %d!\n", rc); goto ERROROUT; } } + dprintf("pthread_create ok\n"); - /* Wait until all child threads lock a mutex. */ + /* Wait until all child threads obtain a mutex. */ while (g_startNum < THREAD_NUM) { usleep(100); } @@ -118,14 +123,14 @@ static int testcase(void) /* Acquire a mutex and block all threads using pthread_cond_wait. */ rc = pthread_mutex_lock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex lock failed, error code is %d\n", rc); + dprintf("ERROR: mutex lock failed, error code is %d\n", rc); goto ERROROUT; } - /* Release a mutex. */ + /* Release the mutex. */ rc = pthread_mutex_unlock(&g_td.mutex); if (rc != 0) { - printf("ERROR: mutex unlock failed, error code is %d!\n", rc); + dprintf("ERROR: mutex unlock failed, error code is %d!\n", rc); goto ERROROUT; } @@ -133,7 +138,7 @@ static int testcase(void) /* Broadcast signals on the cond variable. */ rc = pthread_cond_signal(&g_td.cond); if (rc != 0) { - printf("ERROR: pthread condition failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition failed, error code is %d!\n", rc); goto ERROROUT; } } @@ -142,73 +147,69 @@ static int testcase(void) /* Check whether all child threads are woken up. */ if (g_wakenNum != THREAD_NUM) { - printf("ERROR: not all threads awaken, only %d thread(s) awaken!\n", g_wakenNum); + dprintf("ERROR: not all threads awaken, only %d thread(s) awaken!\n", g_wakenNum); goto ERROROUT; } + dprintf("all threads awaked\n"); - /* Wait for all threads to terminate. */ + /* Join all child threads, that is, wait for the end of all child threads. */ for (i = 0; i < THREAD_NUM; i++) { rc = pthread_join(thread[i], NULL); if (rc != 0) { - printf("ERROR: pthread join failed, error code is %d!\n", rc); + dprintf("ERROR: pthread join failed, error code is %d!\n", rc); goto ERROROUT; } } + dprintf("all threads join ok\n"); /* Destroy the cond variable. */ rc = pthread_cond_destroy(&g_td.cond); if (rc != 0) { - printf("ERROR: pthread condition destroy failed, error code is %d!\n", rc); + dprintf("ERROR: pthread condition destroy failed, error code is %d!\n", rc); goto ERROROUT; } return 0; ERROROUT: return -1; } +``` -/* - * Main function - */ -int main(int argc, char *argv[]) -{ - int rc; +#### Verification - /* Start the test function. */ - rc = testcase(); - if (rc != 0) { - printf("ERROR: testcase failed!\n"); - } + The output is as follows: - return 0; -} -#ifdef __cplusplus -#if __cplusplus -} -#endif /* __cplusplus */ -#endif /* __cplusplus */ +``` +pthread_create ok +all threads awaked +all threads join ok ``` ## Differences from the Linux Standard Library -This section describes the key differences between the standard library carried by the OpenHarmony kernel and the Linux standard library. For more differences, see the API document of the C library. +The following describes the key differences between the standard library supported by the OpenHarmony kernel and the Linux standard library. For more differences, see the API document of the C library. + ### Process -1. The OpenHarmony user-mode processes support only static priorities, which range from 10 \(highest\) to 31 \(lowest\). -2. The OpenHarmony user-mode threads support only static priorities, which range from 0 \(highest\) to 31 \(lowest\). -3. The OpenHarmony process scheduling supports **SCHED\_RR** only, and thread scheduling supports **SCHED\_RR** or **SCHED\_FIFO**. +- The OpenHarmony user-mode processes support only static priorities, which range from 10 (highest) to 31 (lowest). + +- The OpenHarmony user-mode threads support only static priorities, which range from 0 (highest) to 31 (lowest). + +- The OpenHarmony process scheduling supports **SCHED_RR** only, and thread scheduling supports **SCHED_RR** or **SCHED_FIFO**. + ### Memory -**h2****Difference with Linux mmap** +**Differences from Linux mmap** + +mmap prototype: **void \*mmap (void \*addr, size_t length, int prot, int flags, int fd, off_t offset)** -mmap prototype: **void \*mmap \(void \*addr, size\_t length, int prot, int flags, int fd, off\_t offset\)** +The lifecycle implementation of **fd** is different from that of Linux glibc. glibc releases the **fd** handle immediately after successfully invoking **mmap** for mapping. In the OpenHarmony kernel, you are not allowed to close the **fd** immediately after the mapping is successful. You can close the **fd** only after **munmap** is called. If you do not close **fd**, the OS reclaims the **fd** when the process exits. -The lifecycle implementation of **fd** is different from that of Linux glibc. glibc releases the **fd** handle immediately after successfully invoking **mmap** for mapping. In the OpenHarmony kernel, you are not allowed to close the **fd** immediately after the mapping is successful. You can close the **fd** only after **munmap** is called. If you do not close **fd**, the OS reclaims the **fd** when the process exits. +**Example** -**h2****Sample Code** -Linux OS: +Linux: ``` int main(int argc, char *argv[]) @@ -226,13 +227,14 @@ int main(int argc, char *argv[]) perror("mmap"); exit(EXIT_FAILURE); } - close(fd); /* OpenHarmony does not support close fd immediately after the mapping is successful. */ + close(fd); /* OpenHarmony does not support closing fd immediately after the mapping is successful. */ ... exit(EXIT_SUCCESS); } ``` -OpenHarmony: + + OpenHarmony: ``` int main(int argc, char *argv[]) @@ -252,27 +254,32 @@ int main(int argc, char *argv[]) } ... munmap(addr, length); - close(fd); /* Close fd after the munmap is canceled. */ + close(fd); /* Close fd after the munmap is canceled. */ exit(EXIT_SUCCESS); } ``` + ### File System -**System directories**: You cannot modify system directories and device mount directories, which include **/dev**, **/proc**, **/app**, **/bin**, **/data**, **/etc**, **/lib**, **/system** and **/usr**. +System directories: You cannot modify system directories and device mount directories, which include **/dev**, **/proc**, **/app**, **/bin**, **/data**, **/etc**, **/lib**, **/system**, and **/usr**. -**User directory**: The user directory refers to the **/storage** directory. You can create, read, and write files in this directory, but cannot mount devices. +User directory: The user directory refers to the **/storage** directory. You can create, read, and write files in this directory, but cannot mount it to a device. + +Except in the system and user directories, you can create directories and mount them to devices. Note that nested mount is not allowed, that is, a mounted folder and its subfolders cannot be mounted repeatedly. A non-empty folder cannot be mounted. -Except in the system and user directories, you can create directories and mount devices. Note that nested mount is not allowed, that is, a mounted folder and its subfolders cannot be mounted repeatedly. A non-empty folder cannot be mounted. ### Signal -- The default behavior for signals does not include **STOP**, **CONTINUE**, or **COREDUMP**. -- A sleeping process \(for example, a process enters the sleeping status by calling the sleep function\) cannot be woken up by a signal. The signal mechanism does not support the wakeup function. The behavior for a signal can be processed only when the process is scheduled by the CPU. -- After a process exits, **SIGCHLD** is sent to the parent process. The sending action cannot be canceled. -- Only signals 1 to 30 are supported. The callback is executed only once even if the same signal is received multiple times. +- The default behavior for signals does not include **STOP**, **CONTINUE**, or **COREDUMP**. -### Time +- A sleeping process (for example, a process enters the sleeping status by calling the sleep function) cannot be woken up by a signal. The signal mechanism does not support the wakeup function. The behavior for a signal can be processed only when the process is scheduled by the CPU. -The OpenHarmony time precision is based on tick. The default value is 10 ms/tick. The time error of the **sleep** and **timeout** functions is less than or equal to 20 ms. +- After a process exits, **SIGCHLD** is sent to the parent process. The sending action cannot be canceled. + +- Only signals 1 to 30 are supported. The callback is invoked only once even if the same signal is received multiple times. + + +### Time +The default time precision of OpenHarmony is 10 ms/tick. The time error of the **sleep** and **timeout** functions is less than or equal to 20 ms. diff --git a/en/device-dev/kernel/kernel-small-basic-interrupt.md b/en/device-dev/kernel/kernel-small-basic-interrupt.md index b84a71b17ddd6c99f9278514a7c514bfc4bc5781..b22e5e78ff75cf72ec14352aa7a37129b4f4e9ee 100644 --- a/en/device-dev/kernel/kernel-small-basic-interrupt.md +++ b/en/device-dev/kernel/kernel-small-basic-interrupt.md @@ -1,132 +1,131 @@ # Interrupt and Exception Handling -## Basic Concepts +## Basic Concepts An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. An interrupt alerts the processor of a high-priority condition requiring interruption of the code being executed by the processor. In this way, the CPU does not need to spend a lot of time in waiting and querying the peripheral status, which effectively improves the real-time performance and execution efficiency of the system. -Exception handling involves a series of actions taken by the OS to respond to exceptions \(chip hardware faults\) that occurred during the OS running, for example, printing the call stack information of the current function, CPU information, and call stack information of tasks when the virtual memory page is missing. +OpenHarmony supports the following interrupt operations: -## Working Principles ++ Initializing an interrupt. ++ Creating an interrupt. ++ Enabling or disabling interrupts. ++ Restoring the system status before interrupts are disabled. ++ Deleting an interrupt. -Peripherals can complete certain work without the intervention of the CPU. In some cases, however, the CPU needs to perform certain work for peripherals. With the interrupt mechanism, the CPU responds to the interrupt request from a peripheral only when required, and execute other tasks when the peripherals do not require the CPU. The interrupt controller receives the input of other peripheral interrupt pins and sends interrupt signals to the CPU. You can enable or disable the interrupt source and set the priority and trigger mode of the interrupt source by programming the interrupt controller. Common interrupt controllers include vector interrupt controllers \(VICs\) and general interrupt controllers \(GICs\). The ARM Cortex-A7 uses GICs. After receiving an interrupt signal sent by the interrupt controller, the CPU interrupts the current task to respond to the interrupt request. +Exception handling involves a series of actions taken by the OS to respond to exceptions (chip hardware faults) that occurred during the OS running, for example, printing the call stack information of the current function, CPU information, and call stack information of tasks when the virtual memory page is missing. -Exception handling interrupts the normal running process of the CPU to handle exceptions, such as, undefined instructions, an attempt to modify read-only data, and unaligned address access. When an exception occurs, the CPU suspends the current program, handles the exception, and then continues to execute the program interrupted by the exception. + +## Working Principles + +Peripherals can complete certain work without the intervention of the CPU. In some cases, however, the CPU needs to perform certain work for peripherals. With the interrupt mechanism, the CPU responds to the interrupt request from a peripheral only when required, and execute other tasks when the peripherals do not require the CPU. + +The interrupt controller receives the input from the interrupt pins of other peripherals and sends interrupt signals to the CPU. You can enable or disable the interrupt source and set the priority and trigger mode of the interrupt source by programming the interrupt controller. Common interrupt controllers include vector interrupt controllers (VICs) and general interrupt controllers (GICs). The ARM Cortex-A7 uses GICs. + +After receiving an interrupt signal sent by the interrupt controller, the CPU interrupts the current task to respond to the interrupt request. + +An exception interrupts the normal running process of the CPU to handle exceptions, such as, undefined instructions, an attempt to modify read-only data, and unaligned address access. When an exception occurs, the CPU suspends the current program, handles the exception, and then continues to execute the program interrupted by the exception. The following uses the ARMv7-a architecture as an example. The interrupt vector table is the entry for interrupt and exception handling. The interrupt vector table contains the entry function for each interrupt and exception handling. -**Figure 1** Interrupt vector table +**Figure 1** Interrupt vector table + ![](figures/interrupt-vector-table.png "interrupt-vector-table") -## Development Guidelines - -### Available APIs - -Exception handling is an internal mechanism and does not provide external APIs. The following table describes APIs available for the interrupt module. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting interrupts

-

LOS_HwiCreate

-

Creates an interrupt and registers the interrupt ID, interrupt triggering mode, interrupt priority, and interrupt handler. When an interrupt is triggered, the interrupt handler will be called.

-

LOS_HwiDelete

-

Deletes an interrupt.

-

Enabling and disabling all interrupts

-

LOS_IntUnLock

-

Enables all interrupts of the current processor.

-

LOS_IntLock

-

Disables all interrupts for the current processor.

-

LOS_IntRestore

-

Restores to the status before all interrupts are disabled by using LOS_IntLock.

-

Obtaining the maximum number of interrupts supported

-

LOS_GetSystemHwiMaximum

-

Obtains the maximum number of interrupts supported by the system.

-
- -### How to Develop - -1. Call **LOS\_HwiCreate** to create an interrupt. -2. Call **LOS\_HwiDelete** to delete the specified interrupt. Use this API based on actual requirements. - -### Development Example + +## Development Guidelines + + +### Available APIs + +Exception handling is an internal mechanism and does not provide external APIs. The following tables describe the APIs available for the interrupt module. + +##### Creating or Deleting an Interrupt + +| API | Description | +|------------ | ----------------------------------------------------------- | +| LOS_HwiCreate | Creates an interrupt and registers the interrupt ID, triggering mode, priority, and interrupt handler. When the interrupt is triggered, the interrupt handler will be called.| +| LOS_HwiDelete | Deletes an interrupt based on the interrupt number. | + +##### Enabling or Disabling Interrupts + +| API | Description | +| -------------- | ------------------------------------------- | +| LOS_IntUnlock | Enables all interrupts for the current processor. | +| LOS_IntLock | Disables all interrupts for the current processor. | +| LOS_IntRestore | Restores the status in which the system was before **LOS_IntLock** is called.| + +##### Obtaining Interrupt Information + +| API | Description | +| ----------------------- | ------------------------ | +| LOS_GetSystemHwiMaximum | Obtains the maximum number of interrupts supported by the system.| + + + +### How to Develop + +1. Call **LOS_HwiCreate** to create an interrupt. + +2. Call **LOS_HwiDelete** to delete the specified interrupt. Use this API based on actual requirements. + + +### Development Example + This example implements the following: -1. Create an interrupt. -2. Delete an interrupt. -The following sample code shows how to create and delete an interrupt. When the interrupt **HWI\_NUM\_TEST** is generated, the interrupt handler function will be called. +1. Create an interrupt. -``` +2. Delete an interrupt. + +The following sample code demostrates how to create and delete an interrupt, and call the interrupt handler when the specified interrupt **HWI_NUM_TEST** is triggered. You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src/osTest.c** for testing. + +The sample code is as follows: + +```c #include "los_hwi.h" /* Interrupt handler function*/ STATIC VOID HwiUsrIrq(VOID) { - printf("in the func HwiUsrIrq \n"); + PRINTK("in the func HwiUsrIrq \n"); } static UINT32 Example_Interrupt(VOID) { UINT32 ret; - HWI_HANDLE_T hwiNum = 7; - HWI_PRIOR_T hwiPrio = 3; + HWI_HANDLE_T hwiNum = 7; // The interrupt number is 7. + HWI_PRIOR_T hwiPrio = 3; // The interrupt priority is 3. HWI_MODE_T mode = 0; HWI_ARG_T arg = 0; -/* Create an interrupt.*/ + /* Create an interrupt. */ ret = LOS_HwiCreate(hwiNum, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, (HwiIrqParam *)arg); - if(ret == LOS_OK){ - printf("Hwi create success!\n"); + if (ret == LOS_OK) { + PRINTK("Hwi create success!\n"); } else { - printf("Hwi create failed!\n"); + PRINTK("Hwi create failed!\n"); return LOS_NOK; } - /* Delay 50 ticks. When a hardware interrupt occurs, call the HwiUsrIrq function.*/ + /* Delay 50 ticks. Call HwiUsrIrq when a hardware interrupt occurs. */ LOS_TaskDelay(50); - /* Delete an interrupt./ - ret = LOS_HwiDelete(hwiNum, (HwiIrqParam *)arg); - if(ret == LOS_OK){ - printf("Hwi delete success!\n"); + /* Delete the interrupt. */ + ret = LOS_HwiDelete(hwiNum, (HwiIrqParam *)arg); + if (ret == LOS_OK) { + PRINTK("Hwi delete success!\n"); } else { - printf("Hwi delete failed!\n"); + PRINTK("Hwi delete failed!\n"); return LOS_NOK; } return LOS_OK; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: @@ -134,4 +133,3 @@ The development is successful if the return result is as follows: Hwi create success! Hwi delete success! ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-process-process.md b/en/device-dev/kernel/kernel-small-basic-process-process.md index 413951926be6282146304660a198bc0546014067..33847a3d95060948d7737a5ed8cbff9a5c76b7cc 100644 --- a/en/device-dev/kernel/kernel-small-basic-process-process.md +++ b/en/device-dev/kernel/kernel-small-basic-process-process.md @@ -1,64 +1,66 @@ # Process -## Basic Concepts +## Basic Concepts -A process is the minimum unit for system resource management. The process module provided by the OpenHarmony LiteOS-A kernel is used to isolate user-mode processes. The kernel mode is considered as a process space and does not have other processes except KIdle, which is an idle process provided by the system and shares the same process space with KProcess. +A process is the minimum unit for system resource management. The process module provided by the OpenHarmony LiteOS-A kernel isolates user-mode processes. The kernel mode is considered as a process space and does not have other processes except KIdle, which is an idle process provided by the system and shares the same process space with KProcess. KProcess is the root process of kernel-mode processes, and KIdle is its child process. -- The process module provides multiple processes for users and implements switching and communication between processes, facilitating your management over service programs. -- The processes use the preemption scheduling mechanism. The processes with a higher priority are scheduled first, and the processes with the same priority are scheduled using the time slice polling. -- The processes are assigned 32 priorities \(**0** to **31**\). Among them, user processes can be configured with 22 priorities from **10** \(highest\) to **31** \(lowest\). -- A higher-priority process can preempt the resources of a lower-priority process. The lower-priority process can be scheduled only after the higher-priority process is blocked or terminated. -- Each user-mode process has its own memory space, which is invisible to other processes. In this way, processes are isolated from each other. -- The user-mode root process **init** is created by the kernel. Other user-mode processes are created by the **init** process via the **fork** call. +- The process module provides multiple processes for users and implements switching and communication between processes, facilitating your management over service programs. -**Process States:** +- The processes use the preemption scheduling mechanism. The processes with a higher priority are scheduled first, and the processes with the same priority are scheduled using the time slice round robin. -- Init: The process is being created. +- The processes are assigned 32 priorities (**0** to **31**). Among them, user processes can be configured with 22 priorities from **10** (highest) to **31** (lowest). -- Ready: The process is in the Ready queue and waits for scheduling by the CPU. -- Running: The process is running. -- Pending: The process is blocked and suspended. When all threads in a process are blocked, the process is blocked and suspended. -- Zombies: The process stops running and waits for the parent process to reclaim its control block resources. +- A higher-priority process can preempt the resources of a lower-priority process. The lower-priority process can be scheduled only after the higher-priority process is blocked or terminated. -**Figure 1** Process state transition -![](figures/process-state-transition.png "process-state-transition") +- Each user-mode process has its own memory space, which is invisible to other processes. In this way, processes are isolated from each other. -**Process State Transition:** +- The user-mode root process **init** is created by the kernel. Other user-mode processes are created by the **init** process via the **fork** call. -- Init→Ready: +**Process States** - When a process is created, the process enters the Init state after obtaining the process control block to start initialization. After the process is initialized, the process is inserted into the scheduling queue and therefore enters the Ready state. +- Init: The process is being created. -- Ready→Running: +- Ready: The process is in the Ready queue and waits for scheduling by the CPU. - When a process switchover is triggered, the process with the highest priority in the Ready queue is executed and enters the Running state. If this process has no thread in the Ready state, the process is deleted from the Ready queue and resides only in the Running state. If it has threads in the Ready state, the process still stays in the Ready queue. In this case, the process is in both the Ready and Running states, but presented as the Running state. +- Running: The process is running. -- Running→Pending: +- Pending: The process is blocked and suspended. When all threads in a process are blocked, the process is blocked and suspended. - When the last thread of a process enters the Pending state, all threads in the process are in the Pending state. Then, the process enters the Pending state, and process switching occurs. +- Zombies: The process stops running and waits for the parent process to reclaim its control block resources. -- Pending→Ready: + **Figure 1** Process state transition - When any thread in a Pending process restores to the Ready state, the process is added to the Ready queue and changes to the Ready state. + ![](figures/process-state-transition.png "process-state-transition") -- Ready→Pending: +**Process State Transition** - When the last ready thread in a process enters the Pending state, the process is deleted from the Ready queue, and the process changes from the Ready state to the Pending state. +- Init→Ready: + When a process is created or forked, the process enters the Init state after obtaining the process control block. When the process initialization is complete, the process is added to the scheduling queue, and the process enters the Ready state. -- Running→Ready: +- Ready→Running: + When process switching occurs, the process that has the highest priority and time slice in the Ready queue is executed and enters the Running state. If this process has no thread in the Ready state, the process is deleted from the Ready queue and resides only in the Running state. If it has threads in the Ready state, the process still stays in the Ready queue. In this case, the process is in both the Ready and Running states, but presented as the Running state. - A process may change from the Running state to the Ready state in either of the following scenarios: +- Running→Pending: + When the last thread of a process enters the Pending state, all threads in the process are in the Pending state. Then, the process enters the Pending state, and process switching occurs. - 1. After a process with a higher priority is created or restored, processes will be scheduled. The process with the highest priority in the Ready queue will change to the Running state, and the originally running process will change from the Running state to the Ready state. - 2. If scheduling policy for a process is **LOS\_SCHED\_RR** and its priority is the same as that of another process in the Ready state, this process will change from the Running state to the Ready state after its time slices are used up, and the other process with the same priority will change from the Ready state to the Running state. +- Pending→Ready: + When any thread in a Pending process restores to the Ready state, the process is added to the Ready queue and changes to the Ready state. -- Running→Zombies: +- Ready→Pending: + When the last ready thread in a process enters the Pending state, the process is deleted from the Ready queue, and the process changes from the Ready state to the Pending state. - After the main thread or all threads of a process are stopped, the process changes from the **Running** state to the **Zombies** state and waits for the parent process to reclaim resources. +- Running→Ready: + A process may change from the Running state to the Ready state in either of the following scenarios: + 1. After a process with a higher priority is created or restored, processes will be scheduled. The process with the highest priority in the Ready queue will change to the Running state, and the originally running process will change from the Running state to the Ready state. + 2. If scheduling policy for a process is **LOS_SCHED_RR** (time slice round robin) and its priority is the same as that of another process in the Ready state, this process will change from the Running state to the Ready state after its time slices are used up, and the other process with the same priority will change from the Ready state to the Running state. -## Working Principles +- Running→Zombies: + After the main thread or all threads of a process are stopped, the process changes from the **Running** state to the **Zombies** state and waits for the parent process to reclaim resources. + + +## Working Principles The OpenHarmony process module is used to isolate user-mode processes and supports the following functions: creating and exiting user-mode processes, reclaiming process resources, setting and obtaining scheduling parameters and process group IDs, and obtaining process IDs. @@ -66,105 +68,65 @@ A user-mode process is created by forking a parent process. During forking, the A process is only a resource management unit, and the actual running is executed by threads in the process. When switching occurs between threads in different processes, the process space will be switched. -**Figure 2** Process management +**Figure 2** Process management + ![](figures/process-management.png "process-management") -## Development Guidelines - -### Available APIs - -**Table 1** Process management module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Process scheduling parameter control

-

LOS_GetProcessScheduler

-

Obtains the scheduling policy of the specified process.

-

LOS_SetProcessScheduler

-

Sets the scheduling parameters, including the priority and scheduling policy, for the specified process.

-

LOS_GetProcessPriority

-

Obtains the priority of the specified process.

-

LOS_SetProcessPriority

-

Sets the priority of the specified process.

-

Waiting for reclaiming child processes

-

LOS_Wait

-

Waits for the specified child process to terminate, and reclaims its resources.

-

Process group

-

LOS_GetProcessGroupID

-

Obtains the process group ID of the specified process.

-

LOS_GetCurrProcessGroupID

-

Obtains the process group ID of the current process.

-

Obtaining the process ID.

-

LOS_GetCurrProcessID

-

Obtains the ID of the current process.

-

User and user group

-

LOS_GetUserID

-

Obtains the user ID of the current process.

-

LOS_GetGroupID

-

Obtains the user group ID of the current process.

-

LOS_CheckInGroups

-

Checks whether the specified user group ID is in the user group of the current process.

-

Maximum number of processes supported

-

LOS_GetSystemProcessMaximum

-

Obtains the maximum number of processes supported by the system.

-
- -### How to Develop -Kernel-mode processes cannot be created. Therefore, kernel-mode process development is not involved. +## Development Guidelines + + +### Available APIs + +**Table 1** APIs for processes and process groups + +| API | Description | +| ------------------------- | ---------------------- | +| LOS_GetCurrProcessID | Obtains the ID of the current process. | +| LOS_GetProcessGroupID | Obtains the process group ID of the specified process.| +| LOS_GetCurrProcessGroupID | Obtains the process group ID of the current process.| + +**Table 2** APIs for users and user groups + +| API | Description | +| ----------------- | ---------------------------------------- | +| LOS_GetUserID | Obtains the user ID of the current process. | +| LOS_GetGroupID | Obtains the user group ID of the current process. | +| LOS_CheckInGroups | Checks whether the specified user group ID is in the user group of the current process.| ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- The number of idle threads depends on the number of CPU cores. Each CPU has a corresponding idle thread. ->- Except KProcess and KIdle, other kernel-mode processes cannot be created. ->- If a thread is created after a user-mode process enters the kernel mode by a system call, the thread belongs to a KProcess not a user-mode process. +**Table 3** APIs for process scheduling + +| API | API | +| ----------------------- | -------------------------------------------- | +| LOS_GetProcessScheduler | Obtains the scheduling policy of a process. | +| LOS_SetProcessScheduler | Sets scheduling parameters, including the priority and scheduling policy, for a process.| +| LOS_SetProcessPriority | Sets the process priority. | +| LOS_GetProcessPriority | Obtains the priority of a process. | + +**Table 4** APIs for obtaining system process information + +| API | Description | +| --------------------------- | -------------------------- | +| LOS_GetSystemProcessMaximum | Obtains the maximum number of processes supported by the system.| +| LOS_GetUsedPIDList | Obtains a list of used process IDs. | + +**Table 5** APIs for managing processes + +| API | Description | +| ---------- | -------------------------- | +| LOS_Fork | Creates a child process. | +| LOS_Wait | Waits for the child process to terminate, and reclaims its resources.| +| LOS_Waitid | Wait for the specified process to terminate. | +| LOS_Exit | Exits a process. | + + + +### How to Develop + +Kernel-mode processes cannot be created. Therefore, kernel-mode process development is not involved. +> **NOTE** +> +> - The number of idle threads depends on the number of CPU cores. Each CPU has a corresponding idle thread. +>- Except KProcess and KIdle, other kernel-mode processes cannot be created. +> - If a thread is created after a user-mode process enters the kernel mode by a system call, the thread belongs to a KProcess not a user-mode process. diff --git a/en/device-dev/kernel/kernel-small-basic-process-scheduler.md b/en/device-dev/kernel/kernel-small-basic-process-scheduler.md index fdd199036e7bcb51cbdd57e52bdce0b273fec998..8af7150bd3ced5e5c914edf340f79ec238246cca 100644 --- a/en/device-dev/kernel/kernel-small-basic-process-scheduler.md +++ b/en/device-dev/kernel/kernel-small-basic-process-scheduler.md @@ -1,53 +1,48 @@ # Scheduler -## Basic Concepts +## Basic Concepts The OpenHarmony LiteOS-A kernel uses the preemptive scheduling mechanism for tasks. The tasks with a higher priority are scheduled first, and the tasks with the same priority are scheduled using the time slice polling. The system runs based on the real-time timeline from the startup, which ensures good real-time performance of the scheduling algorithm. The OpenHarmony scheduling algorithm is embedded with the tickless mechanism, which ensures lower power consumption and on-demand response to tick interrupts. This minimizes useless tick interrupt response time and further improves the real-time performance of the system. -The OpenHarmony process scheduling policy is **SCHED\_RR**, and the thread scheduling policy can be **SCHED\_RR** or **SCHED\_FIFO**. +OpenHarmony supports **SCHED_RR** (time slice round robin) for process scheduling and **SCHED_RR** and **SCHED_FIFO** (first in, first out) for thread scheduling . -Threads are the minimum scheduling units in the OpenHarmony. +Threads are the minimum scheduling units in OpenHarmony. -## Working Principles -The OpenHarmony uses process priority queue and thread priority queue for scheduling. The process priority ranges from 0 to 31, and there are 32 process priority bucket queues. Each bucket queue corresponds to a thread priority bucket queue. The thread priority ranges from 0 to 31, and a thread priority bucket queue also has 32 priority queues. +## Working Principles + +OpenHarmony uses process priority queue and thread priority queue for scheduling. The process priority ranges from 0 to 31, and there are 32 process priority bucket queues. Each bucket queue corresponds to a thread priority bucket queue. The thread priority ranges from 0 to 31, and a thread priority bucket queue also has 32 priority queues. + +**Figure 1** Scheduling priority bucket queue -**Figure 1** Scheduling priority bucket queue ![](figures/scheduling-priority-bucket-queue.png "scheduling-priority-bucket-queue") The OpenHarmony system starts scheduling after the kernel initialization is complete. The processes or threads created during running are added to the scheduling queues. The system selects the optimal thread for scheduling based on the priorities of the processes and threads and the time slice consumption of the threads. Once a thread is scheduled, it is deleted from the scheduling queue. If a thread is blocked during running, the thread is added to the corresponding blocking queue and triggers scheduling of another thread. If no thread in the scheduling queue can be scheduled, the system selects the thread of the KIdle process for scheduling. -**Figure 2** Scheduling process +**Figure 2** Scheduling process + ![](figures/scheduling-process.png "scheduling-process") -## Development Guidelines - -### Available APIs - - - - - - - - - - - - -

Function

-

API

-

Description

-

System scheduling

-

LOS_Schedule

-

Triggers system scheduling.

-
- -### How to Develop - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->Scheduling cannot be triggered during the system initialization process. +## Development Guidelines + + +### Available APIs + +| API| Description| +| -------- | -------- | +| LOS_Schedule | Triggers system scheduling.| +| LOS_GetTaskScheduler | Obtains the scheduling policy of a task.| +| LOS_SetTaskScheduler | Sets the scheduling policy for a task.| +| LOS_GetProcessScheduler | Obtains the scheduling policy of a process.| +| LOS_SetProcessScheduler | Sets scheduling parameters, including the priority and scheduling policy, for a process.| + + +### How to Develop + +> **NOTE** +> +> Scheduling cannot be triggered during the system initialization process. diff --git a/en/device-dev/kernel/kernel-small-basic-process-thread.md b/en/device-dev/kernel/kernel-small-basic-process-thread.md index 5631cf62fb43f48d26b5016ac96534e24bdd7f37..96a97e237f8799864e5b9bd4bf01337ab334df56 100644 --- a/en/device-dev/kernel/kernel-small-basic-process-thread.md +++ b/en/device-dev/kernel/kernel-small-basic-process-thread.md @@ -1,315 +1,244 @@ # Task -## Basic Concepts + +## Basic Concepts Tasks are the minimum running units that compete for system resources. They can use or wait to use CPUs and use system resources such as memory. They run independently from one another. In the OpenHarmony kernel, a task represents a thread. -Tasks in the processes of the same priority in the OpenHarmony kernel are scheduled and run in a unified manner. +Tasks for the processes of the same priority in the OpenHarmony kernel are scheduled and run in a unified manner. -The tasks in the kernel use the preemptive scheduling mechanism, either round-robin \(RR\) scheduling or First In First Out \(FIFO\) scheduling. +The tasks in the kernel use the preemptive scheduling mechanism, either round-robin (RR) scheduling or First In First Out (FIFO) scheduling. -Tasks are assigned 32 priorities, ranging from **0** \(highest\) to **31** \(lowest\). +Tasks are assigned 32 priorities, ranging from **0** (highest) to **31** (lowest). In the same process, a higher-priority task can preempt resources of a lower-priority task. The lower-priority task can be scheduled only after the higher-priority task is blocked or terminated. -**Task Status Description** +**Task States** + +- Init: The task is being created. + +- Ready: The task is in the Ready queue and waits for scheduling by the CPU. + +- Running: The task is running. + +- Blocked: The task is blocked and suspended. The Blocked states include pending (blocked due to lock, event, or semaphore issues), suspended (active pending), delay (blocked due to delays), and pendtime (blocked by waiting timeout of locks, events, or semaphores). + +- Exit: The task is complete and waits for the parent task to reclaim its control block resources. -- Init: The task is being created. -- Ready: The task is in the Ready queue and waits for scheduling by the CPU. -- Running: The task is running. -- Blocked: The task is blocked and suspended. The Blocked states include pending \(blocked due to lock, event, or semaphore issues\), suspended \(active pending\), delay \(blocked due to delays\), and pendtime \(blocked by waiting timeout of locks, events, or semaphores\). -- Exit: The task is complete and waits for the parent task to reclaim its control block resources. + **Figure 1** Task state transition -**Figure 1** Task state transition -![](figures/task-state-transition.png "task-state-transition") + ![](figures/task-state-transition.png "task-state-transition") **Task State Transition** -- Init→Ready: +- Init→Ready: + When a task is created, the task obtains the control block and enters the Init state (initialization). After the initialization is complete, the task is inserted into the scheduling queue and enters the Ready state. - When a task is created, the task obtains the control block and enters the Init state \(initialization\). After the initialization is complete, the task is inserted into the scheduling queue and enters the Ready state. +- Ready→Running: + When a task switching is triggered, the task with the highest priority in the Ready queue is executed and enters the Running state. Then, this task is deleted from the Ready queue. -- Ready→Running: +- Running→Blocked: + When a running task is blocked (for example, is pended, delayed, or reading semaphores), its state changes from Running to Blocked. Then, a task switching is triggered to run the task with the highest priority in the Ready queue. - When a task switching is triggered, the task with the highest priority in the Ready queue is executed and enters the Running state. Then, this task is deleted from the Ready queue. +- Blocked→Ready: + After the blocked task is restored (the task is restored, the delay times out, the semaphore reading times out, or the semaphore is read), the task is added to the Ready queue and will change from the Blocked state to the Ready state. -- Running→Blocked: +- Ready→Blocked: + When a task in the Ready state is blocked (suspended), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered. - When a running task is blocked \(for example, is pended, delayed, or reading semaphores\), its state changes from Running to Blocked. Then, a task switching is triggered to run the task with the highest priority in the Ready queue. +- Running→Ready: + When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and is added to the Ready queue. -- Blocked→Ready: +- Running→Exit: + When a running task is complete, it changes to the Exit state. If the task has a detach attribute (set by **LOS_TASK_STATUS_DETACHED** in **los_task.h**), it will be destroyed directly. - After the blocked task is restored \(the task is restored, the delay times out, the semaphore reading times out, or the semaphore is read\), the task is added to the Ready queue and will change from the Blocked state to the Ready state. -- Ready→Blocked: +## Working Principles - When a task in the Ready state is blocked \(suspended\), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered. +The OpenHarmony task management module provides the following functions: creating, delaying, suspending, and restoring tasks, locking and unlocking task scheduling, and querying task control block information by ID. -- Running→Ready: +When a user creates a task, the system initializes the task stack and presets the context. The system places the task entry function in the corresponding position so that the function can be executed when the task enters the running state for the first time. - When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and is added to the Ready queue. -- Running→Exit: +## Development Guidelines - When a running task is complete, it changes to the Exit state. If the task is set with a detach attribute \(**LOS\_TASK\_STATUS\_DETACHED**\), it will be directly destroyed after being terminated. +### Available APIs -## Working Principles +**Table 1** APIs for creating and deleting a task -The OpenHarmony task management module provides the following functions: creating, delaying, suspending, and restoring tasks, locking and unlocking task scheduling, and querying task control block information by ID. +| API | Description | +| ------------------ | ------------------------------------------------------------ | +| LOS_TaskCreate | Creates a task. If the priority of the created task is higher than that of the task in running and task scheduling is not locked, the task will be scheduled to run. | +| LOS_TaskCreateOnly | Creates a task and blocks it. The task will not be added to the Ready queue unless it is resumed. | +| LOS_TaskDelete | Deletes a task and reclaims the resources consumed by the task control block and task stack. | + +**Table 2** APIs for controlling task status + +| API | Description | +| --------------- | ------------------------------------------------------------ | +| LOS_TaskResume | Resumes a suspended task. | +| LOS_TaskSuspend | Suspends a task. The suspended task will be removed from the Ready queue. | +| LOS_TaskJoin | Blocks the current task until the specified task is complete, and reclaims its resources. | +| LOS_TaskDetach | Changes the task attribute from **joinable** to **detach**. When a task of the **detach** attribute is complete, the task control block resources will be automatically reclaimed.| +| LOS_TaskDelay | Delays the current task for the specified time (number of ticks). | +| LOS_TaskYield | Moves the current task from the queue of the tasks with the same priority to the end of the Ready queue.| + +**Table 3** APIs for task scheduling -When a task is created, the system initializes the task stack and presets the context. The system also places the task entry function in the corresponding position so that the function can be executed when the task enters the running state for the first time. - -## Development Guidelines - -### Available APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Task creation and deletion

-

LOS_TaskCreateOnly

-

Creates a task and places the task in the Init state without scheduling.

-

LOS_TaskCreate

-

Creates a task and places it in the Init state for scheduling.

-

LOS_TaskDelete

-

Deletes the specified task.

-

Task status control

-

LOS_TaskResume

-

Resumes a suspended task.

-

LOS_TaskSuspend

-

Suspends the specified task.

-

LOS_TaskJoin

-

Suspends this task till the specified task is complete and the task control block resources are reclaimed.

-

LOS_TaskDetach

-

Changes the task attribute from joinable to detach. After the task of the detach attribute is complete, the task control block resources will be automatically reclaimed.

-

LOS_TaskDelay

-

Delays a task.

-

LOS_TaskYield

-

Adjusts the scheduling sequence of tasks that call the task priority.

-

Task scheduling control

-

LOS_TaskLock

-

Locks task scheduling.

-

LOS_TaskUnlock

-

Unlocks task scheduling.

-

Task priority control

-

LOS_CurTaskPriSet

-

Sets the priority for the current task.

-

LOS_TaskPriSet

-

Sets the priority for a specified task.

-

LOS_TaskPriGet

-

Obtains the priority of a specified task.

-

Obtaining task information

-

LOS_CurTaskIDGet

-

Obtains the ID of the current task.

-

LOS_TaskInfoGet

-

Obtains information about the specified task.

-

Binding tasks to CPU cores

-

LOS_TaskCpuAffiSet

-

Binds a specified task to the specified CPU. It is used only in multi-core scenarios.

-

LOS_TaskCpuAffiGet

-

Obtains the core binding information of the specified task. It is used only in multi-core scenarios.

-

Task scheduling parameter control

-

LOS_GetTaskScheduler

-

Obtains the scheduling policy of the specified task.

-

LOS_SetTaskScheduler

-

Sets the scheduling parameters, including the priority and scheduling policy, for the specified task.

-

Maximum number of tasks supported

-

LOS_GetSystemTaskMaximum

-

Obtains the maximum number of tasks supported by the system.

-
- -### How to Develop +| API | Description | +| -------------------- | ------------------------------------------------------------ | +| LOS_TaskLock | Locks task scheduling to prevent task switching. | +| LOS_TaskUnlock | Unlocks task scheduling. After that, the task lock count decrements by 1. If a task is locked multiple times, the task can be scheduled only when the number of locks is reduced to 0. | +| LOS_GetTaskScheduler | Obtains the scheduling policy of a task. | +| LOS_SetTaskScheduler | Sets the scheduling parameters, including the priority and scheduling policy, for a task. | +| LOS_Schedule | Triggers active task scheduling. | + +**Table 4** APIs for obtaining task information + +| API | Description | +| ------------------------ | ------------------------ | +| LOS_CurTaskIDGet | Obtains the ID of the current task. | +| LOS_TaskInfoGet | Obtains task information. | +| LOS_GetSystemTaskMaximum | Obtains the maximum number of tasks supported by the system.| + +**Table 5** APIs for managing task priorities + +| API | Description | +| ----------------- | ------------------------------ | +| LOS_CurTaskPriSet | Sets a priority for the current task.| +| LOS_TaskPriSet | Sets a priority for a task. | +| LOS_TaskPriGet | Obtains the priority of a task. | + +**Table 6** APIs for setting CPU pinning + +| API | Description | +| ------------------ | ------------------------------------------- | +| LOS_TaskCpuAffiSet | Binds a task to the specified CPU core. This API is used only in multi-core CPUs.| +| LOS_TaskCpuAffiGet | Obtains information about the core binding of a task. This API is used only in multi-core CPUs. | + + + +### How to Develop The typical task development process is as follows: -1. Call **LOS\_TaskCreate** to create a task. - - Specify the execution entry function for the task. - - Specifies the task name. - - Specify the task stack size. - - Specify the priority of the task. - - Specify the task attribute, which can be **LOS\_TASK\_ATTR\_JOINABLE** or **LOS\_TASK\_STATUS\_DETACHED**. - - Specify the task-core binding attribute for multi-core environment. +1. Call **LOS_TaskCreate** to create a task. + - Specify the execution entry function for the task. + - Specifies the task name. + - Specify the task stack size. + - Specify the priority of the task. + - Specify the task attribute, which can be **LOS_TASK_ATTR_JOINABLE** or **LOS_TASK_STATUS_DETACHED**. + - Specify the task-core binding attribute for multi-core environment. -2. Run the service code to implement task scheduling. -3. Reclaim resources when the task is complete. If the task attribute is **LOS\_TASK\_STATUS\_DETACHED**, the task resources are automatically reclaimed. If the task attribute is **LOS\_TASK\_ATTR\_JOINABLE**, call **LOS\_TaskJoin** to reclaim task resources. The default task attribute is **LOS\_TASK\_STATUS\_DETACHED**. +2. Run the service code to implement task scheduling. ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- The kernel mode has the highest permission and can operate tasks in any process. ->- If a task is created after a user-mode process enters the kernel mode by a system call, the task belongs to a KProcess not a user-mode process. +3. Reclaim resources when the task is complete. If the task attribute is **LOS_TASK_STATUS_DETACHED**, the task resources are automatically reclaimed. If the task attribute is **LOS_TASK_ATTR_JOINABLE**, call **LOS_TaskJoin** to reclaim task resources. The default task attribute is **LOS_TASK_STATUS_DETACHED**. -### Development Example +> **NOTE** +> +> - The kernel mode has the highest permission and can operate tasks in any process. +> +> - If a task is created after a user-mode process enters the kernel mode by a system call, the task belongs to a KProcess not a user-mode process. -The sample code is as follows: -``` +### Development Example + +The sample code is as follows. You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src /osTest.c** for testing + + +```c UINT32 g_taskLoID; -UINT32 g_taskHiID; -#define TSK_PRIOR_HI 4 -#define TSK_PRIOR_LO 5 -UINT32 ExampleTaskHi(VOID) -{ +UINT32 g_taskHiID; +#define TSK_PRIOR_HI 4 +#define TSK_PRIOR_LO 5 +UINT32 ExampleTaskHi(VOID) +{ UINT32 ret; - PRINTK("Enter TaskHi Handler.\n"); - /* Delay the task for 2 ticks. The task is then suspended, and the remaining task with the highest priority (g_taskLoID) will be executed.*/ + PRINTK("Enter TaskHi Handler.\n"); + /* Delay the task for 2 ticks. The task is suspended, and the remaining task with the highest priority (g_taskLoID) will be executed. */ ret = LOS_TaskDelay(2); - if (ret != LOS_OK) { + if (ret != LOS_OK) { PRINTK("Delay Task Failed.\n"); - return LOS_NOK; - } - /* After 2 ticks elapse, the task is resumed and executed.*/ - PRINTK("TaskHi LOS_TaskDelay Done.\n"); - /* Suspend the task.*/ - ret = LOS_TaskSuspend(g_taskHiID); + return LOS_NOK; + } + /* After 2 ticks elapse, the task is resumed and executed. */ + PRINTK("TaskHi LOS_TaskDelay Done.\n"); + /* Suspend the task. */ + ret = LOS_TaskSuspend(g_taskHiID); if (ret != LOS_OK) { - PRINTK("Suspend TaskHi Failed.\n"); + PRINTK("Suspend TaskHi Failed.\n"); return LOS_NOK; - } - PRINTK("TaskHi LOS_TaskResume Success.\n"); + } + PRINTK("TaskHi LOS_TaskResume Success.\n"); return LOS_OK; } -/* Entry function of the lower-priority task */ +/* Entry function of the low-priority task. */ UINT32 ExampleTaskLo(VOID) -{ - UINT32 ret; - PRINTK("Enter TaskLo Handler.\n"); - /* Delay the task for 2 ticks. The task is then suspended, and the remaining task with the highest priority (background task) will be executed.*/ - ret = LOS_TaskDelay(2); - if (ret != LOS_OK) { - PRINTK("Delay TaskLo Failed.\n"); - return LOS_NOK; - } +{ + UINT32 ret; + PRINTK("Enter TaskLo Handler.\n"); + /* Delay the task for 2 ticks. The task is suspended, and the remaining task with the highest priority (background task) will be executed. */ + ret = LOS_TaskDelay(2); + if (ret != LOS_OK) { + PRINTK("Delay TaskLo Failed.\n"); + return LOS_NOK; + } PRINTK("TaskHi LOS_TaskSuspend Success.\n"); - /* Resume the suspended task g_taskHiID.*/ + /* Resume the suspended task g_taskHiID. */ ret = LOS_TaskResume(g_taskHiID); if (ret != LOS_OK) { PRINTK("Resume TaskHi Failed.\n"); return LOS_NOK; - } - PRINTK("TaskHi LOS_TaskDelete Success.\n"); + } + PRINTK("TaskHi LOS_TaskDelete Success.\n"); return LOS_OK; -} -/* Task test entry function, which is used to create two tasks with different priorities.*/ -UINT32 ExampleTaskCaseEntry(VOID) -{ - UINT32 ret; +} +/* Create two tasks with different priorities in the task test entry function. */ +UINT32 ExampleTaskCaseEntry(VOID) +{ + UINT32 ret; TSK_INIT_PARAM_S initParam = {0}; - /* Lock task scheduling.*/ + /* Lock task scheduling. */ LOS_TaskLock(); PRINTK("LOS_TaskLock() Success!\n"); + /* Parameters used to initialize the high-priority task, the resources of which can be reclaimed by LOS_TaskJoin. */ initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi; - initParam.usTaskPrio = TSK_PRIOR_HI; + initParam.usTaskPrio = TSK_PRIOR_HI; initParam.pcName = "HIGH_NAME"; initParam.uwStackSize = LOS_TASK_MIN_STACK_SIZE; initParam.uwResved = LOS_TASK_ATTR_JOINABLE; - /* Create a task with a higher priority. The task will not be executed immediately after being created, because task scheduling is locked.*/ + /* Create a task with higher priority. The task will not be executed immediately after being created, because task scheduling is locked. */ ret = LOS_TaskCreate(&g_taskHiID, &initParam); if (ret != LOS_OK) { LOS_TaskUnlock(); PRINTK("ExampleTaskHi create Failed! ret=%d\n", ret); return LOS_NOK; - } + } PRINTK("ExampleTaskHi create Success!\n"); + /* Parameters used to initialize the low-priority task, which will be automatically destroyed after the task is complete. */ initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo; initParam.usTaskPrio = TSK_PRIOR_LO; initParam.pcName = "LOW_NAME"; initParam.uwStackSize = LOS_TASK_MIN_STACK_SIZE; initParam.uwResved = LOS_TASK_STATUS_DETACHED; - /* Create a task with a lower priority. The task will not be executed immediately after being created, because task scheduling is locked.*/ + /* Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */ ret = LOS_TaskCreate(&g_taskLoID, &initParam); - if (ret!= LOS_OK) { - LOS_TaskUnlock(); + if (ret!= LOS_OK) { + LOS_TaskUnlock(); PRINTK("ExampleTaskLo create Failed!\n"); - return LOS_NOK; - } - PRINTK("ExampleTaskLo create Success!\n"); + return LOS_NOK; + } + PRINTK("ExampleTaskLo create Success!\n"); - /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed.*/ + /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed. */ LOS_TaskUnlock(); ret = LOS_TaskJoin(g_taskHiID, NULL); if (ret != LOS_OK) { @@ -319,11 +248,12 @@ UINT32 ExampleTaskCaseEntry(VOID) } while(1){}; return LOS_OK; -} +} ``` The development is successful if the return result is as follows: + ``` LOS_TaskLock() Success! ExampleTaskHi create Success! @@ -336,4 +266,3 @@ TaskHi LOS_TaskResume Success. TaskHi LOS_TaskDelete Success. Join ExampleTaskHi Success! ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-event.md b/en/device-dev/kernel/kernel-small-basic-trans-event.md index 2aba10352fbf9691cb4ab825f00ec28564d14c44..7d478d71a13aebbfa152bebd7832496887ebdfb7 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-event.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-event.md @@ -1,146 +1,145 @@ # Event -## Basic Concepts -An event is a mechanism for communication between tasks. It can be used to synchronize tasks. +## Basic Concepts + +An event is a communication mechanism used to synchronize tasks. In multi-task environment, synchronization is required between tasks. Events can be used for synchronization in the following cases: -- One-to-many synchronization: A task waits for the triggering of multiple events. A task is woken up by one or multiple events. -- Many-to-many synchronization: Multiple tasks wait for the triggering of multiple events. +- One-to-many synchronization: A task waits for the triggering of multiple events. A task can be woken up by one or multiple events. + +- Many-to-many synchronization: Multiple tasks wait for the triggering of multiple events. The event mechanism provided by the OpenHarmony LiteOS-A event module has the following features: -- A task triggers or waits for an event by creating an event control block. -- Events are independent of each other. The internal implementation is a 32-bit unsigned integer, and each bit indicates an event type. The 25th bit is unavailable. Therefore, a maximum of 31 event types are supported. -- Events are used only for synchronization between tasks, but not for data transmission. -- Writing the same event type to the event control block for multiple times is equivalent to writing the event type only once before the event control block is cleared. -- Multiple tasks can read and write the same event. -- The event read/write timeout mechanism is supported. +- A task triggers or waits for an event by creating an event control block. + +- Events are independent of each other. The internal implementation is a 32-bit unsigned integer, and each bit indicates an event type. The value **0** indicates that the event type does not occur, and the value **1** indicates that the event type has occurred. There are 31 event types in total. The 25th bit (`0x02U << 24`) is reserved. + +- Events are used for task synchronization, but not for data transmission. + +- Writing the same event type to an event control block multiple times is equivalent to writing the event type only once before the event control block is cleared. + +- Multiple tasks can read and write the same event. -## Working Principles +- The event read/write timeout mechanism is supported. + + +## Working Principles + + +### Event Control Block -### Event Control Block ``` /** -* Event control block data structure + * Event control block data structure */ typedef struct tagEvent { UINT32 uwEventID; /* Event set, which is a collection of events processed (written and cleared). */ - LOS_DL_LIST stEventList; /* List of tasks waiting for specific events */ + LOS_DL_LIST stEventList; /* List of tasks waiting for specific events. */ } EVENT_CB_S, *PEVENT_CB_S; ``` -### Working Principles -**Initializing an event**: An event control block is created to maintain a collection of processed events and a linked list of tasks waiting for specific events. +### Working Principles + +**Initializing an Event** + +An event control block is created to maintain a set of processed events and a linked list of tasks waiting for specific events. -**Writing an event**: When a specified event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the task conditions. +**Writing an Event** -**Reading an event**: If the read event already exists, it is returned synchronously. In other cases, the return time is determined based on the timeout period and event triggering status. If the wait event condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired. +When an event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the specified conditions. -The input parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** indicates the mask of the event. **mode** indicates the handling mode, which can be any of the following: +**Reading an Event** -- **LOS\_WAITMODE\_AND**: Event reading is successful only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. -- **LOS\_WAITMODE\_OR**: Event reading is successful when any of the events corresponding to **eventMask** occurs. Otherwise, the task will be blocked, or an error code will be returned. -- **LOS\_WAITMODE\_CLR**: This mode must be used with **LOS\_WAITMODE\_AND** or **LOS\_WAITMODE\_OR** \(LOS\_WAITMODE\_AND | LOS\_WAITMODE\_CLR or LOS\_WAITMODE\_OR | LOS\_WAITMODE\_CLR\). In this mode, if **LOS\_WAITMODE\_AND** or **LOS\_WAITMODE\_OR** is successful, the corresponding event type bit in the event control block will be automatically cleared. +If the event to read already exists, it is returned synchronously. In other cases, the event is returned based on the timeout period and event triggering conditions. If the wait condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired. -**Clearing events**: Clear the event set of the event control block based on the specified mask. If the mask is **0**, the event set will be cleared. If the mask is **0xffff**, no event will be cleared, and the event set remains unchanged. +The parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** specifies the event mask. **mode** specifies the handling mode, which can be any of the following: -**Destroying an event**: Destroy the specified event control block. +- **LOS_WAITMODE_AND**: Read the event only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. -**Figure 1** Event working mechanism for small systems -![](figures/event-working-mechanism-for-small-systems.png "event-working-mechanism-for-small-systems") +- **LOS_WAITMODE_OR**: Read the event only when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. -## Development Guidelines +- **LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared. -### Available APIs +**Clearing Events** + +The events in the event set of the event control block can be cleared based on the specified mask. The mask **0** means to clear the event set; the mask **0xffff** means the opposite. + +**Destroying Events** + +The event control block can be destroyed to release resources. + +**Figure 1** Event working mechanism for small systems + + ![](figures/event-working-mechanism-for-small-systems.png "event-working-mechanism-for-small-systems") + + +## Development Guidelines + + +### Available APIs The following table describes APIs available for the OpenHarmony LiteOS-A event module. -**Table 1** Event module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Initializing events

-

LOS_EventInit

-

Initializes an event control block.

-

Reading/Writing events

-

LOS_EventRead

-

Reads a specified type of event, with the timeout period of a relative time period in ticks.

-

LOS_EventWrite

-

Writes a specified type of event.

-

Clearing events

-

LOS_EventClear

-

Clears a specified type of event.

-

Checking the event mask

-

LOS_EventPoll

-

Returns whether the event input by the user meets the expectation based on the event ID, event mask, and read mode passed by the user.

-

Destroying events

-

LOS_EventDestroy

-

Destroys a specified event control block.

-
- -### How to Develop +**Table 1** APIs of the event module + +| Category| API Description | +| -------- | -------- | +| Initializing an event| **LOS_EventInit**: initializes an event control block.| +| Reading/Writing an event| - **LOS_EventRead**: reads an event, with a relative timeout period in ticks.
- **LOS_EventWrite**: writes an event. | +| Clearing events| **LOS_EventClear**: clears a specified type of events.| +| Checking the event mask| **LOS_EventPoll**: checks whether the specified event occurs.| +| Destroying events | **LOS_EventDestroy**: destroys an event control block.| + + +### How to Develop The typical event development process is as follows: -1. Initialize an event control block. -2. Block a read event control block. -3. Write related events. -4. Wake up a blocked task, read the event, and check whether the event meets conditions. -5. Handle the event control block. -6. Destroy an event control block. +1. Initialize an event control block. + +2. Block a read event. + +3. Write related events. + +4. Wake up a blocked task, read the event, and check whether the event meets conditions. + +5. Handle the event control block. + +6. Destroy an event control block. + +> **NOTE** +> +> - For event read and write operations, the 25th bit (`0x02U << 24`) of the event is reserved and cannot be set. +> +> - Repeated writes of the same event are treated as one write. + + +## Development Example + + +### Example Description ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- When an event is read or written, the 25th bit of the event is reserved and cannot be set. ->- Repeated writes of the same event are treated as one write. +In this example, run the **Example_TaskEntry** task to create the **Example_Event** task. Run the **Example_Event** task to read an event to trigger task switching. Run the **Example_TaskEntry** task to write an event. You can understand the task switching during event operations based on the sequence in which logs are recorded. -## Development Example +1. Create the **Example_Event** task in the **Example_TaskEntry** task with a higher priority than the **Example_TaskEntry** task. -### Example Description +2. Run the **Example_Event** task to read event **0x00000001**. Task switching is triggered to execute the **Example_TaskEntry** task. -In this example, run the **Example\_TaskEntry** task to create the **Example\_Event** task, run the **Example\_Event** task to read an event to trigger task switching, and run the **Example\_TaskEntry** task to write an event. You can understand the task switching during event operations based on the sequence in which logs are recorded. +3. Run the **Example_TaskEntry** task to write event **0x00000001**. Task switching is triggered to execute the **Example_Event** task. -1. Create the **Example\_Event** task in the **Example\_TaskEntry** task with a higher priority than the **Example\_TaskEntry** task. -2. Run the **Example\_Event** task to read event **0x00000001**. Task switching is triggered to execute the **Example\_TaskEntry** task. -3. Run the **Example\_TaskEntry** task to write event **0x00000001**. Task switching is triggered to execute the **Example\_Event** task. -4. The **Example\_Event** task is executed. -5. The **Example\_TaskEntry** task is executed. +4. The **Example_Event** task is executed. -### Sample Code +5. The **Example_TaskEntry** task is executed. + + +### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **Example_EventEntry** function is called in **TestTaskEntry**. The sample code is as follows: @@ -149,28 +148,28 @@ The sample code is as follows: #include "los_task.h" #include "securec.h" -/* Task ID*/ +/* Task ID */ UINT32 g_testTaskId; -/* Event control structure*/ +/* Event control structure */ EVENT_CB_S g_exampleEvent; -/* Type of the wait event*/ -#define EVENT_WAIT 0x00000001 - -/* Example task entry function*/ +/* Type of the wait event */ +#define EVENT_WAIT 0x00000001 +#define EVENT_TIMEOUT 500 +/* Example task entry function */ VOID Example_Event(VOID) { UINT32 event; - /* Set a timeout period for event reading to 100 ticks. If the specified event is not read within 100 ticks, the read operation times out and the task is woken up.*/ - printf("Example_Event wait event 0x%x \n", EVENT_WAIT); + /* Set a timeout period for event reading to 100 ticks. If the specified event is not read within 100 ticks, the read operation times out and the task is woken up. */ + dprintf("Example_Event wait event 0x%x \n", EVENT_WAIT); - event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); + event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT); if (event == EVENT_WAIT) { - printf("Example_Event,read event :0x%x\n", event); + dprintf("Example_Event,read event :0x%x\n", event); } else { - printf("Example_Event,read event timeout\n"); + dprintf("Example_Event,read event timeout\n"); } } @@ -179,14 +178,14 @@ UINT32 Example_EventEntry(VOID) UINT32 ret; TSK_INIT_PARAM_S task1; - /* Initialize the event.*/ + /* Initialize the event. */ ret = LOS_EventInit(&g_exampleEvent); if (ret != LOS_OK) { - printf("init event failed .\n"); + dprintf("init event failed .\n"); return -1; } - /* Create a task.*/ + /* Create a task. */ (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Event; task1.pcName = "EventTsk1"; @@ -194,39 +193,34 @@ UINT32 Example_EventEntry(VOID) task1.usTaskPrio = 5; ret = LOS_TaskCreate(&g_testTaskId, &task1); if (ret != LOS_OK) { - printf("task create failed.\n"); + dprintf("task create failed.\n"); return LOS_NOK; } /* Write the task wait event (g_testTaskId). */ - printf("Example_TaskEntry write event.\n"); + dprintf("Example_TaskEntry write event.\n"); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); if (ret != LOS_OK) { - printf("event write failed.\n"); + dprintf("event write failed.\n"); return LOS_NOK; } - /* Clear the flag.*/ - printf("EventMask:%d\n", g_exampleEvent.uwEventID); + /* Clear the flag. */ + dprintf("EventMask:%d\n", g_exampleEvent.uwEventID); LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); - printf("EventMask:%d\n", g_exampleEvent.uwEventID); - - /* Delete the task.*/ - ret = LOS_TaskDelete(g_testTaskId); - if (ret != LOS_OK) { - printf("task delete failed.\n"); - return LOS_NOK; - } + dprintf("EventMask:%d\n", g_exampleEvent.uwEventID); return LOS_OK; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: + ``` Example_Event wait event 0x1 Example_TaskEntry write event. @@ -234,4 +228,3 @@ Example_Event,read event :0x1 EventMask:1 EventMask:0 ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-mutex.md b/en/device-dev/kernel/kernel-small-basic-trans-mutex.md index a911f97e1f894004b5cf48fea296982fe1d4d9b5..4d16065f285430f1a4b4007d65d6e704f4695f3a 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-mutex.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-mutex.md @@ -1,196 +1,118 @@ # Mutex +## Basic Concepts -## Basic Concepts - -A mutual exclusion \(mutex\) is a special binary semaphore used for exclusive access to shared resources. When a task holds the mutex, the task obtains the ownership of the mutex. When the task releases the mutex, the task will lose the ownership of the mutex. When a task holds a mutex, other tasks cannot hold the mutex. In an environment where multiple tasks compete for shared resources, the mutex ensures exclusive access to the shared resources. +A mutual exclusion (mutex) is a special binary semaphore used for exclusive access to shared resources. When a task holds the mutex, the task obtains the ownership of the mutex. When the task releases the mutex, the task will lose the ownership of the mutex. When a task holds a mutex, other tasks cannot hold the mutex. In an environment where multiple tasks compete for shared resources, the mutex ensures exclusive access to the shared resources. A mutex has three attributes: protocol attribute, priority upper limit attribute, and type attribute. The protocol attribute is used to handle a mutex requested by tasks of different priorities. The protocol attribute can be any of the following: -- LOS\_MUX\_PRIO\_NONE - - Do not inherit or protect the priority of the task requesting the mutex. +- LOS_MUX_PRIO_NONE + -- LOS\_MUX\_PRIO\_INHERIT +Do not inherit or protect the priority of the task requesting the mutex. - Inherits the priority of the task that requests the mutex. This is the default protocol attribute. When the mutex protocol attribute is set to this value: If a task with a higher priority is blocked because the mutex is already held by a task, the priority of the task holding the mutex will be backed up to the priority bitmap of the task control block, and then set to be the same as that of the task of a higher priority. When the task holding the mutex releases the mutex, its task priority is restored to its original value. +- LOS_MUX_PRIO_INHERIT + -- LOS\_MUX\_PRIO\_PROTECT - - Protects the priority of the task that requests the mutex. When the mutex protocol attribute is set to this value: If the priority of the task that requests the mutex is lower than the upper limit of the mutex priority, the task priority will be backed up to the priority bitmap of the task control block, and then set to the upper limit value of the mutex priority. When the mutex is released, the task priority is restored to its original value. +Inherits the priority of the task that requests the mutex. This is the default protocol attribute. When the mutex protocol attribute is set to this value: If a task with a higher priority is blocked because the mutex is already held by a task, the priority of the task holding the mutex will be backed up to the priority bitmap of the task control block, and then set to be the same as that of the task of a higher priority. When the task holding the mutex releases the mutex, its task priority is restored to its original value. +- LOS_MUX_PRIO_PROTECT + + Protects the priority of the task that requests the mutex. When the mutex protocol attribute is set to this value: If the priority of the task that requests the mutex is lower than the upper limit of the mutex priority, the task priority will be backed up to the priority bitmap of the task control block, and then set to the upper limit value of the mutex priority. When the mutex is released, the task priority is restored to its original value. The type attribute of a mutex specifies whether to check for deadlocks and whether to support recursive holding of the mutex. The type attribute can be any of the following: -- LOS\_MUX\_NORMAL - - Common mutex, which does not check for deadlocks. If a task repeatedly attempts to hold a mutex, the thread will be deadlocked. If the mutex type attribute is set to this value, a task cannot release a mutex held by another task or repeatedly release a mutex. Otherwise, unexpected results will be caused. +- LOS_MUX_NORMAL + -- LOS\_MUX\_RECURSIVE +Common mutex, which does not check for deadlocks. If a task repeatedly attempts to hold a mutex, the thread will be deadlocked. If the mutex type attribute is set to this value, a task cannot release a mutex held by another task or repeatedly release a mutex. Otherwise, unexpected results will be caused. - Recursive mutex, which is the default attribute. If the type attribute of a mutex is set to this value, a task can hold the mutex for multiple times. Another task can hold this mutex only when the number of lock holding times is the same as the number of lock release times. However, any attempt to hold a mutex held by another task or attempt to release a mutex that has been released will return an error code. +- LOS_MUX_RECURSIVE + -- LOS\_MUX\_ERRORCHECK +Recursive mutex, which is the default attribute. If the type attribute of a mutex is set to this value, a task can hold the mutex for multiple times. Another task can hold this mutex only when the number of lock holding times is the same as the number of lock release times. However, any attempt to hold a mutex held by another task or attempt to release a mutex that has been released will return an error code. - Allows automatic check for deadlocks. When a mutex is set to this type, an error code will be returned if a task attempts to repeatedly hold the mutex, attempts to release the mutex held by another task, or attempts to release the mutex that has been released. +- LOS_MUX_ERRORCHECK + + Mutex for error checks. When a mutex is set to this type, an error code will be returned if a task attempts to repeatedly hold the mutex, attempts to release the mutex held by another task, or attempts to release the mutex that has been released. -## Working Principles +## Working Principles -In a multi-task environment, multiple tasks may access the same shared resource. However, certain shared resources are not shared, and can only be accessed exclusively by tasks. A mutex can be used to address this issue. +In a multi-task environment, multiple tasks may access the same shared resources. However, certain shared resources are not shared, and can only be accessed exclusively by tasks. A mutex can be used to address this issue. When non-shared resources are accessed by a task, the mutex is locked. Other tasks will be blocked until the mutex is released by the task. The mutex allows only one task to access the shared resources at a time, ensuring integrity of operations on the shared resources. -**Figure 1** Mutex working mechanism for small systems + **Figure 1** Mutex working mechanism for the small system + ![](figures/mutex-working-mechanism-for-small-systems.png "mutex-working-mechanism-for-small-systems") -## Development Guidelines - -### Available APIs - -**Table 1** Mutex module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Initializing or destroying a mutex

-

LOS_MuxInit

-

Initializes a mutex.

-

LOS_MuxDestroy

-

Destroys the specified mutex.

-

Requesting or releasing a mutex

-

LOS_MuxLock

-

Requests the specified mutex.

-

LOS_MuxTrylock

-

Attempts to request the specified mutex in non-block mode.

-

LOS_MuxUnlock

-

Releases the specified mutex.

-

Verifying a mutex

-

LOS_MuxIsValid

-

Checks whether the mutex release is valid.

-

Initializing or destroying mutex attributes

-

LOS_MuxAttrInit

-

Initializes mutex attributes.

-

LOS_MuxAttrDestroy

-

Destroys the specified mutex attributes.

-

Setting and obtaining mutex attributes

-

LOS_MuxAttrGetType

-

Obtains the type attribute of a specified mutex.

-

LOS_MuxAttrSetType

-

Sets the type attribute of a specified mutex.

-

LOS_MuxAttrGetProtocol

-

Obtains the protocol attribute of a specified mutex.

-

LOS_MuxAttrSetProtocol

-

Sets the protocol attribute of a specified mutex.

-

LOS_MuxAttrGetPrioceiling

-

Obtains the priority upper limit attribute of a specified mutex.

-

LOS_MuxAttrSetPrioceiling

-

Sets the priority upper limit attribute of a specified mutex.

-

LOS_MuxGetPrioceiling

-

Obtains the mutex priority upper limit attribute.

-

LOS_MuxSetPrioceiling

-

Sets the mutex priority upper limit attribute.

-
- -### How to Develop + +## Development Guidelines + + +### Available APIs + + **Table 1** APIs of the mutex module + +| Category| API Description | +| -------- | -------- | +| Initializing or destroying a mutex| - **LOS_MuxInit**: initializes a mutex.
- **LOS_MuxDestroy**: destroys a mutex.| +| Requesting or releasing a mutex| - **LOS_MuxLock**: requests a mutex.
- **LOS_MuxTrylock**: requests a mutex without blocking.
- **LOS_MuxUnlock**: releases a mutex.| +| Verifying a mutex| - **LOS_MuxIsValid**: checks whether the mutex release is valid.
- **LOS_MuxAttrDestroy**: destroys the specified mutex attribute.| +| Setting and obtaining mutex attributes| - **LOS_MuxAttrGetType**: obtains the type attribute of a mutex.
- **LOS_MuxAttrSetType**: sets the type attribute for a mutex.
- **LOS_MuxAttrGetProtocol**: obtains the protocol attribute of a mutex.
- **LOS_MuxAttrSetProtocol**: sets the protocol attribute for a mutex.
- **LOS_MuxAttrGetPrioceiling**: obtains the priority upper limit attribute of a mutex.
- **LOS_MuxAttrSetPrioceiling**: sets the priority upper limit attribute for a mutex.
- **LOS_MuxGetPrioceiling**: obtains the priority upper limit of this mutex.
- **LOS_MuxSetPrioceiling**: sets the priority upper limit for this mutex. | + + +### How to Develop The typical mutex development process is as follows: -1. Call **LOS\_MuxInit** to initialize a mutex. +1. Call **LOS_MuxInit** to initialize a mutex. -2. Call **LOS\_MuxLock** to request a mutex. +2. Call **LOS_MuxLock** to request a mutex. The following modes are available: -- Non-block mode: A task acquires the mutex if the requested mutex is not held by any task or the task holding the mutex is the same as the task requesting the mutex. -- Permanent block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with the highest priority in the ready queue will be executed. The blocked task can be unlocked and executed only when the mutex is released. -- Scheduled block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with the highest priority in the ready queue will be executed. The blocked task can be executed only when the mutex is released within the specified timeout period or when the specified timeout period expires. +- Non-block mode: A task acquires the mutex if the requested mutex is not held by any task or the task holding the mutex is the same as the task requesting the mutex. + +- Permanent block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with a highest priority in the ready queue will be executed. The blocked task can be unlocked and executed only when the mutex is released. -3. Call **LOS\_MuxUnlock** to release a mutex. +- Scheduled block mode: A task acquires the mutex if the requested mutex is not occupied. If the mutex is occupied, the task will be blocked and the task with the highest priority in the ready queue will be executed. The blocked task can be executed only when the mutex is released within the specified timeout period or when the specified timeout period expires. -- If tasks are blocked by the specified mutex, the task with a higher priority will be unblocked when the mutex is released. The unblocked task changes to the Ready state and is scheduled. -- If no task is blocked by the specified mutex, the mutex is released successfully. +3. Call **LOS_MuxUnlock** to release a mutex. -4. Call **LOS\_MuxDestroy** to destroy a mutex. +- If tasks are blocked by the specified mutex, the task with a higher priority will be unblocked when the mutex is released. The unblocked task changes to the Ready state and is scheduled. ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- Two tasks cannot lock the same mutex. If a task attempts to lock a mutex held by another task, the task will be blocked until the mutex is unlocked. ->- Mutexes cannot be used in the interrupt service program. ->- When using the LiteOS-A kernel, the OpenHarmony must ensure real-time task scheduling and avoid long-time task blocking. Therefore, a mutex must be released as soon as possible after use. +- If no task is blocked by the specified mutex, the mutex is released successfully. -### Development Example +4. Call **LOS_MuxDestroy** to destroy a mutex. -Example Description +> **NOTE**
+> - Two tasks cannot lock the same mutex. If a task attempts to lock a mutex held by another task, the task will be blocked until the mutex is unclocked. +> +> - Mutexes cannot be used in the interrupt service program. +> +> - The system using the LiteOS-A kernel must ensure real-time task scheduling and avoid long-time task blocking. Therefore, a mutex must be released as soon as possible after use. + + +### Development Example + +#### Example Description This example implements the following: -1. Create a mutex in the **Example\_TaskEntry** task, and lock task scheduling. Create two tasks **Example\_MutexTask1** and **Example\_MutexTask2**. and unlock task scheduling. -2. When being scheduled, **Example\_MutexTask2** requests a mutex in permanent block mode. After acquiring the mutex, **Example\_MutexTask2** enters the sleep mode for 100 ticks. **Example\_MutexTask2** is suspended, and **Example\_MutexTask1** is woken up. -3. **Example\_MutexTask1** requests a mutex in scheduled block mode, and waits for 10 ticks. Because the mutex is still held by **Example\_MutexTask2**, **Example\_MutexTask1** is suspended. After 10 ticks, **Example\_MutexTask1** is woken up and attempts to request a mutex in permanent block mode. **Example\_MutexTask1** is suspended because the mutex is still held by **Example\_MutexTask2**. -4. After 100 ticks, **Example\_MutexTask2** is woken up and releases the mutex, and then **Example\_MutexTask1** is woken up. **Example\_MutexTask1** acquires the mutex and then releases the mutex. At last, the mutex is deleted. +1. Create the **Example_TaskEntry** task. In this task, create a mutex to lock task scheduling, and create two tasks **Example_MutexTask1** (with a lower priority) and **Example_MutexTask2** (with a higher priority) to unlock task scheduling. + +2. When being scheduled, **Example_MutexTask2** requests a mutex in permanent block mode. After acquiring the mutex, **Example_MutexTask2** enters the sleep mode for 100 ticks. **Example_MutexTask2** is suspended, and **Example_MutexTask1** is woken up. + +3. **Example_MutexTask1** requests a mutex in scheduled block mode, and waits for 10 ticks. Because the mutex is still held by **Example_MutexTask2**, **Example_MutexTask1** is suspended. After 10 ticks, **Example_MutexTask1** is woken up and attempts to request a mutex in permanent block mode. **Example_MutexTask1** is suspended because the mutex is still held by **Example_MutexTask2**. + +4. After 100 ticks, **Example_MutexTask2** is woken up and releases the mutex, and then **Example_MutexTask1** is woken up. **Example_MutexTask1** acquires the mutex and then releases the mutex. At last, the mutex is deleted. -**Sample Code** +#### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **Example_MutexEntry** function is called in **TestTaskEntry**. The sample code is as follows: @@ -199,7 +121,7 @@ The sample code is as follows: #include "los_mux.h" /* Mutex */ -LosMux g_testMux; +LosMux g_testMutex; /* Task ID*/ UINT32 g_testTaskId01; UINT32 g_testTaskId02; @@ -207,48 +129,49 @@ UINT32 g_testTaskId02; VOID Example_MutexTask1(VOID) { UINT32 ret; + LOS_TaskDelay(50); - printf("task1 try to get mutex, wait 10 ticks.\n"); - /* Request a mutex.*/ - ret = LOS_MuxLock(&g_testMux, 10); + dprintf("task1 try to get mutex, wait 10 ticks.\n"); + /* Request a mutex. */ + ret = LOS_MuxLock(&g_testMutex, 10); if (ret == LOS_OK) { - printf("task1 get mutex g_testMux.\n"); - /* Release the mutex.*/ - LOS_MuxUnlock(&g_testMux); + dprintf("task1 get mutex g_testMux.\n"); + /* Release the mutex. */ + LOS_MuxUnlock(&g_testMutex); return; - } - if (ret == LOS_ETIMEDOUT ) { - printf("task1 timeout and try to get mutex, wait forever.\n"); - /* Request a mutex.*/ - ret = LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("task1 wait forever, get mutex g_testMux.\n"); - /*Release the mutex.*/ - LOS_MuxUnlock(&g_testMux); - /* Delete the mutex. */ - LOS_MuxDestroy(&g_testMux); - printf("task1 post and delete mutex g_testMux.\n"); - return; - } + } + if (ret == LOS_ETIMEDOUT) { + dprintf("task1 timeout and try to get mutex, wait forever.\n"); + /* Request a mutex. */ + ret = LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER); + if (ret == LOS_OK) { + dprintf("task1 wait forever, get mutex g_testMux.\n"); + /* Release the mutex. */ + LOS_MuxUnlock(&g_testMutex); + /* Delete the mutex. */ + LOS_MuxDestroy(&g_testMutex); + dprintf("task1 post and delete mutex g_testMux.\n"); + return; + } } return; } VOID Example_MutexTask2(VOID) { - printf("task2 try to get mutex, wait forever.\n"); - /* Request a mutex.*/ - (VOID)LOS_MuxLock(&g_testMux, LOS_WAIT_FOREVER); + dprintf("task2 try to get mutex, wait forever.\n"); + /* Request a mutex. */ + (VOID)LOS_MuxLock(&g_testMutex, LOS_WAIT_FOREVER); - printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); + dprintf("task2 get mutex g_testMux and suspend 100 ticks.\n"); - /* Enable the task to enter sleep mode for 100 ticks.*/ + /* Enable the task to enter sleep mode for 100 ticks. */ LOS_TaskDelay(100); - printf("task2 resumed and post the g_testMux\n"); - /* Release the mutex.*/ - LOS_MuxUnlock(&g_testMux); + dprintf("task2 resumed and post the g_testMux\n"); + /* Release the mutex. */ + LOS_MuxUnlock(&g_testMutex); return; } @@ -258,13 +181,13 @@ UINT32 Example_MutexEntry(VOID) TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S task2; - /* Initializes the mutex./ - LOS_MuxInit(&g_testMux, NULL); + /* Initialize the mutex. */ + LOS_MuxInit(&g_testMutex, NULL); - /* Lock task scheduling.*/ + /* Lock task scheduling. */ LOS_TaskLock(); - /* Create task 1.*/ + /* Create task 1. */ memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1; task1.pcName = "MutexTsk1"; @@ -272,11 +195,11 @@ UINT32 Example_MutexEntry(VOID) task1.usTaskPrio = 5; ret = LOS_TaskCreate(&g_testTaskId01, &task1); if (ret != LOS_OK) { - printf("task1 create failed.\n"); + dprintf("task1 create failed.\n"); return LOS_NOK; } - /* Create task 2.*/ + /* Create task 2. */ memset(&task2, 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2; task2.pcName = "MutexTsk2"; @@ -284,11 +207,11 @@ UINT32 Example_MutexEntry(VOID) task2.usTaskPrio = 4; ret = LOS_TaskCreate(&g_testTaskId02, &task2); if (ret != LOS_OK) { - printf("task2 create failed.\n"); + dprintf("task2 create failed.\n"); return LOS_NOK; } - /* Unlock task scheduling.*/ + /* Unlock task scheduling. */ LOS_TaskUnlock(); return LOS_OK; @@ -299,13 +222,13 @@ UINT32 Example_MutexEntry(VOID) The development is successful if the return result is as follows: + ``` -task1 try to get mutex, wait 10 ticks. task2 try to get mutex, wait forever. task2 get mutex g_testMux and suspend 100 ticks. +task1 try to get mutex, wait 10 ticks. task1 timeout and try to get mutex, wait forever. task2 resumed and post the g_testMux task1 wait forever, get mutex g_testMux. task1 post and delete mutex g_testMux. ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-queue.md b/en/device-dev/kernel/kernel-small-basic-trans-queue.md index 5e2cbc062c4b9c3ba2066e37594d01d0fd871a7e..578fcac6d76ed84eb3129374bff9cf834e6a02f8 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-queue.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-queue.md @@ -1,7 +1,7 @@ # Queue -## Basic Concepts +## Basic Concepts A queue, also called a message queue, is a data structure used for communication between tasks. The queue receives messages of unfixed length from tasks or interrupts, and determines whether to store the transferred messages in the queue based on different APIs. @@ -11,21 +11,30 @@ You can adjust the timeout period of the read queue and write queue to adjust th An asynchronous processing mechanism is provided to allow messages in a queue not to be processed immediately. In addition, queues can be used to buffer messages and implement asynchronous task communication. Queues have the following features: -- Messages are queued in FIFO mode and can be read and written asynchronously. -- Both the read queue and write queue support the timeout mechanism. -- Each time a message is read, the message node becomes available. -- The types of messages to be sent are determined by the parties involved in communication. Messages of different lengths \(not exceeding the message node size of the queue\) are allowed. -- A task can receive messages from and send messages to any message queue. -- Multiple tasks can receive messages from and send messages to the same queue. -- When a queue is created, the required dynamic memory space is automatically allocated in the queue API. +- Messages are queued in first-in-first-out (FIFO) mode and can be read and written asynchronously. -## Working Principles +- Both the read queue and write queue support the timeout mechanism. + +- Each time a message is read, the message node becomes available. + +- The types of messages to be sent are determined by the parties involved in communication. Messages of different lengths (not exceeding the message node size of the queue) are allowed. + +- A task can receive messages from and send messages to any message queue. + +- Multiple tasks can receive messages from and send messages to the same queue. + +- When a queue is created, the required dynamic memory space is automatically allocated in the queue API. + + +## Working Principles + + +### Queue Control Block -### Queue Control Block ``` /** - * Data structure of the queue control block + * Data structure of the queue control block */ typedef struct { UINT8 *queueHandle; /**< Pointer to a queue handle */ @@ -43,121 +52,94 @@ typedef struct { Each queue control block contains information about the queue status. -- **OS\_QUEUE\_UNUSED**: The queue is not in use. -- **OS\_QUEUE\_INUSED**: The queue is in use. +- **OS_QUEUE_UNUSED**: The queue is not in use. + +- **OS_QUEUE_INUSED**: The queue is in use. + + +### Working Principles + +- The queue ID is returned when a queue is created successfully. + +- The queue control block contains **Head** and **Tail**, which indicate the storage status of messages in a queue. **Head** indicates the start position of occupied message nodes in the queue. **Tail** indicates the end position of the occupied message nodes and the start position of idle message nodes. When a queue is created, **Head** and **Tail** point to the start position of the queue. -### Working Principles +- When data is to be written to a queue, **readWriteableCnt[1]** is used to determine whether data can be written to the queue. If **readWriteableCnt[1]** is **0**, the queue is full and data cannot be written to it. Data can be written to the head node or tail node of a queue. To write data to the tail node, locate the start idle message node based on **Tail** and write data to it. If **Tail** is pointing to the tail of the queue, the rewind mode is used. To write data to the head node, locate previous node based on **Head** and write data to it. If **Head** is pointing to the start position of the queue, the rewind mode is used. -- The queue ID is returned if a queue is created successfully. -- The queue control block contains **Head** and **Tail**, which indicate the storage status of messages in a queue. **Head** indicates the start position of occupied message nodes in the queue. **Tail** indicates the end position of the occupied message nodes and the start position of idle message nodes. When a queue is created, **Head** and **Tail** point to the start position of the queue. -- When data is to be written to a queue, **readWriteableCnt\[1\]** is used to determine whether data can be written to the queue. If **readWriteableCnt\[1\]** is **0**, the queue is full and data cannot be written to it. Data can be written to the head node or tail node of a queue. To write data to the tail node, locate the start idle message node based on **Tail** and write data to it. If **Tail** is pointing to the tail of the queue, the rewind mode is used. To write data to the head node, locate previous node based on **Head** and write data to it. If **Head** is pointing to the start position of the queue, the rewind mode is used. -- When a queue is to be read, **readWriteableCnt\[0\]** is used to determine whether the queue has messages to read. Reading an idle queue \(**readWriteableCnt\[0\]** is** 0**\) will cause task suspension. If the queue has messages to read, the system locates the first node to which data is written based on **Head** and read the message from the node. If **Head** is pointing to the tail of the queue, the rewind mode is used. -- When a queue is to be deleted, the system locates the queue based on the queue ID, sets the queue status to **OS\_QUEUE\_UNUSED**, sets the queue control block to the initial state, and releases the memory occupied by the queue. +- When a queue is to be read, **readWriteableCnt[0]** is used to determine whether the queue has messages to read. Reading an idle queue (**readWriteableCnt[0]** is** 0**) will cause task suspension. If the queue has messages to read, the system locates the first node to which data is written based on **Head** and read the message from the node. If **Head** is pointing to the tail of the queue, the rewind mode is used. -**Figure 1** Reading and writing data in a queue -![](figures/reading-and-writing-data-in-a-queue-3.png "reading-and-writing-data-in-a-queue-3") +- When a queue is to be deleted, the system locates the queue based on the queue ID, sets the queue status to **OS_QUEUE_UNUSED**, sets the queue control block to the initial state, and releases the memory occupied by the queue. + + **Figure 1** Reading and writing data in a queue + + ![](figures/reading-and-writing-data-in-a-queue-3.png "reading-and-writing-data-in-a-queue-3") The preceding figure illustrates how to write data to the tail node only. Writing data to the head node is similar. -## Development Guidelines - -### Available APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting a message queue

-

LOS_QueueCreate

-

Creates a message queue. The system dynamically allocates the queue space.

-

LOS_QueueDelete

-

Deletes the specified queue based on the queue ID.

-

Reading or writing data in a queue (without the content contained in the address)

-

LOS_QueueRead

-

Reads data in the head node of the specified queue. The data in the queue node is an address.

-

LOS_QueueWrite

-

Writes the value of the input parameter bufferAddr (buffer address) to the tail node of the specified queue.

-

LOS_QueueWriteHead

-

Writes the value of the input parameter bufferAddr (buffer address) to the head node of the specified queue.

-

Reading or writing in a queue (with the content contained in the address)

-

LOS_QueueReadCopy

-

Reads data from the head node of the specified queue.

-

LOS_QueueWriteCopy

-

Writes the data saved in the input parameter bufferAddr to the tail node of the specified queue.

-

LOS_QueueWriteHeadCopy

-

Writes the data saved in the input parameter bufferAddr to the head node of the specified queue.

-

Obtaining queue information

-

LOS_QueueInfoGet

-

Obtains information about the specified queue, including the queue ID, queue length, message node size, head node, tail node, number of readable nodes, number of writable nodes, tasks waiting for read operations, and tasks waiting for write operations.

-
- -### How to Develop - -1. Call **LOS\_QueueCreate** to create a queue. The queue ID is returned when the queue is created. -2. Call **LOS\_QueueWrite** or **LOS\_QueueWriteCopy** to write messages to the queue. -3. Call **LOS\_QueueRead** or **LOS\_QueueReadCopy** to read messages from the queue. -4. Call **LOS\_QueueInfoGet** to obtain queue information. -5. Call **LOS\_QueueDelete** to delete a queue. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->- The maximum number of queues supported by the system is the total number of queue resources of the system, not the number of queue resources available to users. For example, if the system software timer occupies one more queue resource, the number of queue resources available to users decreases by one. ->- The input parameters queue name and flags passed when a queue is created are reserved for future use. ->- The input parameter **timeOut** in the queue interface function is relative time. ->- **LOS\_QueueReadCopy**, **LOS\_QueueWriteCopy**, and **LOS\_QueueWriteHeadCopy** are a group of APIs that must be used together. **LOS\_QueueRead**, **LOS\_QueueWrite**, and **LOS\_QueueWriteHead** are a group of APIs that must be used together. ->- As **LOS\_QueueWrite**, **LOS\_QueueWriteHead**, and **LOS\_QueueRead** are used to manage data addresses, you must ensure that the memory directed by the pointer obtained by calling **LOS\_QueueRead** is not modified or released abnormally when the queue is being read. Otherwise, unpredictable results may occur. ->- If the input parameter **bufferSize** in **LOS\_QueueRead** and **LOS\_QueueReadCopy** is less than the length of the message, the message will be truncated. ->- **LOS\_QueueWrite**, **LOS\_QueueWriteHead**, and **LOS\_QueueRead** are called to manage data addresses, which means that the actual data read or written is pointer data. Therefore, before using these APIs, ensure that the message node size is the pointer length during queue creation, to avoid waste and read failures. - -## Development Example - -### Example Description - -Create a queue and two tasks. Enable task 1 to call the queue write API to send messages, and enable task 2 to receive messages by calling the queue read API. - -1. Create task 1 and task 2 by calling **LOS\_TaskCreate**. -2. Create a message queue by calling **LOS\_QueueCreate**. -3. Enable messages to be sent in task 1 by calling **SendEntry**. -4. Enable messages to be received in task 2 by calling **RecvEntry**. -5. Call **LOS\_QueueDelete** to delete a queue. - -### Sample Code + +## Development Guidelines + + +### Available APIs + +| Category| API Description | +| -------- | -------- | +| Creating or deleting a message queue| - **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.
- **LOS_QueueDelete**: deletes a queue.| +| Reading or writing data (address without the content) in a queue| - **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.
- **LOS_QueueWrite**: writes the value of **bufferAddr** (buffer address) to the tail node of a queue.
- **LOS_QueueWrite**: writes the value of **bufferAddr** (buffer address) to the head node of a queue.| +| Reading or writing data (data and address) in a queue| - **LOS_QueueReadCopy**: reads data from the head node of a queue.
- **LOS_QueueWriteCopy**: writes the data saved in **bufferAddr** to the tail node of a queue.
- **LOS_QueueWriteHeadCopy**: writes the data saved in **bufferAddr** to the head node of a queue.| +| Obtaining queue information| **LOS_QueueInfoGet**: obtains queue information, including the queue ID, queue length, message node size, head node, tail node, number of readable/writable nodes, and tasks waiting for read/write operations.| + + +### How to Develop + +1. Call **LOS_QueueCreate** to create a queue. The queue ID is returned when the queue is created. + +2. Call **LOS_QueueWrite** or **LOS_QueueWriteCopy** to write data to the queue. + +3. Call **LOS_QueueRead** or **LOS_QueueReadCopy** to read data from the queue. + +4. Call **LOS_QueueInfoGet** to obtain queue information. + +5. Call **LOS_QueueDelete** to delete a queue. + +> **NOTE**
+> - The maximum number of queues supported by the system is the total number of queue resources of the system, not the number of queue resources available to users. For example, if the system software timer occupies one more queue resource, the number of queue resources available to users decreases by one. +> +> - The queue name and flags passed in when a queue is created are reserved for future use. +> +> - The parameter **timeOut** in the queue function is relative time. +> +> - **LOS_QueueReadCopy**, **LOS_QueueWriteCopy**, and **LOS_QueueWriteHeadCopy** are a group of APIs that must be used together. **LOS_QueueRead**, **LOS_QueueWrite**, and **LOS_QueueWriteHead** are a group of APIs that must be used together. +> +> - As **LOS_QueueWrite**, **LOS_QueueWriteHead**, and **LOS_QueueRead** are used to manage data addresses, you must ensure that the memory directed by the pointer obtained by calling **LOS_QueueRead** is not modified or released abnormally when the queue is being read. Otherwise, unpredictable results may occur. +> +> - If the length of the data to read in **LOS_QueueRead** or **LOS_QueueReadCopy** is less than the actual message length, the message will be truncated. +> +> - **LOS_QueueWrite**, **LOS_QueueWriteHead**, and **LOS_QueueRead** are called to manage data addresses, which means that the actual data read or written is pointer data. Therefore, before using these APIs, ensure that the message node size is the pointer length during queue creation, to avoid waste and read failures. + + +## Development Example + + +### Example Description + +Create a queue and two tasks. Enable task 1 to write data to the queue, and task 2 to read data from the queue. + +1. Call **LOS_TaskCreate** to create task 1 and task 2. + +2. Call **LOS_QueueCreate** to create a message queue. + +3. Task 1 sends a message in **SendEntry**. + +4. Task 2 receives message in **RecvEntry**. + +5. Call **LOS_QueueDelete** to delete the queue. + + +### Sample Code + +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**. + +To avoid excessive printing, call **LOS_Msleep(5000)** to cause a short delay before calling **ExampleQueue**. The sample code is as follows: @@ -175,7 +157,7 @@ VOID SendEntry(VOID) ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); if(ret != LOS_OK) { - printf("send message failure, error: %x\n", ret); + dprintf("send message failure, error: %x\n", ret); } } @@ -185,30 +167,36 @@ VOID RecvEntry(VOID) CHAR readBuf[BUFFER_LEN] = {0}; UINT32 readLen = BUFFER_LEN; - // Sleep for 1s. - usleep(1000000); + LOS_Msleep(1000); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); if(ret != LOS_OK) { - printf("recv message failure, error: %x\n", ret); + dprintf("recv message failure, error: %x\n", ret); } - printf("recv message: %s\n", readBuf); + dprintf("recv message: %s\n", readBuf); ret = LOS_QueueDelete(g_queue); if(ret != LOS_OK) { - printf("delete the queue failure, error: %x\n", ret); + dprintf("delete the queue failure, error: %x\n", ret); } - printf("delete the queue success!\n"); + dprintf("delete the queue success!\n"); } UINT32 ExampleQueue(VOID) { - printf("start queue example\n"); + dprintf("start queue example\n"); UINT32 ret = 0; UINT32 task1, task2; TSK_INIT_PARAM_S initParam = {0}; + ret = LOS_QueueCreate("queue", 5, &g_queue, 0, 50); + if(ret != LOS_OK) { + dprintf("create queue failure, error: %x\n", ret); + } + + dprintf("create the queue success!\n"); + initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; initParam.usTaskPrio = 9; initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; @@ -217,7 +205,8 @@ UINT32 ExampleQueue(VOID) LOS_TaskLock(); ret = LOS_TaskCreate(&task1, &initParam); if(ret != LOS_OK) { - printf("create task1 failed, error: %x\n", ret); + dprintf("create task1 failed, error: %x\n", ret); + LOS_QueueDelete(g_queue); return ret; } @@ -225,29 +214,26 @@ UINT32 ExampleQueue(VOID) initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; ret = LOS_TaskCreate(&task2, &initParam); if(ret != LOS_OK) { - printf("create task2 failed, error: %x\n", ret); + dprintf("create task2 failed, error: %x\n", ret); + LOS_QueueDelete(g_queue); return ret; } - ret = LOS_QueueCreate("queue", 5, &g_queue, 0, 50); - if(ret != LOS_OK) { - printf("create queue failure, error: %x\n", ret); - } - - printf("create the queue success!\n"); LOS_TaskUnlock(); + LOS_Msleep(5000); return ret; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: + ``` -start test example +start queue example create the queue success! recv message: test message delete the queue success! ``` - diff --git a/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md b/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md index 31cf7a943e55c174be94905d70ad7c5a6d102dcb..22411251d4982ec959d2e1ebb9984c99fd1860f4 100644 --- a/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md +++ b/en/device-dev/kernel/kernel-small-basic-trans-semaphore.md @@ -1,34 +1,38 @@ # Semaphore -## Basic Concepts +## Basic Concepts -Semaphore is a mechanism for implementing inter-task communication. It implements synchronization between tasks or exclusive access to shared resources. +Semaphore is a mechanism used to implement synchronization between tasks or exclusive access to shared resources. -In the data structure of a semaphore, there is a value indicating the number of shared resources available. The value can be: +In the semaphore data structure, there is a value indicating the number of shared resources available. The value can be: -- **0**: The semaphore is unavailable. Tasks waiting for the semaphore may exist. -- Positive number: The semaphore is available. +- **0**: The semaphore is unavailable. In this case, tasks waiting for the semaphore may exist. -The semaphore for exclusive access is different from the semaphore for synchronization: +- Positive number: The semaphore is available. -- Semaphore used for exclusive access: The initial semaphore counter value \(non-zero\) indicates the number of shared resources available. The semaphore counter value must be acquired before a shared resource is used, and released when the resource is no longer required. When all shared resources are used, the semaphore counter is reduced to 0 and the tasks that need to obtain the semaphores will be blocked. This ensures exclusive access to shared resources. In addition, when the number of shared resources is 1, a binary semaphore \(similar to the mutex mechanism\) is recommended. -- Semaphore used for synchronization: The initial semaphore counter value is **0**. Task 1 cannot acquire the semaphore and is blocked. Task 1 enters Ready or Running state only when the semaphore is released by task 2 or an interrupt. In this way, task synchronization is implemented. +The semaphore used for exclusive access to resources is different from the semaphore used for synchronization: -## Working Principles +- Semaphore used for exclusive access: The initial semaphore counter value \(non-zero\) indicates the number of shared resources available. A semaphore must be acquired before a shared resource is used, and released when the resource is no longer required. When all shared resources are used, the semaphore counter is reduced to 0 and all tasks requiring the semaphore will be blocked. This ensures exclusive access to shared resources. In addition, if the number of shared resources is 1, a binary semaphore \(similar to the mutex mechanism\) is recommended. + +- Semaphore used for synchronization: The initial semaphore counter value is **0**. A task without the semaphore will be blocked, and enters the Ready or Running state only when the semaphore is released by another task or an interrupt. + + +## Working Principles **Semaphore Control Block** + ``` /** - * Data structure of the semaphore control block + * Data structure of the semaphore control block */ typedef struct { UINT16 semStat; /* Semaphore status */ - UINT16 semType; /* Semaphore type*/ - UINT16 semCount; /* Semaphore count*/ - UINT16 semId; /* Semaphore index*/ - LOS_DL_LIST semList; /* Mount the task blocked by the semaphore.*/ + UINT16 semType; /* Semaphore type */ + UINT16 semCount; /* Semaphore count */ + UINT16 semId; /* Semaphore ID */ + LOS_DL_LIST semList; /* List of blocked tasks */ } LosSemCB; ``` @@ -36,102 +40,89 @@ typedef struct { Semaphore allows only a specified number of tasks to access a shared resource at a time. When the number of tasks accessing the resource reaches the limit, other tasks will be blocked until the semaphore is released. -- Semaphore initialization +- Semaphore initialization + + Allocate memory for the semaphores (the number of semaphores is specified by the **LOSCFG_BASE_IPC_SEM_LIMIT** macro), set all semaphores to the unused state, and add them to a linked list. + +- Semaphore creation + + Obtain a semaphore from the linked list of unused semaphores and assign an initial value to the semaphore. - The system allocates memory for the semaphores configured \(you can configure the number of semaphores using the **LOSCFG\_BASE\_IPC\_SEM\_LIMIT** macro\), initializes all semaphores to be unused semaphores, and adds them to a linked list for the system to use. +- Semaphore request -- Semaphore creation + If the counter value is greater than 0 when a semaphore is requsted, the counter is decreased by 1 and a success message is returned. Otherwise, the task is blocked and added to the end of a task queue waiting for semaphores. The wait timeout period can be set. - The system obtains a semaphore from the linked list of unused semaphores and assigns an initial value to the semaphore. +- Semaphore release -- Semaphore request + If no task is waiting for the semaphore, the counter is incremented by 1. Otherwise, wake up the first task in the wait queue. - If the counter value is greater than 0, the system allocates a semaphore, decreases the value by 1, and returns a success message. Otherwise, the system blocks the task and moves the task to the end of a task queue waiting for semaphores. The wait timeout period can be set. +- Semaphore deletion -- Semaphore release + Set a semaphore in use to the unused state and add it to the linked list of unused semaphores. - When a semaphore is released, if there is no task waiting for it, the counter value is increased by 1. Otherwise, the first task in the wait queue is woken up. +The following figure illustrates the semaphore working mechanism. -- Semaphore deletion +**Figure 1** Semaphore working mechanism for the small system - The system sets a semaphore in use to unused state and inserts it to the linked list of unused semaphores. +![](figures/semaphore-working-mechanism-for-small-systems.png "semaphore-working-mechanism-for-small-systems") -The following figure illustrates the semaphore working mechanism. +## Development Guidelines -**Figure 1** Semaphore working mechanism for small systems -![](figures/semaphore-working-mechanism-for-small-systems.png "semaphore-working-mechanism-for-small-systems") -## Development Guidelines - -### Available APIs - -**Table 1** Semaphore module APIs - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

Creating or deleting a semaphore

-

LOS_SemCreate

-

Creates a semaphore and returns the semaphore ID.

-

LOS_BinarySemCreate

-

Creates a binary semaphore. The maximum counter value is 1.

-

LOS_SemDelete

-

Deletes a semaphore.

-

Requesting or releasing a semaphore

-

LOS_SemPend

-

Requests a specified semaphore and sets the timeout period.

-

LOS_SemPost

-

Posts (releases) a semaphore.

-
- -### How to Develop - -1. Call **LOS\_SemCreate** to create a semaphore. To create a binary semaphore, call **LOS\_BinarySemCreate**. -2. Call **LOS\_SemPend** to request a semaphore. -3. Call **LOS\_SemPost** to release a semaphore. -4. Call **LOS\_SemDelete** to delete a semaphore. - ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->As interrupts cannot be blocked, semaphores cannot be requested in block mode for interrupts. - -### Development Example - -### Example Description +### Available APIs + +**Table 1** APIs for creating and deleting a semaphore + +| API| Description| +| -------- | -------- | +| LOS_SemCreate | Creates a semaphore and returns the semaphore ID.| +| LOS_BinarySemCreate | Creates a binary semaphore. The maximum counter value is **1**.| +| LOS_SemDelete | Deletes a semaphore.| + +**Table 2** APIs for requesting and releasing a semaphore + +| API| Description| +| -------- | -------- | +| LOS_SemPend | Requests a semaphore and sets a timeout period.| +| LOS_SemPost | Releases a semaphore.| + + +### How to Develop + +1. Call **LOS_SemCreate** to create a semaphore. To create a binary semaphore, call **LOS_BinarySemCreate**. + +2. Call **LOS_SemPend** to request a semaphore. + +3. Call **LOS_SemPost** to release a semaphore. + +4. Call **LOS_SemDelete** to delete a semaphore. + +> **NOTE**
+> As interrupts cannot be blocked, semaphores cannot be requested in block mode for interrupts. + + +### Development Example + + +### Example Description This example implements the following: -1. Create a semaphore in task **ExampleSem** and lock task scheduling. Create two tasks **ExampleSemTask1** and **ExampleSemTask2** \(with higher priority\). Enable the two tasks to request the same semaphore. Unlock task scheduling. Enable task **ExampleSem** to enter sleep mode for 400 ticks. Release the semaphore in task **ExampleSem**. -2. Enable** ExampleSemTask2** to enter sleep mode for 20 ticks after acquiring the semaphore. \(When **ExampleSemTask2** is delayed, **ExampleSemTask1** is woken up.\) -3. Enable **ExampleSemTask1** to request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks. \(Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended. **ExampleSemTask1** is woken up after 10 ticks.\) Enable **ExampleSemTask1** to request the semaphore in permanent block mode after it is woken up 10 ticks later. \(Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended.\) -4. After 20 ticks, **ExampleSemTask2** is woken up and releases the semaphore. **ExampleSemTask1** acquires the semaphore and is scheduled to run. When **ExampleSemTask1** is complete, it releases the semaphore. -5. Task **ExampleSem** is woken up after 400 ticks and deletes the semaphore. +1. Create a semaphore in task **ExampleSem** and lock task scheduling. Create two tasks **ExampleSemTask1** and **ExampleSemTask2** (with higher priority). Enable the two tasks to request the same semaphore. Unlock task scheduling. Enable task **ExampleSem** to enter sleep mode for 400 ticks. Release the semaphore in task **ExampleSem**. + +2. Enable **ExampleSemTask2** to enter sleep mode for 20 ticks after acquiring the semaphore. (When **ExampleSemTask2** is delayed, **ExampleSemTask1** is woken up.) + +3. Enable **ExampleSemTask1** to request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks. (Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended. **ExampleSemTask1** is woken up after 10 ticks.) Enable **ExampleSemTask1** to request the semaphore in permanent block mode after it is woken up 10 ticks later. (Because the semaphore is still held by **ExampleSemTask2**, **ExampleSemTask1** is suspended.) + +4. After 20 ticks, **ExampleSemTask2** is woken up and releases the semaphore. **ExampleSemTask1** acquires the semaphore and is scheduled to run. When **ExampleSemTask1** is complete, it releases the semaphore. + +5. Task **ExampleSem** is woken up after 400 ticks. After that, delete the semaphore. + + +### Sample Code -### Sample Code +The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **ExampleSem** function is called in **TestTaskEntry**. The sample code is as follows: @@ -144,33 +135,34 @@ static UINT32 g_testTaskId01; static UINT32 g_testTaskId02; /* Task priority */ -#define TASK_PRIO_TEST 5 +#define TASK_PRIO_LOW 5 +#define TASK_PRIO_HI 4 -/* Semaphore structure ID*/ +/* Semaphore structure ID */ static UINT32 g_semId; VOID ExampleSemTask1(VOID) { UINT32 ret; - printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); + dprintf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); - /* Request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks.*/ + /* Request the semaphore in scheduled block mode, with a wait timeout period of 10 ticks. */ ret = LOS_SemPend(g_semId, 10); - - /* The semaphore is acquired.*/ + /* The semaphore is acquired. */ if (ret == LOS_OK) { LOS_SemPost(g_semId); return; } - /* The semaphore is not acquired when the timeout period has expired.*/ + /* The semaphore is not acquired when the timeout period has expired. */ if (ret == LOS_ERRNO_SEM_TIMEOUT) { - printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); + dprintf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); - /* Request the semaphore in permanent block mode.*/ + /* Request the semaphore in permanent block mode. */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); + dprintf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); if (ret == LOS_OK) { + dprintf("ExampleSemTask1 post sem g_semId.\n"); LOS_SemPost(g_semId); return; } @@ -180,20 +172,19 @@ VOID ExampleSemTask1(VOID) VOID ExampleSemTask2(VOID) { UINT32 ret; - printf("ExampleSemTask2 try get sem g_semId wait forever.\n"); + dprintf("ExampleSemTask2 try get sem g_semId wait forever.\n"); - /* Request the semaphore in permanent block mode.*/ + /* Request the semaphore in permanent block mode. */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); + dprintf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); } - /* Enable the task to enter sleep mode for 20 ticks.*/ + /* Enable the task to enter sleep mode for 20 ticks. */ LOS_TaskDelay(20); - printf("ExampleSemTask2 post sem g_semId.\n"); - /* Release the semaphore.*/ + dprintf("ExampleSemTask2 post sem g_semId.\n"); + /* Release the semaphore. */ LOS_SemPost(g_semId); return; } @@ -204,60 +195,65 @@ UINT32 ExampleSem(VOID) TSK_INIT_PARAM_S task1; TSK_INIT_PARAM_S task2; - /* Create a semaphore.*/ + /* Create a semaphore. */ LOS_SemCreate(0, &g_semId); - /* Lock task scheduling.*/ + /* Lock task scheduling. */ LOS_TaskLock(); - /* Create task 1.*/ + /* Create task 1. */ (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pcName = "TestTask1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = TASK_PRIO_TEST; + task1.usTaskPrio = TASK_PRIO_LOW; ret = LOS_TaskCreate(&g_testTaskId01, &task1); if (ret != LOS_OK) { - printf("task1 create failed .\n"); + dprintf("task1 create failed .\n"); return LOS_NOK; } - /* Create task 2.*/ + /* Create task 2. */ (VOID)memset_s(&task2, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pcName = "TestTask2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task2.usTaskPrio = (TASK_PRIO_TEST - 1); + task2.usTaskPrio = TASK_PRIO_HI; ret = LOS_TaskCreate(&g_testTaskId02, &task2); if (ret != LOS_OK) { - printf("task2 create failed.\n"); + dprintf("task2 create failed.\n"); return LOS_NOK; } - /* Unlock task scheduling.*/ + /* Unlock task scheduling. */ LOS_TaskUnlock(); + /* Enable the task to enter sleep mode for 400 ticks. */ + LOS_TaskDelay(400); + ret = LOS_SemPost(g_semId); - /* Enable the task to enter sleep mode for 400 ticks.*/ + /* Enable the task to enter sleep mode for 400 ticks. */ LOS_TaskDelay(400); - /* Delete the semaphore. */ + /* Delete the semaphore. */ LOS_SemDelete(g_semId); return LOS_OK; } ``` -### Verification + +### Verification The development is successful if the return result is as follows: + ``` ExampleSemTask2 try get sem g_semId wait forever. -ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks. ExampleSemTask1 timeout and try get sem g_semId wait forever. +ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask2 post sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId. +ExampleSemTask1 post sem g_semId. ``` - diff --git a/en/device-dev/kernel/kernel-small-start-kernel.md b/en/device-dev/kernel/kernel-small-start-kernel.md index 01c4373ac8b51dc17a9ea91985c98688f4965311..c96beb9191fd8f04aadba8b35b7194fb5d90362e 100644 --- a/en/device-dev/kernel/kernel-small-start-kernel.md +++ b/en/device-dev/kernel/kernel-small-start-kernel.md @@ -3,20 +3,22 @@ ## Kernel Startup Process -The kernel startup process consists of the assembly startup and C language startup, as shown in the following figure. +The kernel startup process consists of the assembly startup and C language startup, as shown in **Figure 1**. The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language. -The C language startup involves the following operations: starting the **OsMain** function and starting scheduling. As shown in the following figure, the **OsMain** function is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. The table below describes each phase. +The C language startup involves the following operations: starting the **OsMain** function and starting scheduling. +**OsMain()** is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. **Table 1** describes each phase. - **Figure 1** Kernel startup process
- ![](figures/kernel-startup-process-2.png "kernel-startup-process-2") +**Figure 1** Kernel startup process +![](figures/kernel-startup-process-2.png "kernel-startup-process-2") - **Table 1** Start framework -| Level | Startup Description | +**Table 1** Kernel startup framework + +| API| Description| | -------- | -------- | | LOS_INIT_LEVEL_EARLIEST | Earliest initialization.
The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.
Example: trace module| | LOS_INIT_LEVEL_ARCH_EARLY | Early initialization of the architecture.
The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at **LOS_INIT_LEVEL_ARCH**.| @@ -28,54 +30,52 @@ The C language startup involves the following operations: starting the **OsMain* | LOS_INIT_LEVEL_KMOD_BASIC | Initialization of the kernel basic modules.
Initialize the basic modules that can be detached from the kernel.
Example: VFS initialization| | LOS_INIT_LEVEL_KMOD_EXTENDED | Initialization of the kernel extended modules.
Initialize the extended modules that can be detached from the kernel.
Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC| | LOS_INIT_LEVEL_KMOD_TASK | Kernel task creation.
Create kernel tasks (kernel tasks and software timer tasks).
Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task| +| LOS_INIT_LEVEL_FINISH | Complete of the kernel initialization.| -## Programming Example +## Development Example **Example Description** Add a kernel module and register the initialization function of the module to the kernel startup process through the kernel startup framework, so as to complete the module initialization during the kernel initialization process. +You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**. **Sample Code** - - -``` +```c /* Header file of the kernel startup framework */ #include "los_init.h" -... /* Initialization function of the new module */ unsigned int OsSampleModInit(void) { PRINTK("OsSampleModInit SUCCESS!\n"); - ...... } -... + /* Register the new module at the target level of the kernel startup framework. */ LOS_MODULE_INIT(OsSampleModInit, LOS_INIT_LEVEL_KMOD_EXTENDED); ``` - **Verification** - - ``` + main core booting up... + +/* The print information may vary depending on the running environment. */ +... + +/* Print the initialization function of the new module in the test code. */ OsSampleModInit SUCCESS! -releasing 1 secondary cores -cpu 1 entering scheduler -cpu 0 entering scheduler ``` -According to the information displayed during the system startup, the kernel has called the initialization function of the registered module during the startup to initialize the module. +According to the information displayed during the system startup, the kernel calls the initialization function of the registered module during the startup to initialize the module. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> -> Modules at the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required. -> +> **NOTE** +> +> Modules of the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required. +> > You can view the symbol table in the **.rodata.init.kernel.*** segment of the **OHOS_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect. diff --git a/en/device-dev/kernel/kernel-small-start-user.md b/en/device-dev/kernel/kernel-small-start-user.md index 40f586e1576f07bd9223d03aa2fbc7681cec086d..96535ef581fb6edcdde458f94085e65cdd04b034 100644 --- a/en/device-dev/kernel/kernel-small-start-user.md +++ b/en/device-dev/kernel/kernel-small-start-user.md @@ -1,17 +1,21 @@ # Startup in User Mode -## Startup of the Root Process in User Mode + +## Startup of the Root Process in User Mode The root process is the first user-mode process in the system. The process ID is 1. The root process is the ancestor of all user-mode processes. -**Figure 1** Process tree +**Figure 1** Process tree + ![](figures/process-tree.png "process-tree") -### Startup Process of the Root Process + +### Startup Process of the Root Process Use the link script to place the following init startup code to the specified location in the system image. -``` + +```c #define LITE_USER_SEC_ENTRY __attribute__((section(".user.entry"))) LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) { @@ -23,38 +27,38 @@ LITE_USER_SEC_ENTRY VOID OsUserInit(VOID *args) } ``` -During system startup, **OsUserInitProcess** is called to start the **init** process. The procedure is as follows: +> **NOTE** +> +> The preceeding code is in **kernel/liteos_a/kernel/user/src/los_user_init.c**. The value of **g_initPath** can be **/dev/shm/init** or **/bin/init**, depending on the startup settings. -1. The kernel calls **OsLoadUserInit** to load the code. -2. A process space is created to start the **/bin/init** process. +Use **OsUserInitProcess** to start the **init** process. The procedure is as follows: -### Responsibilities of the Root Process +1. The kernel calls **OsLoadUserInit** to load the code for startup. -- Starts key system programs or services, such as shell. +2. A process space is created to start the **/bin/init** process. - >![](../public_sys-resources/icon-note.gif) **NOTE** - > - >In OpenHarmony, the **init** process reads the **/etc/init.cfg** file and runs specified commands or starts specified processes based on configurations. For details, see [init Module](../subsystems/subsys-boot-init-cfg.md). +### Responsibilities of the Root Process -- Monitors the process for reclaiming the orphan process and clears the zombie processes in child processes. +- The root process starts key system programs or services, such as shell. + > **NOTE** + > In OpenHarmony, the **init** process reads **/etc/init.cfg** and runs commands or starts processes based on the configuration. For details, see [init Configuration File](../subsystems/subsys-boot-init-cfg.md). -## Running Programs in User Mode +- The root process monitors the process for reclaiming the orphan process and clears the zombie processes in child processes. -A user-mode program can be started in either of the following ways: - -- Run the shell command to start the process. - - ``` - OHOS $ exec helloworld - OHOS $ ./helloworld - OHOS $ /bin/helloworld - ``` +## Running Programs in User Mode +A user-mode program can be started in either of the following ways: -- Start a new process by calling the POSIX API. +- Using shell commands - Use the **Fork\(\)** method to create a process, and call the **exec\(\)** method to execute a new process. + ``` + OHOS $ exec helloworld + OHOS $ ./helloworld + OHOS $ /bin/helloworld + ``` +- Using POSIX APIs + Use **Fork()** to create a process, and call **exec()** to execute a process. diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001275267040.png b/en/device-dev/quick-start/figures/en-us_image_0000001275267040.png deleted file mode 100644 index 204894213329c4de1edf74d869c1bfd8e8e78d04..0000000000000000000000000000000000000000 Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001275267040.png and /dev/null differ diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001285965546.png b/en/device-dev/quick-start/figures/en-us_image_0000001285965546.png deleted file mode 100644 index f07b21dbc89b6722f6374a8bde9bdc893798f120..0000000000000000000000000000000000000000 Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001285965546.png and /dev/null differ diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001285965778.png b/en/device-dev/quick-start/figures/en-us_image_0000001285965778.png deleted file mode 100644 index 6aa63a6876293a994ffe1cc90f6973a949e9e43a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001285965778.png and /dev/null differ diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001326386753.png b/en/device-dev/quick-start/figures/en-us_image_0000001326386753.png deleted file mode 100644 index 97d98319b294e132d43cd4f75a2cc8031995b99f..0000000000000000000000000000000000000000 Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001326386753.png and /dev/null differ diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001338012765.png b/en/device-dev/quick-start/figures/en-us_image_0000001338012765.png index 7848b0336d1c8fb4e9b8f38e94b8308453b2b464..c9553f714d09d1dae9559eb86bbb801d32d08141 100644 Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001338012765.png and b/en/device-dev/quick-start/figures/en-us_image_0000001338012765.png differ diff --git a/en/device-dev/quick-start/quickstart-ide-env-ubuntu.md b/en/device-dev/quick-start/quickstart-ide-env-ubuntu.md index fb65184467734cd3a8930d68c0247d9cd0b92f1b..7f2c7f416b0e3ec6b49af69ad002a1e8c6cff6a5 100644 --- a/en/device-dev/quick-start/quickstart-ide-env-ubuntu.md +++ b/en/device-dev/quick-start/quickstart-ide-env-ubuntu.md @@ -13,10 +13,12 @@ The following describes how to set up the Ubuntu environment. ## System Requirements -- Ubuntu: Ubuntu 18.04 to 21.10; version 20.04 with 16 GB or larger memory is recommended +- Ubuntu: Ubuntu 18.04 to 21.10; version 20.04 with 16 GB or larger memory and a 100 GB or larger hard disk is recommended - User name (Ubuntu): cannot contain Chinese characters +- DevEco Device Tool: latest and same version installed on both Ubuntu and Windows + ## Procedure @@ -28,6 +30,7 @@ The following describes how to set up the Ubuntu environment. ``` ![en-us_image_0000001226764302](figures/en-us_image_0000001226764302.png) + 2. Start the command-line tool, run the following command, enter your password, and select **No** to set **Ubuntu shell** to **bash**. ```shell @@ -36,24 +39,24 @@ The following describes how to set up the Ubuntu environment. ![ubuntu-dash-to-bash](figures/ubuntu-dash-to-bash.png) -2. Download the [DevEco Device Tool 3.0 Release](https://device.harmonyos.com/cn/ide#download) Linux edition. +2. Download the latest version of [DevEco Device Tool](https://device.harmonyos.com/cn/ide#download) for Linux. 3. Decompress the DevEco Device Tool software package and assign permission on the folder obtained from the decompression. - 1. Go to the directory where the DevEco Device Tool software package is stored and run the following command to decompress the software package. In the command, change **devicetool-linux-tool-3.1.0.300.zip** to the actual software package name. + 1. Go to the directory where the DevEco Device Tool software package is stored and run the following command to decompress the software package. In the command, **devicetool-linux-tool-{Version}.zip** indicates the software package name. ```shell - unzip devicetool-linux-tool-3.1.0.300.zip + unzip devicetool-linux-tool-{Version}.zip ``` - 2. Open the folder of the decompressed software package and run the following command to grant the execute permission on the installation file. In the command, change **devicetool-linux-tool-3.1.0.300.sh** to the actual installation file name. + 2. Open the folder of the decompressed software package and run the following command to grant the execute permission on the installation file. In the command, **devicetool-linux-tool-{Version}.sh** indicates the installation file name. ```shell - chmod u+x devicetool-linux-tool-3.1.0.300.sh + chmod u+x devicetool-linux-tool-{Version}.sh ``` -4. Run the following command to install DevEco Device Tool, where **devicetool-linux-tool-3.1.0.300.sh** indicates the installation file name. +4. Run the following command to install DevEco Device Tool, where **devicetool-linux-tool-{Version}.sh** indicates the installation file name. ```shell - sudo ./devicetool-linux-tool-3.1.0.300.sh + sudo ./devicetool-linux-tool-{Version}.sh ``` 5. On the page for agreeing to the user agreement and privacy statement, read and agree to the user agreement and privacy statement. You can scroll through the options by pressing the up and down arrow keys on the keyboard. diff --git a/en/device-dev/quick-start/quickstart-ide-env-win.md b/en/device-dev/quick-start/quickstart-ide-env-win.md index 51ffa98a5d0a7ec388016e738f1c30f6adc6c773..cf7a0879bb76b86c5c798c62963b88fc8356a5d3 100644 --- a/en/device-dev/quick-start/quickstart-ide-env-win.md +++ b/en/device-dev/quick-start/quickstart-ide-env-win.md @@ -8,54 +8,36 @@ The following describes how to set up the Windows environment. ## System Requirements -- OS: 64-bit Windows 10 +- Windows 10 (64-bit): 8 GB or larger memory and a 100 GB or larger hard disk recommended -- DevEco Device Tool: 3.1 Beta1 +- DevEco Device Tool: latest and same version installed on both Windows and Ubuntu ## Procedure -1. Download the [DevEco Device Tool 3.1 Beta1](https://device.harmonyos.com/cn/ide#download) Windows edition. +1. Download the latest version of [DevEco Device Tool](https://device.harmonyos.com/cn/ide#download) for Windows. 2. Decompress the DevEco Device Tool package, double-click the installer, and then click **Next**. -3. Set the installation path for DevEco Device Tool and click **Next**. Make sure the path does not contain Chinese characters and is in a drive other than the C drive. +3. On the page shown, read the user agreement and privacy statement carefully and select **I accept the licenses** before proceeding to the next step. - ![en-us_image_0000001326386753](figures/en-us_image_0000001326386753.png) +4. Set the installation path for DevEco Device Tool and click **Next**. Make sure the path does not contain Chinese characters and is **in a drive other than the C drive**. -4. When prompted, select the tools to be automatically installed. - 1. On the **VSCode installation confirm** page, select **Install VS Code 1.62.2 automatically** and click **Next**. - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** - > - > If Visual Studio Code 1.62 or later has been installed, this step will be skipped. - +5. Install the dependent tools by following the onscreen instructions. - ![en-us_image_0000001285965546](figures/en-us_image_0000001285965546.png) - - 2. Select the Visual Studio Code installation path and click Next. + You can select **Install** or **Custom** as needed: - ![select-vscode-path](figures/select-vscode-path.png) + - **Install**: Install the software based on the default path and parameters. + + - **Custom**: You can customize the installation path and other parameters before the installation. - 2. On the displayed **Python select page**, select **Download from Huawei mirror** and click **Next**. - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** - > - > If Python 3.8 or 3.9 has been installed, select **Use one of compatible on your PC**. - - ![en-us_image_0000001285965778](figures/en-us_image_0000001285965778.png) - -5. When the page shown below is displayed, click **Next**. - - ![en-us_image_0000001285806330](figures/en-us_image_0000001285806330.png) - -6. On the page shown below, read the user agreement and privacy statement carefully and select **I accept the licenses** before proceeding to the next step. - - ![en-us_image_0000001275586896](figures/en-us_image_0000001275586896.png) + After the installation is complete, the status of the dependent tools should be **OK**. + +6. Click **Install** to install DevEco Device Tool. 7. Wait for the DevEco Device Tool setup wizard to automatically install DevEco Device Tool. After the installation is complete, click **Finish** to close the setup wizard. - ![en-us_image_0000001275267040](figures/en-us_image_0000001275267040.png) - 8. From Visual Studio Code, access the DevEco Device Tool page. Now you can conduct your development in DevEco Device Tool. ![en-us_image_0000001338012765](figures/en-us_image_0000001338012765.png) diff --git a/en/device-dev/quick-start/quickstart-pkg-3568-helloworld.md b/en/device-dev/quick-start/quickstart-pkg-3568-helloworld.md index 91826305d91d3eb1caa53563429d0e2a4661283b..014bacde40feaa20ac9c6d6fbb3c2942ba6e8a89 100644 --- a/en/device-dev/quick-start/quickstart-pkg-3568-helloworld.md +++ b/en/device-dev/quick-start/quickstart-pkg-3568-helloworld.md @@ -1,16 +1,18 @@ # Writing a Hello World Program -The following exemplifies how to run the first program on the development board. The created program outputs the message "Hello World!" +The following exemplifies how to run the first program on the development board. The created program outputs the message "Hello World!". + ## Example Directory +Obtain the OpenHarmony project code. From the source code root directory, add the **sample/hello** directory, and then create therein the **hello** source code directory, the build file **BUILD.gn**, and the component configuration file **bundle.json**. The complete code directory is as follows: ``` -applications/sample/hello +sample/hello │── BUILD.gn │── include │ └── helloworld.h @@ -27,11 +29,11 @@ vendor/hihope ## How to Develop -Perform the steps below in the source code directory: +Perform the steps below in the source code root directory: 1. Create a directory and write the service code. - Create the **applications/sample/hello/src/helloworld.c** directory and file whose code is shown in the following example. You can customize the content to be printed. For example, you can change **World** to **OHOS**. Declare the string printing function **HelloPrint** in the **helloworld.h** file. You can use either C or C++ to develop a program. + Create the **sample/hello/src/helloworld.c** file, with the sample code as follows. In this example, the content to be printed is **World**, which you can change to any string that you prefer, for example, **OHOS**. The print function **HelloPrint** is declared in the included **helloworld.h** file. You can use either C or C++ to develop a program. ``` @@ -52,7 +54,7 @@ Perform the steps below in the source code directory: } ``` - Add the header file **applications/sample/hello/include/helloworld.h**. The sample code is as follows: + Add the header file **sample/hello/include/helloworld.h**. The sample code is as follows: ``` @@ -75,85 +77,117 @@ Perform the steps below in the source code directory: ``` 2. Create a build file. - 1. Create the **applications/sample/hello/BUILD.gn** file. The file content is as follows: - - ``` - import("//build/ohos.gni") # Import the build template. - ohos_executable("helloworld") {# Executable module. - sources = [ # Source code of the module. - "src/helloworld.c" - ] - include_dirs = [ # Directory of header files on which the module depends. - "include" - ] - cflags = [] - cflags_c = [] - cflags_cc = [] - ldflags = [] - configs = [] - deps =[] # Internal dependencies of a component. - part_name = "hello" # Component name. This parameter is mandatory. - install_enable = true # Whether to install the software by default. This parameter is optional. By default, the software is not installed. - } - ``` - 2. Create the **applications/sample/hello/bundle.json** file and add the description of the **sample** component. The content is as follows: - - ``` - { - "name": "@ohos/hello", - "description": "Hello world example.", - "version": "3.1", - "license": "Apache License 2.0", - "publishAs": "code-segment", - "segment": { - "destPath": "applications/sample/hello" + + Create the **sample/hello/BUILD.gn** file. For details, see [Module](../subsystems/subsys-build-module.md). + + The content of the **BUILD.gn** file is as follows: + + ``` + import("//build/ohos.gni") # Import the build template. + ohos_executable("helloworld") {# Executable module. + sources = [ # Source code of the module. + "src/helloworld.c" + ] + include_dirs = [ # Directory of header files on which the module depends. + "include" + ] + cflags = [] + cflags_c = [] + cflags_cc = [] + ldflags = [] + configs = [] + deps =[] # Internal dependencies of a component. + part_name = "hello" # Component name. This parameter is mandatory. + install_enable = true # Whether to install the software by default. This parameter is optional. By default, the software is not installed. + } + ``` + +3. Create a component configuration file. + + Create the **sample/hello/bundle.json** file and add the **sample** component description therein. For details, see [Component](../subsystems/subsys-build-component.md). + + The content of the **bundle.json** file is as follows: + + ``` + { + "name": "@ohos/hello", + "description": "Hello world example.", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "sample/hello" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "hello", + "subsystem": "sample", + "syscap": [], + "features": [], + "adapted_system_type": [ "mini", "small", "standard" ], + "rom": "10KB", + "ram": "10KB", + "deps": { + "components": [], + "third_party": [] }, - "dirs": {}, - "scripts": {}, - "component": { - "name": "hello", - "subsystem": "sample", - "syscap": [], - "features": [], - "adapted_system_type": [ "mini", "small", "standard" ], - "rom": "10KB", - "ram": "10KB", - "deps": { - "components": [], - "third_party": [] - }, - "build": { - "sub_component": [ - "//applications/sample/hello:helloworld" - ], - "inner_kits": [], - "test": [] - } + "build": { + "sub_component": [ + "//sample/hello:helloworld" + ], + "inner_kits": [], + "test": [] } } - ``` + } + ``` - The **bundle.json** file consists of two parts. The first part describes the information about the subsystem to which the component belongs, and the second part defines the build configuration for the component. When adding a component, you must specify the **sub_component** of the component. If there are APIs provided for other components, add them in **inner_kits**. If there are test cases, add them in **test**. + The **bundle.json** file consists of two parts. The first part describes the information about the subsystem to which the component belongs, and the second part defines the build configuration for the component. When adding a component, you must specify the **sub_component** of the component. Add the APIs provided for other components, if any, in **inner_kits**. Add the test cases, if any, in **test**. -3. Modify the subsystem configuration file. +4. Modify the subsystem configuration file. - Add the configuration of the new subsystem to the **build/subsystem_config.json** file. - + Add the configuration of the new subsystem to the **build/subsystem_config.json** file. For details, see [Subsystem](../subsystems/subsys-build-subsystem.md). + + The configuration of the new subsystem is as follows: ``` "sample": { - "path": "applications/sample/hello", + "path": "sample", "name": "sample" }, ``` -4. Modify the product configuration file. +5. Modify the product configuration file. + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > In versions earlier than OpenHarmony-v3.2-Beta2, the RK3568 configuration file is **productdefine/common/products/rk3568.json**. In OpenHarmony-v3.2-Beta2 and later versions, the RK3568 configuration file is **vendor/hihope/rk3568/config.json**. - In the **vendor/hihope/rk3568/config.json** file, add the **hello** part after the existing part. + - Versions earlier than OpenHarmony-v3.2-Beta2 + + In the **productdefine/common/products/rk3568.json** file, add the **hello** part after the existing part. - ``` + ``` "usb:usb_manager_native":{}, "applications:prebuilt_hap":{}, "sample:hello":{}, "wpa_supplicant-2.9:wpa_supplicant-2.9":{}, - ``` + ``` + + - OpenHarmony-v3.2-Beta2 and later versions + + + In the **vendor/hihope/rk3568/config.json** file, add the **hello** part after the existing part. + + ``` + { + "subsystem": "sample", + "components": [ + { + "component": "hello", + "features": [] + } + ] + }, + ``` diff --git a/en/readme/telephony.md b/en/readme/telephony.md index 78b7169591cad3eec673cb1e4cf1d70135931ba5..158478174026532fdb1ee95f536f72c3fc5e2eae 100755 --- a/en/readme/telephony.md +++ b/en/readme/telephony.md @@ -36,7 +36,7 @@ base/telephony/ ## Constraints 1. The open-source version currently provides the cellular call (CS call only), SMS & MMS, and cellular data services and supports the dual-SIM framework. -2. The Hardware Device Interface (HDI) support is subject to the chip vendors' adaptation capability. For details, see [Telephony Development](../device-dev/subsystems/subsys-tel-guide). +2. The Hardware Device Interface (HDI) support is subject to the chip vendors' adaptation capability. For details, see [Telephony Development](../device-dev/subsystems/subsys-tel-overview.md). ## Usage Guidelines diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-security.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-security.md index 970c73c2bdbe4ac56682e6ff8266c9f73f31f658..4bd1acf87dcc5940947215d8c3dd3d459d0c49bc 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-security.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-security.md @@ -1,6 +1,6 @@ # Security Subsystem ChangeLog -## cl.security.1 setSeed API Change of Random from Asynchronous to Synchronous +## cl.security.1 Change of the setSeed API of Random from Asynchronous to Synchronous **Change Impacts** @@ -8,422 +8,468 @@ Behavior of released JavaScript APIs will be changed. The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - -API prototype before change: - -- setSeed(seed : DataBlob, callback : AsyncCallback\) : void; -- setSeed(seed : DataBlob) : Promise\; - -API prototype after change: - +API prototype before the change: +setSeed(seed : DataBlob, callback : AsyncCallback\) : void; +setSeed(seed : DataBlob) : Promise\; +API prototype after the change: setSeed(seed : DataBlob) : void; **Adaptation Guide** - -See the API adaptation guide of **setSeed** in the API reference: [Crypto Framework - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cryptoFramework.md) +See the API adaptation guide of **setSeed** in the API reference: +[Crypto Framework - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cryptoFramework.md) ## cl.security.2 Migration of interface DataArray from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface DataArray** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.3 Migration of interface EncodingFormat from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface EncodingFormat** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.4 Migration of interface EncodingBlob from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface EncodingBlob** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.5 Migration of interface CertChainData from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface CertChainData** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.6 Migration of interface X509Cert from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface X509Cert** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.7 Migration of function createX509Cert from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **function createX509Cert** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.8 Migration of interface X509CrlEntry from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts. **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface X509CrlEntry** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.9 Migration of interface X509Crl from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface X509Crl** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.10 Migration of function createX509Crl from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **function createX509Crl** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.11 Migration of interface CertChainValidator from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **interface CertChainValidator** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) ## cl.security.12 Migration of function createCertChainValidator from @ohos.security.cryptoFramework.d.ts to @ohos.security.cert.d.ts **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - Migrated **function createCertChainValidator** from **@ohos.security.cryptoFramework.d.ts** to **@ohos.security.cert.d.ts**. **Adaptation Guide** - Import and use the new .d.ts file: - import cryptoCert from '@ohos.security.cert'; - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -## cl.security.13 getPublicKey API Change of X509Cert from Asynchronous to Synchronous +## cl.security.13 Change of the getPublicKey API of X509Cert from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - -API prototype before change: - -- getPublicKey(callback : AsyncCallback\) : void; -- getPublicKey() : Promise\; - -API prototype after change: - +API prototype before the change: +getPublicKey(callback : AsyncCallback\) : void; +getPublicKey() : Promise\; +API prototype after the change: getPublicKey() : cryptoFramework.PubKey; **Adaptation Guide** - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -## cl.security.14 checkValidityWithDate API Change of X509Cert from Asynchronous to Synchronous +## cl.security.14 Change of the checkValidityWithDate API of X509Cert from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** - -API prototype before change: - -- checkValidityWithDate(date: string, callback : AsyncCallback\) : void; -- checkValidityWithDate(date: string) : Promise\; - -API prototype after change: - +API prototype before the change: +checkValidityWithDate(date: string, callback : AsyncCallback\) : void; +checkValidityWithDate(date: string) : Promise\; +API prototype after the change: checkValidityWithDate(date: string) : void; **Adaptation Guide** - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -## cl.security.15 getCertIssuer API Change of X509CrlEntry from Asynchronous to Synchronous +## cl.security.15 Change of the getCertIssuer API of X509CrlEntry from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** +API prototype before the change: +getCertIssuer(callback : AsyncCallback\) : void; +getCertIssuer() : Promise\; -API prototype before change: - -- getCertIssuer(callback : AsyncCallback\) : void; -- getCertIssuer() : Promise\; - -API prototype after change: - +API prototype after the change: getCertIssuer() : DataBlob; **Adaptation Guide** - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -## cl.security.16 getRevocationDate API Change of X509CrlEntry from Asynchronous to Synchronous +## cl.security.16 Change of the getRevocationDate API of X509CrlEntry from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** +API prototype before the change: +getRevocationDate(callback : AsyncCallback\) : void; +getRevocationDate() : Promise\; -API prototype before change: - -- getRevocationDate(callback : AsyncCallback\) : void; -- getRevocationDate() : Promise\; - -API prototype after change: - +API prototype after the change: getRevocationDate() : string; **Adaptation Guide** +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) - -## cl.security.17 isRevoked API Change of X509Crl from Asynchronous to Synchronous +## cl.security.17 Change of the isRevoked API of X509Crl from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** +API prototype before the change: +isRevoked(cert : X509Cert, callback : AsyncCallback\) : void; +isRevoked(cert : X509Cert) : Promise\; -API prototype before change: - -- isRevoked(cert : X509Cert, callback : AsyncCallback\) : void; -- isRevoked(cert : X509Cert) : Promise\; - -API prototype after change: - +API prototype after the change: isRevoked(cert : X509Cert) : boolean; **Adaptation Guide** - -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -## cl.security.18 getRevokedCert API Change of X509Crl from Asynchronous to Synchronous +## cl.security.18 Change of the getRevokedCert API of X509Crl from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** +API prototype before the change: +getRevokedCert(serialNumber : number, callback : AsyncCallback\) : void; +getRevokedCert(serialNumber : number) : Promise\; -API prototype before change: +API prototype after the change: +getRevokedCert(serialNumber : number) : X509CrlEntry; -- getRevokedCert(serialNumber : number, callback : AsyncCallback\) : void; -- getRevokedCert(serialNumber : number) : Promise\; +**Adaptation Guide** +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -API prototype after change: -getRevokedCert(serialNumber : number) : X509CrlEntry; +## cl.security.19 Change of the getRevokedCertWithCert API of X509Crl from Asynchronous to Synchronous +**Change Impacts** -**Adaptation Guide** +Behavior of released JavaScript APIs will be changed. +The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +**Key API/Component Changes** +API prototype before the change: +getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback\) : void; +getRevokedCertWithCert(cert : X509Cert) : Promise\; +API prototype after the change: +getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry; -## cl.security.19 getRevokedCertWithCert API Change of X509Crl from Asynchronous to Synchronous +**Adaptation Guide** +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) + + +## cl.security.20 Change of the getTbsInfo API of X509Crl from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. - The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. **Key API/Component Changes** +API prototype before the change: +getTbsInfo(callback : AsyncCallback\) : void; +getTbsInfo() : Promise\; -API prototype before change: +API prototype after the change: +getTbsInfo() : DataBlob; -- getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback\) : void; -- getRevokedCertWithCert(cert : X509Cert) : Promise\; +**Adaptation Guide** +See the corresponding API adaptation guide in the API reference: +[Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) -API prototype after change: +## cl.security.21 Support of No-Hash Signing Mode for HUKS -getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry; +Before the change, the application passes **huks.HuksTag.HUKS_TAG_DIGEST = huks.HuksKeyDigest.HUKS_DIGEST_NONE** and HUKS uses **huks.HuksKeyDigest.HUKS_DIGEST_SHA256** for processing by default. After the change, the application passes **huks.HuksTag.HUKS_TAG_DIGEST = huks.HuksKeyDigest.HUKS_DIGEST_NONE** and HUKS does not perform digest processing by default. In this case, the service needs to perform the hash operation on the original data and then pass the hashed digest to HUKS for signing or signature verification. -**Adaptation Guide** +**Change Impacts** + +Behavior of released JavaScript APIs will be changed. +The application needs to adapt these APIs so that the signing or signature verification result can be passed before and after the change. + +**Key API/Component Changes** + +Released JavaScript APIs remain unchanged, but parameter sets passed to the APIs are changed. + +The service uses the No-Hash signing mode, and needs to hash the original data and then pass the hashed digest to the signing or signature verification API of HUKS. In addition, the **huks.HuksTag.HUKS_TAG_DIGEST** parameter is set to **huks.HuksKeyDigest.HUKS_DIGEST_NONE**. -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +**Adaptation Guide** +Take signing as an example. The sample code is as follows: + +```js +import huks from '@ohos.security.huks'; + +let keyAlias = 'rsa_Key'; +/* Digest value after SHA-256 encryption */ +let inDataAfterSha256 = new Uint8Array( + 0x4B, 0x1E, 0x22, 0x64, 0xA9, 0x89, 0x60, 0x1D, 0xEC, 0x78, 0xC0, 0x5D, 0xBE, 0x46, 0xAD, 0xCF, + 0x1C, 0x35, 0x16, 0x11, 0x34, 0x01, 0x4E, 0x9B, 0x7C, 0x00, 0x66, 0x0E, 0xCA, 0x09, 0xC0, 0xF3, +); +/* Signing parameters */ +let signProperties = new Array(); +signProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA, +} +signProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN +} +signProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048, +} +signProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, // Set digest-none. +} +let signOptions = { + properties: signProperties, + inData: inDataAfterSha256 // Set the value after hashing. +} + +huks.initSession(keyAlias, signOptions); +``` + +For sample codes of other APIs, see [HUKS guidelines](../../../application-dev/security/huks-guidelines.md) and [HUKS APIs](../../../application-dev/reference/apis/js-apis-huks.md). + +## cl.security.22 Support of Key Calculation Parameter Specification for HUKS During Key Usage + +Before the change, all parameters for key calculation must be specified when the application generates a key. After the change, only mandatory parameters need to be specified when the application generates a key, and other parameters can be specified when the key is used. The application can specify key calculation parameters more flexibly. -## cl.security.20 getTbsInfo API Change of X509Crl from Asynchronous to Synchronous **Change Impacts** Behavior of released JavaScript APIs will be changed. -The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. +The application can specify only mandatory parameters when creating a key and specify other optional parameters when using the key. **Key API/Component Changes** -API prototype before change: +Released JavaScript APIs remain unchanged, but parameter sets passed to the APIs are changed and parameters are classified into mandatory parameters and optional parameters. For details, see [HUKS guidelines](../../../application-dev/security/huks-guidelines.md). -- getTbsInfo(callback : AsyncCallback\) : void; -- getTbsInfo() : Promise\; +huks.generateKeyItem -API prototype after change: +huks.importKeyItem -getTbsInfo() : DataBlob; +huks.importWrappedKeyItem -**Adaptation Guide** +huks.initSession -See the corresponding API adaptation guide in the API reference: [Certificate - API Reference](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cert.md) +huks.updateSession + +huks.finishSession + +**Adaptation Guide** - \ No newline at end of file +Take key generation as an example. The sample code is as follows: + +```js +let keyAlias = 'keyAlias'; +let properties = new Array(); +// Mandatory parameter. +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +// Mandatory parameter. +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 +}; +// Mandatory parameter. +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +// Optional parameter. If this parameter is not specified when a key is generated, it must be specified when the key is used. +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` + +For sample codes of other APIs, see [HUKS guidelines](../../../application-dev/security/huks-guidelines.md) and [HUKS APIs](../../../application-dev/reference/apis/js-apis-huks.md). diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md new file mode 100644 index 0000000000000000000000000000000000000000..6d5ce737601297172bcf6fedf268705102e1053d --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md @@ -0,0 +1,36 @@ +# Account Subsystem ChangeLog + +## cl.account_os_account.1 createOsAccountForDomain Error Code Change + +Changed the error code returned when the **createOsAccountForDomain** API is used to create a domain account that already exists from **12300001** to **12300004**. +The error information is changed from a common system error to an error indicating that the account already exists. + +**Change Impacts** + +The application developed based on earlier versions needs to adapt the new error code. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** +- AccountManager + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>); + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo>; + +**Adaptation Guide** + +The sample code for returning an error when a domain account is repeatedly created is as follows: + +```ts +import account_osAccount from "@ohos.account.osAccount" +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +let accountMgr = account_osAccount.getAccountManager(); +let domainInfo = { + accountName: "zhangsan", + domain: "china.example.com" +}; +try { + await accountMgr.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo); + await accountMgr.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo); +} catch (err) { + expect(err.code).assertEqual(12300004); +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-nfc.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-nfc.md new file mode 100644 index 0000000000000000000000000000000000000000..a2499c7699ae3f6742ff3bc4e8bb96a879e73c36 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-nfc.md @@ -0,0 +1,62 @@ +# ChangeLog of NFC JS API Changes in the Communication Subsystem + +Compared with OpenHarmony 3.2 Beta4, OpenHarmony 3.2.10.2(Mr) has the following API changes in the distributed data management subsystem. + +## cl.nfc.1 API Change +Some NFC JS APIs in API versions 6 to 8 cannot throw error codes and need to be deprecated and deleted, and then APIs in API version 9 are used instead. + +You need to adapt your application based on the following information. + + **Change Impacts** + +Some JS APIs in API versions 6 to 8 are affected. Your application needs to adapt new APIs so that it can properly implement functions in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Class | Method/Attribute/Enumeration/Constant| Change Type| +| -------------------------------- | ------------- | ------------------- | -------- | +| api/@ohos.nfc.cardEmulation.d.ts | cardEmulation | FeatureType | Deprecated | +| api/@ohos.nfc.cardEmulation.d.ts | cardEmulation | isSupported | Deprecated | +| api/@ohos.nfc.cardEmulation.d.ts | cardEmulation | hasHceCapability | Added | +| api/@ohos.nfc.controller.d.ts | nfcController | isNfcAvailable | Deprecated | +| api/@ohos.nfc.controller.d.ts | nfcController | openNfc | Deprecated | +| api/@ohos.nfc.controller.d.ts | nfcController | closeNfc | Deprecated | +| api/@ohos.nfc.controller.d.ts | nfcController | enableNfc | Added | +| api/@ohos.nfc.controller.d.ts | nfcController | disableNfc | Added | +| api/@ohos.nfc.tag.d.ts | tag | getNfcATag | Deprecated | +| api/@ohos.nfc.tag.d.ts | tag | getNfcBTag | Deprecated | +| api/@ohos.nfc.tag.d.ts | tag | getNfcFTag | Deprecated | +| api/@ohos.nfc.tag.d.ts | tag | getNfcVTag | Deprecated | +| api/@ohos.nfc.tag.d.ts | tag | getNfcA | Added | +| api/@ohos.nfc.tag.d.ts | tag | getNfcB | Added | +| api/@ohos.nfc.tag.d.ts | tag | getNfcF | Added | +| api/@ohos.nfc.tag.d.ts | tag | getNfcV | Added | +| api/tag/tagSession.d.ts | TagSession | getTagInfo | Deprecated | +| api/tag/tagSession.d.ts | TagSession | connectTag | Deprecated | +| api/tag/tagSession.d.ts | TagSession | reset | Deprecated | +| api/tag/tagSession.d.ts | TagSession | isTagConnected | Deprecated | +| api/tag/tagSession.d.ts | TagSession | setSendDataTimeout | Deprecated | +| api/tag/tagSession.d.ts | TagSession | getSendDataTimeout | Deprecated | +| api/tag/tagSession.d.ts | TagSession | sendData | Deprecated | +| api/tag/tagSession.d.ts | TagSession | getMaxSendLength | Deprecated | +| api/tag/tagSession.d.ts | TagSession | connect | Added | +| api/tag/tagSession.d.ts | TagSession | resetConnection | Added | +| api/tag/tagSession.d.ts | TagSession | isConnected | Added | +| api/tag/tagSession.d.ts | TagSession | setTimeout | Added | +| api/tag/tagSession.d.ts | TagSession | getTimeout | Added | +| api/tag/tagSession.d.ts | TagSession | transmit | Added | +| api/tag/tagSession.d.ts | TagSession | getMaxTransmitSize | Added | + +**Adaptation Guide** + +View the following API references: +[@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-cardEmulation.md) + +[@ohos.nfc.controller (Standard NFC)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-nfcController.md) + +[@ohos.nfc.tag (Standard NFC Tags)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-nfcTag.md) + +[tagSession (Standard NFC Tag Session)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-tagSession.md) +``` + +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-inputmethod-framworks.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-inputmethod-framworks.md new file mode 100644 index 0000000000000000000000000000000000000000..3318c618bd3cb511da78865aa85a779c689673fb --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-inputmethod-framworks.md @@ -0,0 +1,31 @@ +# Input Method Framework ChangeLog + +## cl.inputmethod_frameworks.1 API Filename Change + +The following modules do not comply with the OpenHarmony API file naming rules. Therefore, they are modified in API version 9 and later. + +**Change Impacts** + +The SDK after the change is incompatible with the earlier versions. Therefore, adaptation is required for applications developed in earlier versions so that they can be properly built with the SDK in the new version. + +**Key API/Component Changes** + +| Module| File Name Before Change| File Name After Change| +|------|--------------|--------------| +| Input method framework module| @ohos.inputmethod.d.ts |@ohos.inputMethod.d.ts | +| Input method service module|@ohos.inputmethodengine.d.ts | @ohos.inputMethodEngine.d.ts | +| Input method ExtentionAbility module| @ohos.inputmethodextensionability.d.ts | @ohos.InputMethodExtensionAbility.d.ts | +| Input method ExtentionContext module|@ohos.inputmethodextensioncontext.d.ts | @ohos.InputMethodExtensionContext.d.ts | +| Input method subtype module| @ohos.inputMethodSubtype.d.ts | @ohos.InputMethodSubtype.d.ts | + +**Adaptation Guide** + +In the application code, change the name of the d.ts file following **import** to the new file name, which complies with the UpperCamelCase or lowerCamelCase style. + +Example: + +```js +import inputMethodEngine from '@ohos.inputMethodEngine'; +``` + + diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-testfwk_arkxtest.md b/en/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-testfwk_arkxtest.md new file mode 100644 index 0000000000000000000000000000000000000000..69bf6038edfb09bcee929d5f85bb66254ef58ab7 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-testfwk_arkxtest.md @@ -0,0 +1,41 @@ +# Test Subsystem ChangeLog + +## cl.testfwk_arkxtest.1 Exception Handling Support of On, Driver, and Component APIs + +The original APIs in API version 8 are deprecated, and substitute APIs that support exception handling are introduced in API version 9. You must use **try catch** to capture exceptions thrown by the APIs. + +## Change Impacts + +This change affects the JS APIs in API version 9 provided by **@ohos.uitest**. If you have used the API of **@ohos.uitest-api9** during test case development, adaptation is required so that the compilation can be successful in the SDK environment of the new version. + +## Key API/Component Changes + +- The **By** class in API version 8 is deprecated and replaced by the **On** class in API version 9. The APIs of the **On** class support exception handling and retain their original name, with the exception of **By#key**, which is renamed **On.id**. +- The **BY** object in API version 8 is deprecated and replaced by the **ON** object in API version 9. +- The **UiDriver** class in API version 8 is deprecated and replaced by the **Driver** class in API version 9. The APIs of the **Driver** class support exception handling and retain their original name. +- The **UiComponent** class in API version 8 is deprecated and replaced by the **Component** class in API version 9. The APIs of the **Component** class support exception handling and retain their original name. + +## Adaptation Guide + +1. Adapt to the API name changes. + + You can replace the class name according to the following rules: + + - `By-->On` + - `BY-->ON` + - `UiDriver-->Driver` + - `UiComponent-->Component` + +2. Catch and handle exceptions. + + Use **try-catch** to catch and handle exceptions thrown by the APIs. Below is the sample code: + + ```typescript + import {Driver,ON,Component} from '@ohos.uitest' + + try { + let driver = Driver.create(); + } catch (error) { + // error handle; error.code indicates the error code. + } + ``` \ No newline at end of file diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.1.5/changelogs-wifiManager.md b/en/release-notes/changelogs/OpenHarmony_4.0.1.5/changelogs-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..f424d69976a74e00b8aab625c5d24b8dfc72c99a --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.1.5/changelogs-wifiManager.md @@ -0,0 +1,62 @@ +# Wi-Fi Subsystem ChangeLog + +## cl.location.1 Location Service Permission Change + +From API version 9, the **ohos.permission.APPROXIMATELY_LOCATION** permission is added for obtaining the approximate location. + +If you use API version 9 or later, you need to apply for both the **ohos.permission.LOCATION** and **ohos.permission.APPROXIMATELY_LOCATION** permissions. Applying for only the **ohos.permission.LOCATION** permission will fail. + +**Change Impacts** + +Applications using API versions earlier than 9 are not affected. For an application using API version 9 or later, the method for applying for the location permission is changed. The details are as follows: + +Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. + +The system provides the following location permissions: + +- ohos.permission.LOCATION + +- ohos.permission.APPROXIMATELY_LOCATION + +- ohos.permission.LOCATION_IN_BACKGROUND + +If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: + +API versions earlier than 9: Apply for **ohos.permission.LOCATION**. + +API version 9 and later: Apply for **ohos.permission.APPROXIMATELY_LOCATION**, or apply for **ohos.permission.APPROXIMATELY_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. + +| API Version| Location Permission | Permission Application Result| Location Accuracy | +| ------------- | ------------------------------------------------------------ | -------- | -------------------------------- | +| Earlier than 9 | ohos.permission.LOCATION | Success | Location accurate to meters| +| 9 and later | ohos.permission.LOCATION | Failure | No location obtained | +| 9 and later | ohos.permission.APPROXIMATELY_LOCATION | Success | Location accurate to 5 kilometers | +| 9 and later | ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success | Location accurate to meters| + +If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. + +You can declare the required permissions in your application's configuration file. For details, see the [permission application guide](../../../application-dev/security/accesstoken-guidelines.md). + +**Key API/Component Changes** + +| Class | API Type| Declaration | Change Type | +| ----------- | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| wifiManager | method | function scan(): void; | The permission is changed to **ohos.permission.SET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getScanResults(): Promise<Array<WifiScanInfo>>; | The permission is changed to **ohos.permission.GET_WIFI_INFO** and **ohos.permission.GET_WIFI_PEERS_MAC** or **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO** and **ohos.permission.GET_WIFI_PEERS_MAC** or **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getScanResultsSync(): Array<WifiScanInfo>; | The permission is changed to **ohos.permission.GET_WIFI_INFO** and **ohos.permission.GET_WIFI_PEERS_MAC** or **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getCandidateConfigs(): Array<WifiDeviceConfig>; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getDeviceConfigs(): Array<WifiDeviceConfig>; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, **ohos.permission.APPROXIMATELY_LOCATION**, and **ohos.permission.GET_WIFI_CONFIG**.| +| wifiManager | method | function getStations(): Array<StationInfo>; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, **ohos.permission.APPROXIMATELY_LOCATION**, and **ohos.permission.MANAGE_WIFI_HOTSPOT**.| +| wifiManager | method | function getCurrentGroup(): Promise<WifiP2pGroupInfo>; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getP2pPeerDevices(): Promise<WifiP2pDevice[]>; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function p2pConnect(config: WifiP2PConfig): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function startDiscoverDevices(): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getP2pGroups(): Promise<Array<WifiP2pGroupInfo>>; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void; | The permission is changed to **ohos.permission.LOCATION** and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void; | The permission is changed to **ohos.permission.GET_WIFI_INFO**, **ohos.permission.LOCATION**, and **ohos.permission.APPROXIMATELY_LOCATION**.| +| wifiManager | method | function off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void; | The permission is changed to **ohos.permission.LOCATION** and **ohos.permission.APPROXIMATELY_LOCATION**.| diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelog-web.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelog-web.md new file mode 100644 index 0000000000000000000000000000000000000000..254050b5104e769b4b4e44d6bbee8d13876d37db --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelog-web.md @@ -0,0 +1,65 @@ +# Web Subsystem ChangeLog + +Compared with earlier versions, OpenHarmony 4.0.2.1 has the following API changes in its Web subsystem: + +## cl.web.1 Parameter Type Change of postMessageEvent + +The **postMessageEvent** API supported only the string type. In OpenHarmony 4.0.2.1 and later versions, it also supports the ArrayBuffer type. + +**Change Impacts** + +The API change is forward compatible. Applications developed based on earlier versions can still use the API, and the original functions are not affected. + +**Key API/Component Changes** + +- Involved APIs + + postMessageEvent(message: string): void + +- Before change + + ```ts + postMessageEvent(message: string): void + ``` + +- After change + + ```ts + type WebMessage = ArrayBuffer | string + postMessageEvent(message: WebMessage): void + ``` + +**Adaptation Guide** + +The API change is forward compatible. Applications developed based on earlier versions can still use the API, and the original functions are not affected. + +## cl.web.2 Parameter Type Change of onMessageEvent + +The **onMessageEvent** API supported only the string type. In OpenHarmony 4.0.2.1 and later versions, it also supports the ArrayBuffer type. + +**Change Impacts** + +The API change is forward compatible. Applications developed based on earlier versions can still use the API. With the corresponding logic handling added, the original functions are not affected. + +**Key API/Component Changes** + +- Involved APIs + + onMessageEvent(callback: (result: string) => void): void + +- Before change + + ```ts + onMessageEvent(callback: (result: string) => void): void + ``` + +- After change + + ```ts + type WebMessage = ArrayBuffer | string + onMessageEvent(callback: (result: WebMessage) => void): void + ``` + +**Adaptation Guide** + +The API change is forward compatible. Applications developed based on earlier versions can still use the API. With the corresponding logic handling added, the original functions are not affected. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-bluetooth.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-bluetooth.md new file mode 100644 index 0000000000000000000000000000000000000000..46cabda38dd35234da3b29b6e3a891fcee63dd56 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-bluetooth.md @@ -0,0 +1,173 @@ +# Bluetooth Subsystem ChangeLog + +## cl.bluetooth.1 API Migration to @ohos.bluetoothManager.d.ts + +**@ohos.bluetooth.d.ts** does not allow for throwing error codes, which is required by API version 9 and system APIs. Therefore, all APIs of **@ohos.bluetooth.d.ts** are migrated to the newly added **@ohos.bluetoothManager.d.ts**, and error code description is also added. + +To use Bluetooth APIs, import **@ohos.bluetoothManager**. + + ```ts + import bluetoothManager from '@ohos.bluetoothManager'; + ``` + + +**Change Impacts** + +System APIs and APIs in API version 9 are affected. Import **@ohos.bluetoothManager** to use APIs that can throw error codes. + + ```ts + import bluetoothManager from '@ohos.bluetoothManager'; + ``` + +**Key API/Component Changes** + +| Class | Original API | New API | Change Type | +| ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| bluetooth | function getState(): BluetoothState | function getState(): BluetoothState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | method | function getBtConnectionState(): ProfileConnectionState; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function pairDevice(deviceId: string): boolean | function pairDevice(deviceId: string): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function cancelPairedDevice(deviceId: string): boolean | function cancelPairedDevice(deviceId: string): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function getRemoteDeviceName(deviceId: string): string | function getRemoteDeviceName(deviceId: string): string | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function getRemoteDeviceClass(deviceId: string): DeviceClass | function getRemoteDeviceClass(deviceId: string): DeviceClass | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function enableBluetooth(): boolean | function enableBluetooth(): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function disableBluetooth(): boolean | function disableBluetooth(): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function getLocalName(): string | function getLocalName(): string | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function getPairedDevices(): Array<string>; | function getPairedDevices(): Array<string>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function getProfileConnState(profileId: ProfileId): ProfileConnectionState | function getProfileConnectionState(profileId: ProfileId): ProfileConnectionState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the API name to **getProfileConnectionState**.| +| bluetooth | function setDevicePairingConfirmation(device: string, accept: boolean): boolean | function setDevicePairingConfirmation(device: string, accept: boolean): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function setLocalName(name: string): boolean; | function setLocalName(name: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function setBluetoothScanMode(mode: ScanMode, duration: number): boolean | function setBluetoothScanMode(mode: ScanMode, duration: number): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function getBluetoothScanMode(): ScanMod | function getBluetoothScanMode(): ScanMode | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function startBluetoothDiscovery(): boolean | function startBluetoothDiscovery(): void | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**, added the **ohos.permission.APPROXIMATELY_LOCATION** permission, and changed the return value to **void**.| +| bluetooth | function stopBluetoothDiscovery(): boolean; | function stopBluetoothDiscovery(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void; | function on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void; | function off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function on(type: "bondStateChange", callback: Callback<BondStateParam>): void; | function on(type: "bondStateChange", callback: Callbackk<BondStateParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function off(type: "bondStateChange", callback?: Callback<BondStateParam>): void; | function off(type: "bondStateChange", callback?: Callback<BondStateParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function on(type: "pinRequired", callback: Callback<PinRequiredParam>): void; | function on(type: "pinRequired", callback: Callback<PinRequiredParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void; | function off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function on(type: "stateChange", callback: Callback<BluetoothState>): void; | function on(type: "stateChange", callback: Callback<BluetoothState>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function off(type: "stateChange", callback?: Callback<BluetoothState>): void; | function off(type: "stateChange", callback?: Callback<BluetoothState>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void; | function sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function sppAccept(serverSocket: number, callback: AsyncCallback<number>): void; | function sppAccept(serverSocket: number, callback: AsyncCallback<number>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void; | function sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function sppCloseServerSocket(socket: number): void; | function sppCloseServerSocket(socket: number): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function sppCloseClientSocket(socket: number): void; | function sppCloseClientSocket(socket: number): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function sppWrite(clientSocket: number, data: ArrayBuffer): boolean; | function sppWrite(clientSocket: number, data: ArrayBuffer): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| bluetooth | function on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void; | function on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void; | function off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | function getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile; | function getProfileInstance(profileId: ProfileId): A2dpSourceProfile | +| bluetooth | function getProfileInst(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | +| BaseProfile | getConnectionDevices(): Array<string>; | getConnectionDevices(): Array<string>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BaseProfile | getDeviceState(device: string): ProfileConnectionState; | getDeviceState(device: string): ProfileConnectionState; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| A2dpSourceProfile | connect(device: string): boolean; | connect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| A2dpSourceProfile | disconnect(device: string): boolean; | disconnect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| A2dpSourceProfile | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| A2dpSourceProfile | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| A2dpSourceProfile | getPlayingState(device: string): PlayingState; | getPlayingState(device: string): PlayingState; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| HandsFreeAudioGatewayProfile | connect(device: string): boolean; | connect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| HandsFreeAudioGatewayProfile | disconnect(device: string): boolean; | disconnect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| HandsFreeAudioGatewayProfile | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| HandsFreeAudioGatewayProfile | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| HidHostProfile | connect(device: string): boolean; | connect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| HidHostProfile | disconnect(device: string): boolean; | disconnect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| HidHostProfile | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| HidHostProfile | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| PanProfile | disconnect(device: string): boolean; | disconnect(device: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| PanProfile | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| PanProfile | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| PanProfile | setTethering(enable: boolean): void; | setTethering(enable: boolean): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| PanProfile | isTetheringOn(): boolean; | isTetheringOn(): boolean; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BLE | function createGattServer(): GattServer; | function createGattServer(): GattServer; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BLE | function createGattClientDevice(deviceId: string): GattClientDevice; | function createGattClientDevice(deviceId: string): GattClientDevice; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BLE | function getConnectedBLEDevices(): Array<string>; | function getConnectedBLEDevices(): Array<string>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BLE | function startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void; | function startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and added the **ohos.permission.APPROXIMATELY_LOCATION** permission.| +| BLE | function stopBLEScan(): void; | function stopBLEScan(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BLE | mefunction on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void;thod | function on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| BLE | function off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void; | function off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void; | startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | stopAdvertising(): void; | stopAdvertising(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | addService(service: GattService): boolean; | addService(service: GattService): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| GattServer | removeService(serviceUuid: string): boolean; | removeService(serviceUuid: string): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**.| +| GattServer | close(): void; | close(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. +| GattServer | notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): boolean; | notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattServer | sendResponse(serverResponse: ServerResponse): boolean; | sendResponse(serverResponse: ServerResponse): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattServer | on(type: "characteristicRead", callback: Callback<CharacteristicReadReq>): void; | on(type: "characteristicRead", callback: Callback<CharacteristicReadRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | off(type: "characteristicRead", callback?: Callback<CharacteristicReadReq>): void; | off(type: "characteristicRead", callback?: Callback<CharacteristicReadRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | on(type: "characteristicWrite", callback: Callback<CharacteristicWriteReq>): void; | on(type: "characteristicWrite", callback: Callback<CharacteristicWriteRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteReq>): void; | off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | on(type: "descriptorRead", callback: Callback<DescriptorReadReq>): void; | on(type: "descriptorRead", callback: Callback<DescriptorReadRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | off(type: "descriptorRead", callback?: Callback<DescriptorReadReq>): void; | off(type: "descriptorRead", callback?: Callback<DescriptorReadRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | on(type: "descriptorWrite", callback: Callback<DescriptorWriteReq>): void; | on(type: "descriptorWrite", callback: Callback<DescriptorWriteRequest>): void;| Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | off(type: "descriptorWrite", callback?: Callback<DescriptorWriteReq>): void; | off(type: "descriptorWrite", callback?: Callback<DescriptorWriteRequest>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void; | on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void;| Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattServer | off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void; | off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | connect(): boolean; | connect(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | disconnect(): boolean; | disconnect(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | close(): boolean; | close(): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | getDeviceName(callback: AsyncCallback<string>): void; | getDeviceName(callback: AsyncCallback<string>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | getDeviceName(): Promise<string>; | getDeviceName(): Promise<string>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | getServices(callback: AsyncCallback<Array<GattService>>): void; | getServices(callback: AsyncCallback<Array<GattService>>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | getServices(): Promise<Array<GattService>>; | getServices(): Promise<Array<GattService>>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void; | readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic>; | readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void; | readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor>; | readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | writeCharacteristicValue(characteristic: BLECharacteristic): boolean; | writeCharacteristicValue(characteristic: BLECharacteristic): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | writeDescriptorValue(descriptor: BLEDescriptor): boolean; | writeDescriptorValue(descriptor: BLEDescriptor): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | getRssiValue(callback: AsyncCallback<number>): void; | getRssiValue(callback: AsyncCallback<number>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | getRssiValue(): Promise<number>; | getRssiValue(): Promise<number>; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | setBLEMtuSize(mtu: number): boolean; | setBLEMtuSize(mtu: number): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): boolean; | setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts** and changed the return value to **void**. | +| GattClientDevice | on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void; | on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void; | off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void; | on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| GattClientDevice | off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void; | off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void; | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | GattService | GattService | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | BLECharacteristic | BLECharacteristic | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | BLEDescriptor | BLEDescriptor | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | NotifyCharacteristic | NotifyCharacteristic | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | CharacteristicReadReq | CharacteristicReadRequest | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | CharacteristicWriteReq | CharacteristicWriteRequest | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | DescriptorReadRe | DescriptorReadRequest | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | DescriptorWriteReq | DescriptorWriteRequest | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ServerResponse | ServerResponse | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | BLEConnectChangedState | BLEConnectChangedState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ScanResult | ScanResult | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | AdvertiseSetting | AdvertiseSetting | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | AdvertiseData | AdvertiseData | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ManufactureData | ManufactureData | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ServiceData | ServiceData | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ScanFilter | ScanFilter | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ScanOptions | ScanOptions | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | SppOption | SppOption | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | PinRequiredParam | PinRequiredParam | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | DeviceClass | DeviceClass | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | BondStateParam | BondStateParam | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | StateChangeParam | StateChangeParam | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ScanDuty | ScanDuty | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | MatchMode | MatchMode | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ProfileConnectionState | ProfileConnectionState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | BluetoothState | BluetoothState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | SppType | SppType | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ScanMode | ScanMode | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | BondState | BondState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | MajorClass | MajorClass | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | MajorMinorClass | MajorMinorClass | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | PlayingState | PlayingState | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | +| bluetooth | ProfileId | ProfileId | Migrated this API in API version 9 to **@ohos.bluetoothManager.d.ts**. | + + + +**(Optional) Adaptation Guide** + +The following uses **enableLocation** as an example to show how it is called in the new version: + + ```ts + import bluetoothManager from '@ohos.bluetoothManager'; + try { + var state = bluetoothManager.getState(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md index d67dc521bfdb10aff1beee5453a9381ef39d4dc6..2e4e9981788e07f1f41bef6c579898fe649c7368 100644 --- a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md @@ -2,7 +2,7 @@ ## cl.filemanagement.1 Changed environment -The file management subsystem **d.ts** file has been moved to the **file** directory. The **environment** module supports error code processing. +The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **environment** module supports error code processing. **Change Impacts** @@ -24,7 +24,7 @@ import environment from '@ohos.file.environment'; ## cl.filemanagement.2 Changed securityLabel -The file management subsystem **d.ts** file has been moved to the **file** directory. The **securityLabel** module supports error code processing. +The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **securityLabel** module supports error code processing. **Change Impacts** @@ -50,7 +50,7 @@ The **ino** attribute type of the **Stat** API under the **fs** module is change **Change Impacts** -The **ino** attribute type is changed from number to BigInt, to adapt to the inode range of all types of files in the file system. +The **ino** attribute type is changed from number to BigInt, to adapt the inode range of all types of files in the file system. **Key API/Component Changes** @@ -58,7 +58,7 @@ The type of the **ino** attribute of the **Stat** API is changed from number to ## cl.filemanagement.4 Changed fileAccess -The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileAccess** module supports error code processing. +The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **fileAccess** module supports error code processing. **Change Impacts** @@ -80,7 +80,7 @@ import fileAccess from '@ohos.file.fileAccess'; ## cl.filemanagement.5 Changed fileExtensionInfo -The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. +The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. **Change Impacts** @@ -102,7 +102,7 @@ import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; ## cl.filemanagement.6 Changed storageStatistics -The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. +The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. **Change Impacts** @@ -124,7 +124,7 @@ import storageStatistics from '@ohos.file.storageStatistics'; ## cl.filemanagement.7 Changed volumeManager -The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. +The file management subsystem **d.ts** file has been archived moved to the **file** directory. The **volumeManager** module supports error code processing. **Change Impacts** diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-testfwk_arkxtest.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-testfwk_arkxtest.md new file mode 100644 index 0000000000000000000000000000000000000000..1206d659402df80e9892ca3e7b4eba1e729c9357 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-testfwk_arkxtest.md @@ -0,0 +1,42 @@ +# Test Subsystem ChangeLog + +## cl.testfwk_arkxtest.1 API Name Change of Rect + +The definition of **Rect**, an enumeration type that indicates the component bound information, is changed since version 4.0.2.1. + +## Change Impacts + +This change affects the **Rect** API provided by **@ohos.uitest**. If you have used the **Rect** API of **@ohos.uitest-api9** during test case development, adaptation is required so that the compilation can be successful in the SDK environment of the new version. + +## Key API/Component Changes + +### Rect9+ + +Before change + +| Name | Value | Description | +| ------- | ---- | ------------------------- | +| leftX | 1 | X-coordinate of the upper left corner of the component bounds.| +| topY | 2 | Y-coordinate of the upper left corner of the component bounds.| +| rightX | 3 | X-coordinate of the lower right corner of the component bounds.| +| bottomY | 4 | Y-coordinate of the lower right corner of the component bounds.| + +After change + +| Name | Value | Description | +| ------ | ---- | ------------------------- | +| left | 1 | X-coordinate of the upper left corner of the component bounds.| +| top | 2 | Y-coordinate of the upper left corner of the component bounds.| +| right | 3 | X-coordinate of the lower right corner of the component bounds.| +| bottom | 4 | Y-coordinate of the lower right corner of the component bounds.| + +## Adaptation Guide + +### Adaptation to the API Name Change + +You can replace the class name according to the following rules: + +- `leftX-->left` +- `topY-->top` +- `rightX-->right` +- `bottomY-->bottom` diff --git a/en/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md b/en/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md new file mode 100644 index 0000000000000000000000000000000000000000..1eb84215498004fe05d46715ac02236ee28d5e58 --- /dev/null +++ b/en/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md @@ -0,0 +1,57 @@ +# Account Subsystem ChangeLog + +## cl.account_os_account.1 OsAccountInfo.type Value Type Change + +Changed the value type of **OsAccountInfo.type** from **Object** to **OsAccountType** enumeration. + +**Change Impacts** + +The mode for reading the **OsAccountInfo.type** value needs to be changed for the application developed based on earlier versions. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + +The following APIs are involved: +- AccountManager + - queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>>): void; + - queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>>; + - createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback<OsAccountInfo>): void; + - createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo>; + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>): void; + - createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo>; + - queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void; + - queryCurrentOsAccount(): Promise<OsAccountInfo>; + - getCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void; + - getCurrentOsAccount(): Promise<OsAccountInfo>; + - queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void; + - queryOsAccountById(localId: number): Promise<OsAccountInfo>; + + - getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void; + - getOsAccountTypeFromProcess(): Promise<OsAccountType>; + - getOsAccountType(callback: AsyncCallback<OsAccountType>): void; + - getOsAccountType(): Promise<OsAccountType>; + +**Adaptation Guide** +```ts +import account_osAccount from "@ohos.account.osAccount" +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +let accountMgr = account_osAccount.getAccountManager(); +accountMgr.createOsAccount('account_test', account_osAccount.OsAccountType.GUEST).then((accountInfo) => { + expect(accountInfo.type).assertEqual(account_osAccount.OsAccountType.GUEST); + accountMgr.activateOsAccount(accountInfo.localId).then(() => { + console.log('activateOsAccount successfully'); + accountMgr.getOsAccountTypeFromProcess().then((accountType) => { + expect(accountType).assertEqual(account_osAccount.OsAccountType.GUEST); + }).catch((err) => { + console.log('activateOsAccount err: ' + JSON.stringify(err)); + expect().assertFail(); + }); + }).catch((err) => { + console.log('activateOsAccount err: ' + JSON.stringify(err)); + expect().assertFail(); + }); +}).catch((err) => { + console.log('createOsAccount err: ' + JSON.stringify(err)); + expect().assertFail(); +}); +``` diff --git a/zh-cn/application-dev/application-models/accessibilityextensionability.md b/zh-cn/application-dev/application-models/accessibilityextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..2066ba3f3b7868180745f7a37a6e1e4483b6a33b --- /dev/null +++ b/zh-cn/application-dev/application-models/accessibilityextensionability.md @@ -0,0 +1,124 @@ +# AccessibilityExtensionAbility开发指南 + +AccessibilityExtensionAbility基于ExtensionAbility框架,提供无障碍扩展服务,开发者可以基于AccessibilityExtensionAbility模板开发自己的辅助功能应用,协助用户完成一些快捷的交互过程。 + +> **环境要求** +> +> IDE: DevEco Studio 3.0 Beta3 (3.0.0.900)及以后版本 +> +> SDK: API Version 9 及以后版本 +> +> Model: Stage + +本文档将从以下场景来介绍AccessibilityExtensionAbility的基本开发: + +- [如何创建一个无障碍扩展服务](#如何创建一个无障碍扩展服务) +- [如何处理一个无障碍事件](#如何处理一个无障碍事件) +- [如何声明无障碍扩展服务具备的能力](#如何声明无障碍扩展服务具备的能力) +- [如何开启自定义的无障碍扩展服务](#如何开启自定义的无障碍扩展服务) +- [相关示例](#相关示例) + +## 如何创建一个无障碍扩展服务 + +开发者在创建一个无障碍扩展服务时,如工程满足环境要求,开发者可自主选择是否跳过创建工程步骤,在已有工程中新增无障碍扩展服务。 + +### 创建工程 + +如需新增独立的无障碍扩展服务应用,可按以下步骤进行。在DevEco Studio中新建一个工程,具体步骤如下: +1. 在DevEco Studio的左上角标签栏,选择`File -> New -> Create Project`新建一个工程; +2. 根据工程创建向导,选择`OpenHarmony`标签页,选择`Empty Ability`模板,点击Next,进入项目详细配置页; +3. 选择项目类型为Application,Compile API(高版本为Compile SDK)为9,Model为`Stage`,然后点击Finish完成工程创建。 + +### 新建AccessibilityExtAbility文件 + +在已创建工程的ets文件夹下创建AccessibilityExtAbility文件夹,在该文件夹下创建AccessibilityExtAbility.ts文件,在新增的文件中加入以下代码: + +```typescript +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'; + +class AccessibilityExtAbility extends AccessibilityExtensionAbility { + onConnect() { + console.log('AccessibilityExtAbility onConnect'); + } + + onDisconnect() { + console.log('AccessibilityExtAbility onDisconnect'); + } + + onAccessibilityEvent(accessibilityEvent) { + console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); + } +} + +export default AccessibilityExtAbility; +``` + +其中,主要定义了以下接口: + +| 接口 | 描述 | +| ---- | ---- | +| onConnect(): void | 当扩展服务连接时回调 | +| onDisconnect(): void | 当扩展服务断开时回调 | +| onAccessibilityEvent(event: AccessibilityEvent): void | 当无障碍事件发生时回调 | + +## 如何处理一个无障碍事件 + +相关无障碍事件可以在`onAccessibilityEvent()`方法中进行业务逻辑处理,具体事件可参考[AccessibilityEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityevent)。此处以事件`pageStateUpdate`为例: + +```typescript +onAccessibilityEvent(accessibilityEvent) { + console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); + if (accessibilityEvent.eventType === 'pageStateUpdate') { + console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate'); + // TODO: 自定义相关逻辑开发 + } +} +``` +此外,也可在相应的无障碍事件中,使用[辅助功能扩展上下文(AccessibilityExtensionContext)](../reference/apis/js-apis-inner-application-accessibilityExtensionContext.md)提供的接口进行扩展开发,包括允许配置辅助应用关注信息类型、查询节点信息、手势注入等。 + +## 如何声明无障碍扩展服务具备的能力 + +在完成自定义无障碍扩展服务的逻辑开发后,还需要在工程中Module对应的module.json5文件中加入新增扩展服务的配置信息,其中`srcEntrance`标签为`extensionAbility`对应的路径。需要注意的一点是配置信息中的type标签要按照与无障碍子系统的约定进行配置,固定为`accessibility`,否则将无法正常连接。 + +```json +"extensionAbilities": [ + { + "name": "AccessibilityExtAbility", + "srcEntrance": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts", + "label": "$string:MainAbility_label", + "description": "$string:MainAbility_desc", + "type": "accessibility", + "metadata": [ + { + "name": "ohos.accessibleability", + "resource": "$profile:accessibility_config" + } + ] + } +] +``` +另外,配置信息中的`accessibility_config`为无障碍扩展服务的具体配置,需要在`resources/profile/`下新建`accessibility_config.json`文件,在该文件中声明此无障碍扩展服务具备的[能力类型](../reference/apis/js-apis-accessibility.md#capability): +```json +{ + "accessibilityCapabilities": [ + "retrieve", + "gesture" + ] +} +``` +## 如何开启自定义的无障碍扩展服务 + +目前设置中尚未开放无障碍扩展服务开启关闭功能,需要使用命令行进行开启关闭。 +- 开启命令:`accessibility enable -a AccessibilityExtAbility -b com.example.demo -c rg` +- 关闭命令:`accessibility disable -a AccessibilityExtAbility -b com.example.demo` + +其中,`AccessibilityExtAbility`为自定义的无障碍扩展服务名,`com.example.demo`为bundleName,`rg`为无障碍扩展服务具体的类型(其中,r为`retrieve`的首字母,其余同理)。 + +若开启或关闭成功,则会打印`enable ability successfully`或`disable ability successfully`。 + +## 相关示例 + +针对AccessibilityExtensionAbility开发,有以下相关示例可供参考: + +[AccessibilityExtAbility的创建和使用(ArkTS)(API 9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/AccessibilityExtAbility) + diff --git a/zh-cn/application-dev/application-models/application-model-description.md b/zh-cn/application-dev/application-models/application-model-description.md index 0623ea2b00b526e9e45596c5fdb365ce3c401a9f..45fb17804cd9a95d9ec45df33a9973404d392ed3 100644 --- a/zh-cn/application-dev/application-models/application-model-description.md +++ b/zh-cn/application-dev/application-models/application-model-description.md @@ -9,7 +9,7 @@ - Stage模型:OpenHarmony API 9开始新增的模型,是目前主推且会长期演进的模型。在该模型中,由于提供了AbilityStage、WindowStage等类作为应用组件和Window窗口的“舞台”,因此称这种应用模型为Stage模型。 -Stage模型之所以成为主推模型,源于其设计思想。Stage模型的设计基于如下4个出发点。 +Stage模型之所以成为主推模型,源于其设计思想。Stage模型的设计基于如下出发点。 1. **为复杂应用而设计** - 多个应用组件共享同一个ArkTS引擎(运行ArkTS语言的虚拟机)实例,应用组件之间可以方便的共享对象和状态,同时减少复杂应用运行对内存的占用。 diff --git a/zh-cn/application-dev/application-models/enterprise-extensionAbility.md b/zh-cn/application-dev/application-models/enterprise-extensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..b418036d0faacb55d22a3ae4ed96d5db25a60c1a --- /dev/null +++ b/zh-cn/application-dev/application-models/enterprise-extensionAbility.md @@ -0,0 +1,118 @@ +# EnterpriseAdminExtensionAbility开发指南 + +## EnterpriseAdminExtensionAbility简介 + +企业设备管理扩展能力,是MDM应用必备组件。当开发者为企业开发MDM(Mobilie Device Management)应用时,需继承EnterpriseAdminExtensionAbility,在EnterpriseAdminExtensionAbility实例中实现MDM业务逻辑,EnterpriseAdminExtensionAbility实现了系统管理状态变化通知功能,并定义了管理应用激活、去激活、应用安装、卸载事件等回调接口。 + +## 约束与限制 + +- **_功能限制_** + + 仅支持设备管理员应用使用。 + + +## 场景:监听设备管理器激活、去激活、应用安装、卸载事件 + +## 概述 + +onAdminEnabled:由企业管理员或者员工部署MDM应用,激活设备管理器,系统通知MDM应用已激活DeviceAdmin权限。MDM应用可在onAdminEnabled回调函数中进行初始化策略设置。 + +onAdminDisabled:由系统或者员工去激活设备管理器,通知去激活DeviceAdmin权限,应用可以通知企业管理员设备已脱管。 + +onBundleAdded: 企业应用管理场景下,企业管理员订阅应用安装卸载事件,端侧应用安装和卸载事件通知MDM应用,MDM应用可以在回调函数中进行事件上报,通知企业管理员。 + +onBundleRemoved: 企业应用管理场景下,企业管理员取消订阅应用安装卸载事件。 + +## 接口说明 + +| 类名 | 接口名称 | 描述 | +| :------------------------------ | ----------------------------------------- | ---------------------------- | +| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | 设备管理器应用去激活回调方法 | +| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | 应用安装回调方法 | +| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | 设备管理器应用激活回调方法 | +| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | 应用卸载回调方法 | + +## 开发步骤 + +开发者在实现EnterpriseAdminExtensionAbility的时候,需先激活设备管理员应用,并在设备管理员应用的代码目录下载新建ExtensionAbility,具体步骤如下。 + +1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为EnterpriseExtAbility。 +2. 在EnterpriseExtAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为EnterpriseExtAbility.ts。 +3. 打开EnterpriseExtAbility.ts文件,导入EnterpriseAdminExtensionAbility模块,自定义类继承EnterpriseAdminExtensionAbility并加上需要的应用通知回调方法,如onAdminEnabled()、onAdminDisabled()等回调方法。当设备管理员应用被激活或则去激活时,则可以在对应回调方法中接受系统发送通知。 + +```ts +import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility'; + +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + + onAdminEnabled() { + console.info("onAdminEnabled"); + } + + onAdminDisabled() { + console.info("onAdminDisabled"); + } + + onBundleAdded(bundleName: string) { + console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName) + } + + onBundleRemoved(bundleName: string) { + console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName) + } +}; +``` + +​ 4.在工程Module对应的[module.json5](../quick-start/module-configuration-file.md)配置文件中注册ServiceExtensionAbility,type标签需要设置为“enterpriseAdmin”,srcEntrance标签表示当前ExtensionAbility组件所对应的代码路径。 + +```ts +"extensionAbilities": [ + { + "name": "ohos.samples.enterprise_admin_ext_ability", + "type": "enterpriseAdmin", + "visible": true, + "srcEntrance": "./ets/enterpriseextability/EnterpriseAdminAbility.ts" + } + ] +``` + +## 使用示例 + +通过@ohos.enterprise.adminManager模块中的subscribeManagedEvent接口和unsubscribeManagedEvent接口进行企业设备管理事件的订阅,订阅应用安装、卸载事件。当订阅成功后,端侧应用安装和卸载事件通知MDM应用,MDM应用可以在回调函数中进行事件上报,通知企业管理员。 + +```ts + @State managedEvents: Array = [0,1] + @State subscribeManagedEventMsg: string = "" + @State unsubscribeManagedEventMsg: string = "" + + async subscribeManagedEventCallback() { + await adminManager.subscribeManagedEvent(this.admin, + [adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED, + adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED], (error) => { + if (error) { + this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::errorCode: ' + error.code + ' errorMessage: ' + error.message + } else { + this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::success' + } + }) + } + + async unsubscribeManagedEventPromise() { + await adminManager.unsubscribeManagedEvent(this.admin, + [adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED, + adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED]).then(() => { + this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::success' + }).catch((error) => { + this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::errorCode: ' + error.code + ' errorMessage: ' + error.message + }) + } +``` + + + +## 相关实例 + +针对EnterpriseAdminExtensionAbility开发,有以下相关示例可供参考: + +[EnterpriseAdminExtensionAbility:EnterpriseAdminExtensionAbility的创建与使用(ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/customization/EnterpriseAdminExtensionAbility) + diff --git a/zh-cn/application-dev/application-models/inputmethodextentionability.md b/zh-cn/application-dev/application-models/inputmethodextentionability.md new file mode 100644 index 0000000000000000000000000000000000000000..0f2f84f321ebf304b3fe8110bd10493e04b47be1 --- /dev/null +++ b/zh-cn/application-dev/application-models/inputmethodextentionability.md @@ -0,0 +1,367 @@ +# InputMethodExtensionAbility开发指南 + +[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)是inputMethod类型的ExtensionAbility组件,提供输入法框架服务相关扩展能力。 + +[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)可以被其他组件启动或连接,并根据调用者的请求信息在后台处理相关事务。 + + +InputMethodExtensionAbility通过[InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md)提供相关能力。 + + +## 实现一个输入法应用 + +[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)提供了onCreate()和onDestory()生命周期回调,根据需要重写对应的回调方法。InputMethodExtensionAbility的生命周期如下: + +- **onCreate** + 服务被首次创建时触发该回调,开发者可以在此进行一些初始化的操作,例如注册公共事件监听等。 + + > **说明:** + > 如果服务已创建,再次启动该InputMethodExtensionAbility不会触发onCreate()回调。 + +- **onDestroy** + 当不再使用服务且准备将其销毁该实例时,触发该回调。开发者可以在该回调中清理资源,如注销监听等。 + + +## 开发步骤 + +开发者在实现一个输入法应用时,需要在DevEco Studio工程中新建一个InputMethodExtensionAbility,具体步骤如下: + +在工程Module对应的ets目录下,右键选择“New > Extention Ability > InputMethod”,即可创建出InputMethodExtensionAbility的最小化模板。 + +最小化模板为一个最基本的输入法应用,包含软键盘拉起以及输入删除功能。后续开发者可在此基础上添加功能,如隐藏键盘等,实现自己的输入法应用。 + +最小化模板主要包含四个文件,分别为KeyboardController.ts、InputMethodService.ts、Index.ets以及KeyboardKeyData.ts。目录如下: + +``` +/src/main/ +├── ets/InputMethodExtAbility +│ └──model/KeyboardController.ts # 显示键盘 +│ └──InputMethodService.ts # 自定义类继承InputMethodExtensionAbility并加上需要的生命周期回调 +│ └──pages +│ └──InputMethodExtAbility +│ └── Index.ets # 绘制键盘,添加输入删除功能 +│ └── KeyboardKeyData.ts # 键盘属性定义 +├── resources/base/profile/main_pages.json +``` + +## 文件介绍 + +1. InputMethodService.ts文件。 + + 在InputMethodService.ts文件中,增加导入InputMethodExtensionAbility的依赖包,自定义类继承InputMethodExtensionAbility并加上需要的生命周期回调。 + + ```ts + import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility'; + import { KeyboardController } from './model/KeyboardController' + + export default class InputDemoService extends InputMethodExtensionAbility { + private keyboardController: KeyboardController; + + onCreate(want) { + this.keyboardController = new KeyboardController(this.context); + this.keyboardController.onCreate(); // 初始化窗口并注册对输入法框架的事件监听 + } + + onDestroy() { + console.log("onDestroy."); + this.context.destroy() + } + } + ``` + +2. KeyboardController.ts文件。 + + ```ts + import inputMethodEngine from '@ohos.inputMethodEngine' + import display from '@ohos.display' + import windowManager from '@ohos.window' + + // 调用输入法框架的getInputMethodAbility方法获取实例,并由此实例调用输入法框架功能接口 + globalThis.inputAbility = inputMethodEngine.getInputMethodAbility(); + + export class KeyboardController { + mContext // 保存InputMethodExtensionAbility中的context属性 + WINDOW_TYPE_INPUT_METHOD_FLOAT = 2105 // 定义窗口类型,2105代表输入法窗口类型,用于创建输入法应用窗口 + windowName = 'inputApp'; + private windowHeight: number = 0; + private windowWidth: number = 0; + private nonBarPosition: number = 0; + private isWindowShowing: boolean = false; + + constructor(context) { + this.mContext = context; + } + + public onCreate(): void + { + this.initWindow(); // 初始化窗口 + this.registerListener(); // 注册对输入法框架的事件监听 + } + + public onDestroy(): void // 应用生命周期销毁 + { + this.unRegisterListener(); // 注销事件监听 + var win = windowManager.findWindow(this.windowName) + win.destroyWindow() // 销毁窗口 + this.mContext.terminateSelf(); // 销毁InputMethodExtensionAbility服务 + } + + private initWindow(): void // 初始化窗口 + { + display.getDefaultDisplay().then(dis => { + var dWidth = dis.width; + var dHeight = dis.height; + var keyHeightRate = 0.47; + var keyHeight = dHeight * keyHeightRate; + this.windowWidth = dWidth; + this.windowHeight = keyHeight; + this.nonBarPosition = dHeight - keyHeight + + var config = { + name: this.windowName, + windowType: this.WINDOW_TYPE_INPUT_METHOD_FLOAT, + ctx: this.mContext + } + windowManager.createWindow(config).then((win) => { // 根据窗口类型创建窗口 + win.resize(dWidth, keyHeight).then(() => { + win.moveWindowTo(0, this.nonBarPosition).then(() => { + win.setUIContent('pages/InputMethodExtAbility/Index').then(() => { + }); + }); + }); + }); + }); + } + + private registerListener(): void + { + this.registerInputListener(); // 注册对输入法框架服务的监听 + globalThis.inputAbility.on('keyboardShow', () => { // 注册显示键盘事件监听 + if (this.isWindowShowing) { + return; + } + this.isWindowShowing = true; + this.showHighWindow(); // 显示窗口 + }); + ... + // 注册隐藏键盘事件监听等 + } + + private registerInputListener() { // 注册对输入法框架服务的开启及停止事件监听 + globalThis.inputAbility.on('inputStart', (kbController, textInputClient) => { + globalThis.textInputClient = textInputClient; // 此为输入法客户端实例,由此调用输入法框架提供给输入法应用的功能接口 + globalThis.keyboardController = kbController; + }) + globalThis.inputAbility.on('inputStop', (imeId) => { + if (imeId == "com.example.kikainput/InputDemoService") { + this.onDestroy(); + } + }); + } + + private unRegisterListener(): void + { + globalThis.inputAbility.off('inputStart'); + globalThis.inputAbility.off('inputStop'); + globalThis.inputAbility.off('keyboardShow'); + } + + private showHighWindow() { + var win = windowManager.findWindow(this.windowName) + win.resize(this.windowWidth, this.windowHeight).then(() => { + win.moveWindowTo(0, this.nonBarPosition).then(() => { + win.showWindow().then(() => { + this.isWindowShowing = false; + }) + }) + }) + } + } + ``` + +3. KeyboardKeyData.ts文件。 + + 定义软键盘的按键显示内容。 + + ```ts + export interface sourceListType { + content: string, + } + + export let numberSourceListData: sourceListType[] = [ + { + content: '1' + }, + { + content: '2' + }, + { + content: '3' + }, + { + content: '4' + }, + { + content: '5' + }, + { + content: '6' + }, + { + content: '7' + }, + { + content: '8' + }, + { + content: '9' + }, + { + content: '0' + } + ] + ``` + +4. Index.ets文件。 + + 主要描绘了具体按键功能。如按下数字键,就会将数字内容在输入框中打印出来,按下删除键,就会将内容删除。 + + 同时在resources/base/profile/main_pages.json文件的src字段中添加此文件路径。 + + ```ets + import { numberSourceListData, sourceListType } from './keyboardKeyData' + + @Component + struct keyItem { + private keyValue: sourceListType + @State keyBgc: string = "#fff" + @State keyFontColor: string = "#000" + + build() { + Column() { + Flex({ direction: FlexDirection.Column, + alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.keyValue.content).fontSize(20).fontColor(this.keyFontColor) + } + } + .backgroundColor(this.keyBgc) + .borderRadius(6) + .width("8%") + .height("65%") + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Down) { + globalThis.textInputClient.insertText(this.keyValue.content); + } + }) + } + } + + // 删除组件 + @Component + export struct deleteItem { + @State keyBgc: string = "#fff" + @State keyFontColor: string = "#000" + + build() { + Column() { + Flex({ direction: FlexDirection.Column, + alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text("删除").fontSize(20).fontColor(this.keyFontColor) + } + } + .backgroundColor(this.keyBgc) + .width("13%") + .borderRadius(6) + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Down) { + globalThis.textInputClient.deleteForward(1); + } + }) + } + } + + // 数字键盘 + @Component + struct numberMenu { + private numberList: sourceListType[] + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) { + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + ForEach(this.numberList, (item: sourceListType) => { // 数字键盘第一行 + keyItem({ keyValue: item }) + }, (item: sourceListType) => item.content); + } + .padding({ top: "2%" }) + .width("96%") + .height("25%") + + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + deleteItem() + } + .width("96%") + .height("25%") + } + } + } + + @Entry + @Component + struct Index { + private numberList: sourceListType[] = numberSourceListData + + build() { + Stack() { + Flex({ + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.End + }) { + Flex({ + direction: FlexDirection.Column, + alignItems: ItemAlign.Center, + justifyContent: FlexAlign.SpaceBetween + }) { + numberMenu({ + numberList: this.numberList + }) + } + .align(Alignment.End) + .width("100%") + .height("75%") + } + .height("100%").align(Alignment.End).backgroundColor("#cdd0d7") + } + .position({ x: 0, y: 0 }).zIndex(99999) + } + } + ``` + +5. 在工程Module对应的[module.json5配置文件](../quick-start/module-configuration-file.md)中注册InputMethodExtensionAbility,type标签需要设置为“inputMethod”,srcEntrance标签表示当前InputMethodExtensionAbility组件所对应的代码路径。 + + ```ts + { + "module": { + // ... + "extensionAbilities": [ + { + "description": "输入法Demo", + "icon": "$media:icon", + "name": "InputDemoService", + "srcEntrance": "./ets/InputMethodExtAbility/InputMethodService.ts", + "type": "inputMethod", + "visible": true, + } + ] + } + } + ``` + + + + +## 相关示例 + +针对InputMethodExtensionAbility开发,有以下相关示例可供参考: + +[Kika输入法](https://gitee.com/openharmony/applications_app_samples/tree/master/CompleteApps/KikaInput) \ No newline at end of file diff --git a/zh-cn/application-dev/application-models/widget-development-stage.md b/zh-cn/application-dev/application-models/widget-development-stage.md index 2064bf7b7175cf87f7777103686f41f46395ad58..92ec84dd96bcf6847a3c4f65d1659eabcc1e4b05 100644 --- a/zh-cn/application-dev/application-models/widget-development-stage.md +++ b/zh-cn/application-dev/application-models/widget-development-stage.md @@ -594,6 +594,17 @@ onUpdateForm(formId) { }; ``` +## 限制 + +为了降低FormExtensionAbility能力被三方应用滥用的风险,在FormExtensionAbility中限制以下接口的调用 + +- @ohos.ability.particleAbility.d.ts +- @ohos.backgroundTaskManager.d.ts +- @ohos.resourceschedule.backgroundTaskManager.d.ts +- @ohos.multimedia.camera.d.ts +- @ohos.multimedia.audio.d.ts +- @ohos.multimedia.media.d.ts + ## 相关实例 针对Stage模型卡片提供方的开发,有以下相关实例可供参考: diff --git a/zh-cn/application-dev/application-models/windowextensionability.md b/zh-cn/application-dev/application-models/windowextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..97123053757adc7f27bc8d61593c7d321b3699ff --- /dev/null +++ b/zh-cn/application-dev/application-models/windowextensionability.md @@ -0,0 +1,120 @@ +# WindowExtensionAbility + + +[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md)是一种ExtensionAbility组件,用于提供界面组合扩展能力,允许系统应用进行跨应用的界面拉起和嵌入。 + + +WindowExtensionAbility必须和[AbilityComponent](../reference/arkui-ts/ts-container-ability-component.md)一起配合使用,并根据需求处理被拉起应用的业务。WindowExtensionAbility支持以连接形式运行,系统应用必须添加AbilityComponent组件启动WindowExtensionAbility服务。 + + +每个ExtensionAbility都有自己的Context,WindowExtensionAbility通过 +[WindowExtensionContext](../reference/apis/js-apis-inner-application-windowExtensionContext.md)提供相关能力。本文描述中称被启动的WindowExtensionAbility为提供方,称启动WindowExtensionAbility的AbilityComponent组件为使用方。 + +> **说明:** +> +> 本接口为系统接口,如果三方开发者想要实现应用进行跨应用的界面拉起和嵌入,请参考[full-SDK替换指南](../../application-dev/quick-start/full-sdk-switch-guide.md)将SDK替换为full-SDK。 +> + + +## 设置一个嵌入式Ability(仅对系统应用开放) + +WindowExtensionAbility提供了onConnect()、onDisconnect()和onWindowReady()生命周期回调,根据需要重写对应的回调方法。 + +- **onWindowReady**:当该Ability的应用窗口创建成功时触发该回调。 + +- **onConnect**:当窗口扩展组件AbilityComponent连接该Ability时回调。 + +- **onDisconnect**:当窗口扩展组件AbilityComponent断开与该Ability的连接时回调。 + + +**开发步骤** + +开发者在实现一个嵌入式应用时,需要在DevEco Studio工程中手动新建一个WindowExtensionAbility,具体步骤如下。 + +1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为WindowExtAbility。 + +2. 在WindowExtAbility目录,右键选择“New > ts File”,新建一个.ts文件并命名为WindowExtAbility.ts。 + +3. 打开WindowExtAbility.ts文件,导入WindowExtensionAbility的依赖包,自定义类继承WindowExtensionAbility并实现onWindowReady()、onConnect()和onDisconnect()生命周期回调。 + + ```ts + import Extension from '@ohos.application.WindowExtensionAbility' + + export default class WindowExtAbility extends Extension { + onWindowReady(window) { + window.loadContent('WindowExtAbility/pages/index1').then(() => { + window.getProperties().then((pro) => { + console.log("WindowExtension " + JSON.stringify(pro)); + }) + window.show(); + }) + } + + onConnect(want) { + console.info('JSWindowExtension onConnect ' + want.abilityName); + } + + onDisconnect(want) { + console.info('JSWindowExtension onDisconnect ' + want.abilityName); + } + } + ``` + +4. 在工程Module对应的[module.json5配置文件](../quick-start/module-configuration-file.md)中注册WindowExtensionAbility,type标签需要设置为“window”,srcEntrance标签表示当前ExtensionAbility组件所对应的代码路径。 + + ```json + { + "module": { + "extensionAbilities": [ + { + "name": "WindowExtAbility", + "srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts", + "icon": "$media:icon", + "description": "WindowExtension", + "type": "window", + "visible": true, + } + ], + } + } + ``` + + +## 拉起一个嵌入式Ability(仅对系统应用开放) + +系统应用可以通过AbilityComponent容器加载创建好的WindowExtensionAbility。 + +**开发步骤** + +1. 开发者在连接一个嵌入式应用时,需要在DevEco Studio工程中相应的pages界面中加入AbilityComponent控件。 + +2. 在AbilityComponent控件中写入正确的bundleName和abilityName。 + +3. 设置好宽高。示例代码如下: + +```ts +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + AbilityComponent({ abilityName: "WindowExtAbility", bundleName: "com.example.WindowExtAbility"}) + .width(500) + .height(500) + } + .width('100%') + } + .height('100%') + .backgroundColor(0x64BB5c) + } +} +``` + +## 相关示例 + +针对WindowExtensionAbility开发,有以下相关示例可供参考: + +- [`WindowExtAbility`:WindowExtAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/WindowExtAbility) diff --git a/zh-cn/application-dev/connectivity/Readme-CN.md b/zh-cn/application-dev/connectivity/Readme-CN.md index 1a28dc8b9883f6579bdf232b594d48125e3faf12..b9d8b96bc47d12631c05765e6017c84a11d7f9c0 100755 --- a/zh-cn/application-dev/connectivity/Readme-CN.md +++ b/zh-cn/application-dev/connectivity/Readme-CN.md @@ -5,6 +5,10 @@ - [HTTP数据请求](http-request.md) - [WebSocket连接](websocket-connection.md) - [Socket连接](socket-connection.md) + - [策略管理](net-policy-management.md) + - [网络共享](net-sharing.md) + - [以太网连接](net-ethernet.md) + - [网络连接管理](net-connection-manager.md) - IPC与RPC通信 - [IPC与RPC通信概述](ipc-rpc-overview.md) - [IPC与RPC通信开发指导](ipc-rpc-development-guideline.md) diff --git a/zh-cn/application-dev/connectivity/net-connection-manager.md b/zh-cn/application-dev/connectivity/net-connection-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..d609a62b7e728a134b8b670f0914e199da838d38 --- /dev/null +++ b/zh-cn/application-dev/connectivity/net-connection-manager.md @@ -0,0 +1,246 @@ +# 网络连接管理 + +## 简介 +网络连接管理提供管理网络一些基础能力,包括WiFi/蜂窝/Ethernet等多网络连接优先级管理、网络质量评估、订阅默认/指定网络连接状态变化、查询网络连接信息、DNS解析等功能。 + +> **说明:** +> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-connection.md)。 + +## 基本概念 +- 网络生产者:数据网络的提供方,比如WiFi、蜂窝、Ethernet等。 +- 网络消费者:数据网络的使用方,比如应用或系统服务。 +- 网络探测:检测网络有效性,避免将网络从可用网络切换到不可用网络。内容包括绑定网络探测、DNS探测、HTTP探测及HTTPS探测。 +- 网络优选:处理多网络共存时选择最优网络。在网络状态、网络信息及评分发生变化时被触发。 + +## 约束 +- 开发语言:C++ JS +- 系统:linux内核 +- 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 场景介绍 +网络连接管理的典型场景有: +- 接收指定网络的状态变化通知 +- 获取所有注册的网络 +- 根据数据网络查询网络的连接信息 +- 使用对应网络解析域名,获取所有IP + +以下分别介绍具体开发方式。 +## 接口说明 +完整的JS API说明以及实例代码请参考:[网络连接管理](../reference/apis/js-apis-net-connection.md)。 + +| 类型 | 接口 | 功能说明 | +| ---- | ---- | ---- | +| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\): void; |获取一个含有默认网络的netId的NetHandle对象,使用callback回调 | +| ohos.net.connection | function getGlobalHttpProxy10+(callback: AsyncCallback\): void;| 获取网络的全局代理设置,使用callback回调 | +| ohos.net.connection | function setGlobalHttpProxy10+(httpProxy: HttpProxy, callback: AsyncCallback): void;| 设置网络全局Http代理配置信息,使用callback回调 | +| ohos.net.connection | function getAppNet9+(callback: AsyncCallback\): void;| 获取一个App绑定的包含了网络netId的NetHandle对象,使用callback回调 | +| ohos.net.connection | function setAppNet9+(netHandle: NetHandle, callback: AsyncCallback\): void;| 绑定App到指定网络,绑定后的App只能通过指定网络访问外网。使用callback回调 | +| ohos.net.connection | function getDefaultNetSync9+(): NetHandle; |使用同步方法获取默认激活的数据网络。可以使用getNetCapabilities去获取网络的类型、拥有的能力等信息。| +| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\): void; |查询是否有默认网络,使用callback回调 | +| ohos.net.connection | function getAllNets(callback: AsyncCallback\>): void;| 获取所处于连接状态的网络的MetHandle对象列表,使用callback回调 | +| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void; |查询默认网络的链路信息,使用callback回调 | +| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void; |查询默认网络的能力集信息,使用callback回调 | +| ohos.net.connection | function isDefaultNetMetered9+(callback: AsyncCallback): void; |检查当前网络上的数据流量使用是否被计量,使用callback方式作为异步方法 | +| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\): void;| 向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。使用callback回调 | +| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\): void;| 向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。使用callback回调 | +| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\>): void; |使用对应网络解析域名,获取所有IP,使用callback回调 | +| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\): void; | 设置网络为飞行模式,使用callback回调 | +| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\): void;| 关闭网络飞行模式,使用callback回调 | +| ohos.net.connection | function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | 返回一个NetConnection对象,netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络 | +| ohos.net.connection.NetHandle | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; | 将TCPSocket或UDPSockett绑定到当前网络,使用callback回调 | +| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\>): void; |使用默认网络解析域名,获取所有IP,使用callback回调 | +| ohos.net.connection.NetHandle | getAddressByName(host: string, callback: AsyncCallback\): void; |使用对应网络解析域名,获取一个IP,调用callbac | +| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\): void; |监听收到网络可用的事件 | +| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |监听网络能力变化的事件 | +| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |监听网络连接信息变化的事件 | +| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |订阅网络阻塞状态事件,使用callback方式作为异步方法 | +| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\): void; |监听网络丢失的事件 | +| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\): void; |监听网络不可用的事件 | +| ohos.net.connection.NetConnection | register(callback: AsyncCallback\): void; |注册默认网络或者createNetConnection中指定的网络的监听 | +| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\): void; |注销默认网络或者createNetConnection中指定的网络的监听 | + +## 接收指定网络的状态变化通知 + +1. 从@ohos.net.connection.d.ts中导入connection命名空间。 + +2. 调用createNetConnection方法,指定网络能力、网络类型和超时时间(可选,如不传入代表默认网络;创建不同于默认网络时可通过指定这些参数完成),创建一个NetConnection对象。 + +3. 调用该对象的on()方法,传入type和callback,订阅关心的事件。 + +4. 调用该对象的register()方法,订阅指定网络状态变化的通知。 + +5. 当网络可用时,会收到netAvailable事件的回调;当网络不可用时,会收到netUnavailable事件的回调。 + +6. 当不使用该网络时,可以调用该对象的unregister()方法,取消订阅。 + +```js + // 引入包名 + import connection from '@ohos.net.connection' + + let netCap = { + // 假设当前默认网络是WiFi,需要创建蜂窝网络连接,可指定网络类型为蜂窝网 + bearerTypes: [connection.NetBearType.BEARER_CELLULAR], + // 指定网络能力为Internet + networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], + }; + let netSpec = { + netCapabilities: netCap, + }; + + // 指定超时时间为10s(默认值为0) + let timeout = 10 * 1000; + + // 创建NetConnection对象 + let conn = connection.createNetConnection(netSpec, timeout); + + // 订阅事件,如果当前指定网络可用,通过on_netAvailable通知用户 + conn.on('netAvailable', (data=> { + console.log("net is available, netId is " + data.netId); + })); + + // 订阅事件,如果当前指定网络不可用,通过on_netUnavailable通知用户 + conn.on('netUnavailable', (data=> { + console.log("net is unavailable, netId is " + data.netId); + })); + + // 订阅指定网络状态变化的通知 + conn.register((err, data) => {}); + + // 当不使用该网络时,可以调用该对象的unregister()方法,取消订阅 + conn.unregister((err, data) => {}); +``` + +## 获取所有注册的网络 + +### 开发步骤 + +1. 从@ohos.net.connection.d.ts中导入connection命名空间。 + +2. 调用getAllNets方法,获取所有处于连接状态的网络列表。 + +```js + // 引入包名 + import connection from '@ohos.net.connection' + + // 获取所有处于连接状态的网络列表 + connection.getAllNets((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netList = data; + } + }) +``` + +## 根据数据网络查询网络的能力信息及连接信息 + +### 开发步骤 + +1. 从@ohos.net.connection.d.ts中导入connection命名空间。 + +2. 通过调用getDefaultNet方法,获取默认的数据网络(NetHandle);或者通过调用getAllNets方法,获取所有处于连接状态的网络列表(Array\)。 + +3. 调用getNetCapabilities方法,获取NetHandle对应网络的能力信息。能力信息包含了网络类型(蜂窝网络、Wi-Fi网络、以太网网络等)、网络具体能力等网络信息。 + +4. 调用getConnectionProperties方法,获取NetHandle对应网络的连接信息。 + +```js + // 引入包名 + import connection from '@ohos.net.connection' + + // 调用getDefaultNet方法,获取默认的数据网络(NetHandle) + connection.getDefaultNet((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netHandle = data; + } + }) + + // 获取netHandle对应网络的能力信息。能力信息包含了网络类型、网络具体能力等网络信息 + connection.getNetCapabilities(this.netHandle, (err, data) => { + console.log(JSON.stringify(err)); + + // 获取网络类型(bearerTypes) + for (let item of data.bearerTypes) { + if (item == 0) { + // 蜂窝网 + console.log(JSON.stringify("BEARER_CELLULAR")); + } else if (item == 1) { + // Wi-Fi网络 + console.log(JSON.stringify("BEARER_WIFI")); + } else if (item == 3) { + // 以太网网络 + console.log(JSON.stringify("BEARER_ETHERNET")); + } + } + + // 获取网络具体能力(networkCap) + for (let item of data.networkCap) { + if (item == 0) { + // 表示网络可以访问运营商的MMSC(Multimedia Message Service,多媒体短信服务)发送和接收彩信 + console.log(JSON.stringify("NET_CAPABILITY_MMS")); + } else if (item == 11) { + // 表示网络流量未被计费 + console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); + } else if (item == 12) { + // 表示该网络应具有访问Internet的能力,该能力由网络提供者设置 + console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); + } else if (item == 15) { + // 表示网络不使用VPN(Virtual Private Network,虚拟专用网络) + console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); + } else if (item == 16) { + // 表示该网络访问Internet的能力被网络管理成功验证,该能力由网络管理模块设置 + console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); + } + } + }) + + // 获取netHandle对应网络的连接信息。连接信息包含了链路信息、路由信息等 + connection.getConnectionProperties(this.netHandle, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + + // 调用getAllNets,获取所有处于连接状态的网络列表(Array) + connection.getAllNets((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + if (data) { + this.netList = data; + } + }) + + for (let item of this.netList) { + // 循环获取网络列表每个netHandle对应网络的能力信息 + connection.getNetCapabilities(item, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + + // 循环获取网络列表每个netHandle对应的网络的连接信息 + connection.getConnectionProperties(item, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) + } +``` + +## 使用对应网络解析域名,获取所有IP + +### 开发步骤 + +1. 从@ohos.net.connection.d.ts中导入connection命名空间。 + +2. 调用getAddressesByName方法,使用默认网络解析主机名以获取所有IP地址。 + +```js + // 引入包名 + import connection from '@ohos.net.connection' + + // 使用默认网络解析主机名以获取所有IP地址 + connection.getAddressesByName(this.host, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }) +``` diff --git a/zh-cn/application-dev/connectivity/net-ethernet.md b/zh-cn/application-dev/connectivity/net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..5a324646920897e2f5b552618d1f33e213c25fbd --- /dev/null +++ b/zh-cn/application-dev/connectivity/net-ethernet.md @@ -0,0 +1,140 @@ +# 以太网连接 + +## 简介 +以太网连接的功能是提供支持设备通过硬件接口,以插入网线的形式访问互联网的能力。 +设备接入网线后,可以获取动态分配的IP地址,子网掩码,Gateway,DNS等一系列网络属性;通过静态模式,手动配置与获取设备的网络属性。 + +> **说明:** +> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-ethernet.md)。 + +## 约束 +- 开发语言:C++ JS +- 系统:linux内核 +- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 场景介绍 +以太网连接的典型场景有: +- DHCP模式,通过动态分配IP地址,子网掩码,Gateway,DNS等一系列网络属性,使能访问网络。 +- 静态模式,通过静态配置IP地址,子网掩码,Gateway,DNS等一系列网络属性,使能访问网络。 + +以下分别介绍具体开发方式。 + +## 接口说明 +完整的JS API说明以及实例代码请参考:[以太网连接](../reference/apis/js-apis-net-ethernet.md)。 + +| 类型 | 接口 | 功能说明 | +| ---- | ---- | ---- | +| ohos.net.ethernet | function setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void | 配置指定以太网的网络属性,iface为网口名称,ic为配置信息,调用callback | +| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\): void | 获取指定以太网的网络属性,iface为网口名称,调用callback | +| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\): void | 判断指定网口是否已激活,iface为网卡名称(无参为是否有激活网口),调用callback | +| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\>): void; | 获取所有活动的网络接口,调用callback | + +## 以太网连接-DHCP模式 + +1. 设备通过硬件接口,插入网线。 +2. 从@ohos.net.ethernet中导入ethernet命名空间。 +3. 调用getAllActiveIfaces方法,获取所有激活的有线网卡名称,如:“eth0”,“eth1”。 +4. 用户态通过isIfaceActive方法,来判断网口“eth0”是否已激活。 +5. 用户态通过getIfaceConfig方法,来获取指定网口“eth0”的网络属性,未设置过的以太网络默认为DHCP模式,获取自动分配的网络属性。 + +```js + // 从@ohos.net.ethernet中导入ethernet命名空间 + import ethernet from '@ohos.net.ethernet' + + // getAllActiveIfaces获取所有活动的网络设备名称 + ethernet.getAllActiveIfaces((error, data) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces callback = " + data[i]); + } + } + }); + + // isIfaceActive判断指定网口是否已激活 + ethernet.isIfaceActive("eth0", (error, data) => { + if (error) { + console.log("isIfaceActive callback error = " + error); + } else { + console.log("isIfaceActive callback = " + data); + } + }); + + // getIfaceConfig获取指定以太网的网络属性 + ethernet.getIfaceConfig("eth0", (error, data) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + data.mode); + console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); + } + }); +``` +## 以太网连接-静态模式 + +### 开发步骤 + +1. 设备通过硬件接口,插入网线。 +2. 从@ohos.net.ethernet中导入ethernet命名空间。 +3. 用户态通过getAllActiveIfaces方法,来获取所有活动的网络设备名称,如:“eth0”,“eth1”。 +4. 用户态通过isIfaceActive方法,来判断网口“eth0”是否已激活。 +5. 用户态调用setIfaceConfig方法,来设置指定网口"eth0"为静态模式,手动IP地址,子网掩码,Gateway,DNS等网络属性。 +6. 用户态通过getIfaceConfig方法,来获取指定网口“eth0”的静态网络属性。 + +```js + // 从@ohos.net.ethernet中导入ethernet命名空间 + import ethernet from '@ohos.net.ethernet' + + // getAllActiveIfaces获取所有活动的网络设备名称 + ethernet.getAllActiveIfaces((error, data) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces callback = " + data[i]); + } + } + }); + + // isIfaceActive判断指定网口是否已激活 + ethernet.isIfaceActive("eth0", (error, data) => { + if (error) { + console.log("isIfaceActive callback error = " + error); + } else { + console.log("isIfaceActive callback = " + data); + } + }); + + // setIfaceConfig配置指定以太网的网络属性 + ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", + gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => { + if (error) { + console.log("setIfaceConfig callback error = " + error); + } else { + console.log("setIfaceConfig callback ok "); + } + }); + + // getIfaceConfig获取指定以太网的网络属性 + ethernet.getIfaceConfig("eth0", (error, data) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + data.mode); + console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); + } + }); +``` diff --git a/zh-cn/application-dev/connectivity/net-mgmt-overview.md b/zh-cn/application-dev/connectivity/net-mgmt-overview.md index dcb27c69e07d6d4dae5e4d446dab144d02e88c08..30846a21c524a0f5e4ef9c9f0b95c2f39b6b614a 100644 --- a/zh-cn/application-dev/connectivity/net-mgmt-overview.md +++ b/zh-cn/application-dev/connectivity/net-mgmt-overview.md @@ -5,6 +5,10 @@ - [HTTP数据请求](http-request.md):通过HTTP发起一个数据请求。 - [WebSocket连接](websocket-connection.md):使用WebSocket建立服务器与客户端的双向连接。 - [Socket连接](socket-connection.md):通过Socket进行数据传输。 +- [网络策略管理](net-policy-management.md):提供一些限制网络的基础能力,包括蜂窝网络策略、休眠/省电模式策略、后台网络策略、重置网络策略等功能。 +- [网络共享](net-sharing.md):分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。 +- [以太网连接](net-ethernet.md):以太网连接主要提供有线网络能力,提供设置有线网络的IP地址,子网掩码,网关,DNS等信息。 +- [网络连接管理](net-connection-manager.md):网络连接管理提供管理网络一些基础能力,包括WiFi/蜂窝/Ethernet等多网络连接优先级管理、网络质量评估、订阅默认/指定网络连接状态变化、查询网络连接信息、DNS解析等功能。 ## 约束与限制 diff --git a/zh-cn/application-dev/connectivity/net-policy-management.md b/zh-cn/application-dev/connectivity/net-policy-management.md new file mode 100644 index 0000000000000000000000000000000000000000..01b2305c44eeba0452611a127dda3a7752845054 --- /dev/null +++ b/zh-cn/application-dev/connectivity/net-policy-management.md @@ -0,0 +1,402 @@ +# 网络策略管理部件 + +## 简介 + +网络策略管理提供一些限制网络的基础能力,包括蜂窝网络策略、休眠/省电模式策略、后台网络策略、重置网络策略等功能。 + +> **说明:** +> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-policy.md)。 + +## 基本概念 + +- 休眠模式:设备在不需要工作的时候把一些部件、外设关掉(进入低功耗模式),并限制部分应用对网络的访问。 +- 省电模式:省电模式是系统里的一个开关,开启后会降低设备的性能,并限制部分应用对网络的访问。 +- 省流量模式:即后台网络策略,对处于后台的使用计量网络的应用进行限制。 +- 蜂窝网络:移动通信网络。 +- 计量网络:设置了流量配额的电话卡网络、Wlan网络以及以太网。 + +## 约束 + +- 开发语言:C++ JS +- 系统:linux内核 +- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 场景介绍 + +网络策略管理的典型场景有: + +- 设置计量网络配额/获取已经设置的计量网络策略 +- 后台网络限制开关/获取后台网络限制状态/获取指定uid在后台状态下能否访问网络 +- 设定指定uid访问计量网络的策略/获取指定uid访问计量网络的策略/获取设置了对应策略的uids +- 重置网络策略 +- 判断uid能否访问计量/非计量网络 +- 将对应uid从休眠白名单里添加、移除/获取休眠模式的白名单列表 +- 将对应uid从省电白名单里添加、移除/获取省电模式的白名单列表 +- 更新网络提醒策略 + +以下分别介绍具体开发方式。 + +## 接口说明 + +完整的JS API说明以及实例代码请参考:[网络策略管理](../reference/apis/js-apis-net-policy.md)。 + +| 类型 | 接口 | 功能说明 | +| ---- | ---- | ---- | +| ohos.net.policy | function setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void |设置后台网络策略,使用callback方式作为异步方法 | +| ohos.net.policy | function isBackgroundAllowed(callback: AsyncCallback\): void; |获取后台网络策略,使用callback方式作为异步方法 | +| ohos.net.policy | function setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void; |设置对应uid应用的访问计量网络的策略,使用callback方式作为异步方法 | +| ohos.net.policy | function getPolicyByUid(uid: number, callback: AsyncCallback\): void;| 通过应用uid获取策略,使用callback方式作为异步方法 | +| ohos.net.policy | function getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void; | 通过策略获取设置这一策略的应用uid数组,使用callback方式作为异步方法 | +| ohos.net.policy | function getNetQuotaPolicies(callback: AsyncCallback\>): void; |获取计量网络策略,使用callback方式作为异步方法 | +| ohos.net.policy | function setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void; |设置计量网络策略,使用callback方式作为异步方法 | +| ohos.net.policy | function restoreAllPolicies(iccid: string, callback: AsyncCallback\): void; | 重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用callback方式作为异步方法 | +| ohos.net.policy | function isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void; | 获取对应uid能否访问计量或非计量网络,使用callback方式作为异步方法 | +| ohos.net.policy | function isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void; | 获取对应uid能否访问指定的iface的网络,使用callback方式作为异步方法 | +| ohos.net.policy | function setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; | 设置指定uid应用是否在休眠防火墙的白名单,使用callback方式作为异步方法 | +| ohos.net.policy | function getDeviceIdleAllowList(callback: AsyncCallback\>): void; | 获取休眠模式白名单所包含的uid数组,使用callback方式作为异步方法 | +| ohos.net.policy | function getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void; | 获取指定uid能否访问后台网络,使用callback方式作为异步方法 | +| ohos.net.policy | function resetPolicies(iccid: string, callback: AsyncCallback\): void; | 重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用callback方式作为异步方法 | +| ohos.net.policy | function updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void; | 更新提醒策略,使用callback方式作为异步方法 | +| ohos.net.policy | function setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; | 设置指定uid应用是否在省电防火墙的白名单,使用callback方式作为异步方法 | +| ohos.net.policy | function getPowerSaveAllowList(callback: AsyncCallback\>): void; | 获取省电模式白名单所包含的uid数组,使用callback方式作为异步方法 | +| ohos.net.policy | function on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; | 订阅policy发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function off(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; | 取消订阅policy发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; | 订阅rule发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function off(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; | 取消订阅rule发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function on(type: "netMeteredIfacesChange", callback: Callback\>): void; | 订阅计量iface发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function off(type: "netMeteredIfacesChange", callback: Callback\>): void; | 取消订阅计量iface发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function on(type: "netQuotaPolicyChange", callback: Callback\>): void; | 订阅计量网络策略发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function off(type: "netQuotaPolicyChange", callback: Callback\>): void; | 取消订阅计量网络策略发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function on(type: "netBackgroundPolicyChange", callback: Callback\): void; | 订阅后台网络策略发生改变时的回调,使用callback方式作为异步方法 | +| ohos.net.policy | function off(type: "netBackgroundPolicyChange", callback: Callback\): void; | 取消订阅后台网络策略发生改变时的回调,使用callback方式作为异步方法 | + +## 设置计量网络配额/获取已经设置的计量网络策略 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用setNetQuotaPolicies方法,设置计量网络策略。 + +3. 调用getNetQuotaPolicies方法,获取计量网络策略。 + +```js + // 引入包名 + import policy from '@ohos.net.policy'; + + addNetQuotaPolicy(){ + let param = { + // netType值详见 [NetBearType](../reference/apis/js-apis-net-connection.md#netbeartype) + netType:Number.parseInt(this.netType), + + // 计量蜂窝网络的SIM卡的标识值。以太网,wifi网络不会用到 + iccid:this.iccid, + + // 计量蜂窝网络中配合iccid联合使用。以太网,wifi网络单独使用。用于标记类型 + ident:this.ident, + + // 计量开始时间。例如M1、D1、Y1等 + periodDuration:this.periodDuration, + + // 发出警告的流量阈值 大于0的整数即可 + warningBytes:Number.parseInt(this.warningBytes), + + // 流量设置的配额 大于0的整数即可 + limitBytes:Number.parseInt(this.limitBytes), + + // 是否为计量网络 true为计量网络 false为非计量网络 + metered:Boolean(Number.parseInt(this.metered)),https://gitee.com/openharmony/docs/pulls/14404 + // 到达流量限制后的动作 详见[LimitAction](../reference/apis/js-apis-net-policy.md#limitaction) + limitAction:Number.parseInt(this.limitAction) + }; + this.netQuotaPolicyList.push(param); + }, + + // 订阅计量网络iface发生改变时的回调 + policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange:' + JSON.stringify(data)); + }); + + // 订阅计量网络策略发生改变时的回调 + policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange:' + JSON.stringify(data)); + }); + + // 调用setNetQuotaPolicies方法,设置计量网络策略 + setNetQuotaPolicies(){ + this.dialogType = DialogType.HIDE; + policy.setNetQuotaPolicies(this.netQuotaPolicyList, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)); + }); + }, + + // 调用getNetQuotaPolicies方法,获取计量网络策略 + getNetQuotaPolicies(){ + policy.getNetQuotaPolicies((err, data) => { + this.callBack(err, data); + if(data){ + this.netQuotaPolicyList = data; + } + }); + }, + + // 取消订阅计量网络iface发生改变时的回调 + policy.off('netMeteredIfacesChange', (data) => { + this.log('off netMeteredIfacesChange:' + JSON.stringify(data)); + }); + + // 取消订阅计量网络策略发生改变时的回调 + policy.off('netQuotaPolicyChange', (data) => { + this.log('off netQuotaPolicyChange:' + JSON.stringify(data)); + }); +``` + +## 后台网络限制开关/获取后台网络限制状态/获取指定uid在后台状态下能否访问网络 + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用setBackgroundAllowed方法,设置开启后台省流量或关闭后台省流量。 + +3. 调用isBackgroundAllowed方法,获取后台网络限制状态(省流量)是开启还是关闭。 + +4. 调用getBackgroundPolicyByUid方法,获取指定uid在后台状态下能否访问网络。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 订阅后台网络策略发生改变时的回调 + policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange:' + JSON.stringify(data)); + }); + + // 调用setBackgroundAllowed方法,设置开启后台省流量或关闭后台省流量 + setBackgroundAllowed() { + policy.setBackgroundAllowed(Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 调用isBackgroundAllowed方法,获取后台网络限制状态(省流量)是开启还是关闭。 + isBackgroundAllowed() { + policy.isBackgroundAllowed((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 调用getBackgroundPolicyByUid方法,获取指定uid在后台状态下能否访问网络。 + getBackgroundPolicyByUid() { + policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 取消订阅后台网络策略发生改变时的回调 + policy.off('netBackgroundPolicyChange', (data) => { + this.log('off netBackgroundPolicyChange:' + JSON.stringify(data)); + }); +``` + +## 设定指定uid访问计量网络的策略/获取指定uid访问计量网络的策略/获取设置了对应策略的uids + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用setPolicyByUid方法,设置指定uid是否可以访问后台网络。 + +3. 调用getPolicyByUid方法,获取指定uid的策略。 + +4. 调用getUidsByPolicy方法,获取使用指定策略的uids。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 订阅uid的policy发生改变时的回调 + policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange:' + JSON.stringify(data)); + }); + + // 订阅uid的rule发生改变时的回调 + policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange:' + JSON.stringify(data)); + }); + + // 调用setPolicyByUid方法,设置指定uid是否可以访问后台网络 + setPolicyByUid() { + let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) + } + policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 调用getPolicyByUid方法,获取指定uid的策略 + getPolicyByUid() { + policy.getPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 调用getUidsByPolicy方法,获取使用指定策略的uids + getUidsByPolicy(){ + policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 取消订阅uid的policy发生改变时的回调 + policy.off('netUidPolicyChange', (data) => { + this.log('off netUidPolicyChange:' + JSON.stringify(data)); + }); + + // 取消订阅uid的rule发生改变时的回调 + policy.off('netUidRuleChange', (data) => { + this.log('off netUidRuleChange:' + JSON.stringify(data)); + }); + +``` + +## 重置网络策略 + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用restoreAllPolicies方法,重置网络策略。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 调用restoreAllPolicies方法,重置网络策略 + restoreAllPolicies(){ + policy.restoreAllPolicies(this.firstParam, (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## 判断uid能否访问计量/非计量网络 + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用isUidNetAllowed方法,获取uid能否访问计量/非计量网络。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 调用isUidNetAllowed方法,获取uid能否访问计量/非计量网络 + isUidNetAllowedIsMetered(){ + let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) + } + policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## 将对应uid从休眠白名单里添加、移除/获取休眠模式的白名单列表 + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用setDeviceIdleAllowList方法,设置uid是否添加到休眠模式白名单。 + +3. 调用getDeviceIdleAllowList方法,获取添加在休眠模式白名单的uids。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 调用setDeviceIdleAllowList方法,设置uid是否添加到休眠模式白名单 + setDeviceIdleAllowList(){ + let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + } + policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 调用getDeviceIdleAllowList方法,获取添加在休眠模式白名单的uids + getDeviceIdleAllowList(){ + policy.getDeviceIdleAllowList((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## 将对应uid从省电白名单里添加、移除/获取省电模式的白名单列表 + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 +2. 调用setPowerSaveAllowList方法,设置uid是否添加到省电模式白名单。 +3. 调用getPowerSaveAllowList方法,获取添加在省电模式白名单的uids。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 调用setPowerSaveAllowList方法,设置uid是否添加到省电模式白名单 + setPowerSaveAllowList(){ + let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) + } + policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, + + // 调用getPowerSaveAllowList方法,获取添加在省电模式白名单的uids + getPowerSaveAllowList(){ + policy.getPowerSaveAllowList((err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` + +## 更新网络提醒策略 + +### 开发步骤 + +1. 从@ohos.net.policy.d.ts中导入policy命名空间。 + +2. 调用updateRemindPolicy,更新网络提醒策略。 + +```js + // 引入包名 + import policy from '@ohos.net.policy' + + // 调用updateRemindPolicy,更新网络提醒策略 + updateRemindPolicy() { + let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType + } + policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (err, data) => { + console.log(JSON.stringify(err)); + console.log(JSON.stringify(data)) + }); + }, +``` \ No newline at end of file diff --git a/zh-cn/application-dev/connectivity/net-sharing.md b/zh-cn/application-dev/connectivity/net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..337939b95247169c84a6bbae1e3fb313b27afd82 --- /dev/null +++ b/zh-cn/application-dev/connectivity/net-sharing.md @@ -0,0 +1,130 @@ +# 网络共享 + +## 简介 +网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。 + +> **说明:** +> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-sharing.md)。 + +## 基本概念 +- WIFI共享:通过WIFI热点共享网络。 +- 蓝牙共享:通过蓝牙共享网络。 +- USB共享:通过USB共享网络。 + +## 约束 +- 开发语言:C++ JS +- 系统:linux内核 +- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 场景介绍 +网络共享的典型场景有: +- 开启网络共享 +- 停止网络共享 +- 获取共享网络的数据流量 + +以下分别介绍具体开发方式。 +## 接口说明 +完整的JS API说明以及实例代码请参考:[网络共享](../reference/apis/js-apis-net-sharing.md)。 + +| 类型 | 接口 | 功能说明 | +| ---- | ---- | ---- | +| ohos.net.sharing | function isSharingSupported(callback: AsyncCallback\): void; | 获取当前系统是否支持网络共享,使用callback方式作为异步方法 | +| ohos.net.sharing | function isSharing(callback: AsyncCallback\): void; | 获取当前共享状态,使用callback方式作为异步方法 | +| ohos.net.sharing | function startSharing(type: SharingIfaceType, callback: AsyncCallback\): void; | 开启共享,type为共享类型,目前支持Wifi热点、蓝牙、USB,使用callback方式作为异步方法 | +| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void; | 停止指定类型共享,type为共享类型,包括Wifi热点、蓝牙、USB,使用callback方式作为异步方法 | +| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\): void; | 获取共享接收数据量,单位KB,使用callback方式作为异步方法 | +| ohos.net.sharing | function getStatsTxBytes(callback: AsyncCallback\): void; | 获取共享发送数据量,单位KB,使用callback方式作为异步方法 | +| ohos.net.sharing | function getStatsTotalBytes(callback: AsyncCallback\): void; | 获取共享总数据流量,单位KB,使用callback方式作为异步方法 | +| ohos.net.sharing | function getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void; | 获取指定状态的网卡名称,state为状态,包括正在共享、可共享、共享错误,使用callback方式作为异步方法 | +| ohos.net.sharing | function getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void; | 获取指定类型共享状态,type为类型,目前支持Wifi热点、蓝牙、USB,使用callback方式作为异步方法 | +| ohos.net.sharing | function getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void; | 获取与指定类型匹配的网卡正则表达式列表,type为类型,目前支持Wifi热点、蓝牙、USB,使用callback方式作为异步方法 | +| ohos.net.sharing | function on(type: 'sharingStateChange', callback: Callback\): void; | 注册共享状态改变监听,返回网络共享的状态。 | +| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\): void; | 注销共享状态改变监听,返回网络共享的状态。 | +| ohos.net.sharing | unction on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | 注册指定网卡共享状态改变监听 | +| ohos.net.sharing | function off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | 注销指定网卡共享状态改变监听 | +| ohos.net.sharing | function on(type: 'sharingUpstreamChange', callback: Callback\): void; | 注册上行网卡改变监听 | +| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\): void; | 注销上行网卡改变监听 | + +## 开启网络共享 + +1. 从@ohos.net.sharing中导入sharing命名空间。 +2. 注册监听共享状态的改变。 +3. 调用startSharing方法,来开启指定类型共享。 +4. 接收到共享状态开启的回调,开启共享成功。 + +```js + // 从@ohos.net.sharing中导入sharing命名空间 + import sharing from '@ohos.net.sharing' + + // 注册监听共享状态的改变 + sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); + + // 调用startSharing方法,来开启指定类型共享 + sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); +``` + +## 停止网络共享 + +### 开发步骤 + +1. 从@ohos.net.sharing中导入sharing命名空间。 +2. 注册监听共享状态的改变。 +3. 调用stopSharing方法,来停止指定类型共享。 +4. 接收到共享状态关闭的回调,停止共享成功。 + +```js + // 从@ohos.net.sharing中导入sharing命名空间 + import sharing from '@ohos.net.sharing' + + // 注册监听共享状态的改变 + sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); + + // 调用stopSharing方法,来停止指定类型共享 + sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); +``` + +## 获取共享网络的数据流量 + +### 开发步骤 + +1. 从@ohos.net.sharing中导入sharing命名空间。 +2. 调用startSharing方法,来开启指定类型共享。 +3. 调用getStatsTotalBytes方法,来获取共享网络数据量。 +4. 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零。 + +```js + // 从@ohos.net.sharing中导入sharing命名空间 + import sharing from '@ohos.net.sharing' + + // 调用startSharing方法,来开启指定类型共享 + sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); + + // 调用getStatsTotalBytes方法,来获取共享网络数据量 + sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); + + // 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零 + sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); + }); + + // 再次调用getStatsTotalBytes方法,共享网络数据量已清零 + sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); + }); +``` diff --git a/zh-cn/application-dev/connectivity/socket-connection.md b/zh-cn/application-dev/connectivity/socket-connection.md index 815b0fde28387264cf5cf0c6effe7d27f8c44c44..ab896fdfe7ac0b9c5669b2df7e12614b30867c9d 100644 --- a/zh-cn/application-dev/connectivity/socket-connection.md +++ b/zh-cn/application-dev/connectivity/socket-connection.md @@ -1,13 +1,27 @@ # Socket连接 +## 简介 + +Socket连接主要是通过Socket进行数据传输,支持TCP/UDP/TLS协议。 + +## 基本概念 + +- Socket:套接字,就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。 +- TCP:传输控制协议(Transmission Control Protocol)。是一种面向连接的、可靠的、基于字节流的传输层通信协议。 +- UDP:用户数据报协议协议(User Datagram Protocol)。是一个简单的面向消息的传输层,不需要连接。 +- TLS:安全传输层协议(Transport Layer Security)。用于在两个通信应用程序之间提供保密性和数据完整性。 ## 场景介绍 -应用通过Socket进行数据传输,支持TCP和UDP两种协议。 +应用通过Socket进行数据传输,支持TCP/UDP/TLS协议。主要场景有: +- 应用通过TCP/UDP Socket进行数据传输 +- 应用通过TLS Socket进行加密数据传输 ## 接口说明 +完整的JS API说明以及实例代码请参考:[Socket连接](../reference/apis/js-apis-socket.md)。 + Socket连接主要由socket模块提供。具体接口说明如下表。 | 接口名 | 功能描述 | @@ -31,8 +45,30 @@ Socket连接主要由socket模块提供。具体接口说明如下表。 | on(type: 'connect') | 订阅TCPSocket的连接事件(仅TCP支持)。 | | off(type: 'connect') | 取消订阅TCPSocket的连接事件(仅TCP支持)。 | +TLS Socket连接主要由tls_socket模块提供。具体接口说明如下表。 -## 开发步骤 +| 接口名 | 功能描述 | +| -------- | -------- | +| bind() | 绑定IP地址和端口号。 | +| close(type: 'error') | 关闭连接。 | +| connect() | 连接到指定的IP地址和端口。 | +| getCertificate() | 返回表示本地证书的对象。 | +| getCipherSuite() | 返回包含协商的密码套件信息的列表。 | +| getProtocol() | 返回包含当前连接协商的SSL/TLS协议版本的字符串。 | +| getRemoteAddress() | 获取TLSSocket连接的对端地址。 | +| getRemoteCertificate() | 返回表示对等证书的对象。 | +| getSignatureAlgorithms() | 在服务器和客户端之间共享的签名算法列表,按优先级降序排列。 | +| getState() | 获取TLSSocket连接的状态。 | +| off(type: 'close') | 取消订阅TLSSocket连接的关闭事件。 | +| off(type: 'error') | 取消订阅TLSSocket连接的Error事件。 | +| off(type: 'message') | 取消订阅TLSSocket连接的接收消息事件。 | +| on(type: 'close') | 订阅TLSSocket连接的关闭事件。 | +| on(type: 'error') | 订阅TLSSocket连接的Error事件。 | +| on(type: 'message') | 订阅TLSSocket连接的接收消息事件。 | +| send() | 发送数据。 | +| setExtraOptions() | 设置TLSSocket连接的其他属性。 | + +## 应用TCP/UDP协议进行通信 UDP与TCP流程大体类似,下面以TCP为例: @@ -49,13 +85,13 @@ UDP与TCP流程大体类似,下面以TCP为例: 6. 发送数据。 7. Socket连接使用完毕后,主动关闭。 - + ```js import socket from '@ohos.net.socket' - + // 创建一个TCPSocket连接,返回一个TCPSocket对象。 let tcp = socket.constructTCPSocketInstance(); - + // 订阅TCPSocket相关的订阅事件 tcp.on('message', value => { console.log("on message") @@ -73,7 +109,7 @@ UDP与TCP流程大体类似,下面以TCP为例: tcp.on('close', () => { console.log("on close") }); - + // 绑定本地IP地址和端口。 let bindAddress = { address: '192.168.xx.xx', @@ -86,6 +122,7 @@ UDP与TCP流程大体类似,下面以TCP为例: return; } console.log('bind success'); + // 连接到指定的IP地址和端口。 let connectAddress = { address: '192.168.xx.xx', @@ -100,6 +137,7 @@ UDP与TCP流程大体类似,下面以TCP为例: return; } console.log('connect success'); + // 发送数据 tcp.send({ data: 'Hello, server!' @@ -112,6 +150,7 @@ UDP与TCP流程大体类似,下面以TCP为例: }) }); }); + // 连接使用完毕后,主动关闭。取消相关事件的订阅。 setTimeout(() => { tcp.close((err) => { @@ -123,8 +162,166 @@ UDP与TCP流程大体类似,下面以TCP为例: }, 30 * 1000); ``` +## 应用通过TLS Socket进行加密数据传输 + +### 开发步骤 + +客户端TLS Socket流程: + +1. import需要的socket模块。 + +2. 绑定服务器IP和端口号。 + +3. 双向认证上传客户端CA证书及数字证书;单向认证上传客户端CA证书。 + +4. 创建一个TLSSocket连接,返回一个TLSSocket对象。 + +5. (可选)订阅TLSSocket相关的订阅事件。 + +6. 发送数据。 + +7. TLSSocket连接使用完毕后,主动关闭。 + +```js + import socket from '@ohos.net.socket' + + // 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。 + let tlsTwoWay = socket.constructTLSSocketInstance(); + + // 订阅TLS Socket相关的订阅事件 + tcp.on('message', value => { + console.log("on message") + let buffer = value.message + let dataView = new DataView(buffer) + let str = "" + for (let i = 0; i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)) + } + console.log("on connect received:" + str) + }); + tcp.on('connect', () => { + console.log("on connect") + }); + tcp.on('close', () => { + console.log("on close") + }); + + // 绑定本地IP地址和端口。 + tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + }); + + // 设置通信过程中使用参数 + let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + + // 连接到指定的IP地址和端口。 + address: { + address: "192.168.xx.xxx", + port: xxxx, // 端口 + family: 1, + }, + + // 设置用于通信过程中完成校验的参数。 + secureOptions: { + key: "xxxx", // 密钥 + cert: "xxxx", // 数字证书 + ca: ["xxxx"], // CA证书 + passwd: "xxxx", // 生成密钥时的密码 + protocols: [socket.Protocol.TLSv12], // 通信协议 + useRemoteCipherPrefer: true, // 是否优先使用对端密码套件 + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法 + cipherSuite: "AES256-SHA256", // 密码套件 + }, + }; + + // 建立连接 + tlsTwoWay.connect(options, (err, data) => { + console.error(err); + console.log(data); + }); + + // 连接使用完毕后,主动关闭。取消相关事件的订阅。 + tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tls.off('message'); + tls.off('connect'); + tls.off('close'); + }); + + // 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。 + let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication + + // 订阅TLS Socket相关的订阅事件 + tcp.on('message', value => { + console.log("on message") + let buffer = value.message + let dataView = new DataView(buffer) + let str = "" + for (let i = 0;i < dataView.byteLength; ++i) { + str += String.fromCharCode(dataView.getUint8(i)) + } + console.log("on connect received:" + str) + }); + tcp.on('connect', () => { + console.log("on connect") + }); + tcp.on('close', () => { + console.log("on close") + }); + + // 绑定本地IP地址和端口。 + tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); + }); + + // 设置通信过程中使用参数 + let oneWayOptions = { + address: { + address: "192.168.xxx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + ca: ["xxxx","xxxx"], // CA证书 + cipherSuite: "AES256-SHA256", // 密码套件 + }, + }; + + // 建立连接 + tlsOneWay.connect(oneWayOptions, (err, data) => { + console.error(err); + console.log(data); + }); + + // 连接使用完毕后,主动关闭。取消相关事件的订阅。 + tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } + tls.off('message'); + tls.off('connect'); + tls.off('close'); + }); +``` + ## 相关实例 + 针对Socket连接开发,有以下相关实例可供参考: - [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) - [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) -- [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) \ No newline at end of file +- [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md index 6d62e1d6024c0faff563643d3ae9d5100c8c6f14..0eb66f5cd42022b1cf8ef6475cbcd280e9c2e63f 100644 --- a/zh-cn/application-dev/database/database-relational-guidelines.md +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -201,76 +201,81 @@ FA模型示例: ```js - import data_rdb from '@ohos.data.relationalStore' + import relationalStore from '@ohos.data.relationalStore' import featureAbility from '@ohos.ability.featureAbility' + var store; + // 获取context - let context = featureAbility.getContext() + let context = featureAbility.getContext(); const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + securityLevel: relationalStore.SecurityLevel.S1 + }; // 假设当前数据库版本为3 - data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - // 当数据库创建时,数据库默认版本为0 - if (rdbStore.version == 0) { - rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) - // 设置数据库的版本,入参为大于0的整数 - rdbStore.version = 3 - } + relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + // 当数据库创建时,数据库默认版本为0 + if (store.version == 0) { + store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null); + // 设置数据库的版本,入参为大于0的整数 + store.version = 3; + } - // 当数据库存在并假定版本为1时,例应用从某一版本升级到当前版本,数据库需要从1版本升级到2版本 - if (rdbStore.version != 3 && rdbStore.version == 1) { - // version = 1:表结构:student (id, age) => version = 2:表结构:student (id, age, score) - rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) - rdbStore.version = 2 - } + // 当数据库存在并假定版本为1时,例应用从某一版本升级到当前版本,数据库需要从1版本升级到2版本 + if (store.version != 3 && store.version == 1) { + // version = 1:表结构:student (id, age) => version = 2:表结构:student (id, age, score) + store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null); + store.version = 2; + } - // 当数据库存在并假定版本为2时,例应用从某一版本升级到当前版本,数据库需要从2版本升级到3版本 - if (rdbStore.version != 3 && rdbStore.version == 2) { - // version = 2:表结构:student (id, age, score) => version = 3:表结构:student (id, score) - rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) - rdbStore.version = 3 - } + // 当数据库存在并假定版本为2时,例应用从某一版本升级到当前版本,数据库需要从2版本升级到3版本 + if (store.version != 3 && store.version == 2) { + // version = 2:表结构:student (id, age, score) => version = 3:表结构:student (id, score) + store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null); + store.version = 3; + } }) ``` Stage模型示例: ```ts - import data_rdb from '@ohos.data.relationalStore' + import relationalStore from '@ohos.data.relationalStore' import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { - const STORE_CONFIG = { - name: "rdbstore.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + var store; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 + }; - // 假设当前数据库版本为3 - data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { - // 当数据库创建时,数据库默认版本为0 - if (rdbStore.version == 0) { - rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) - // 设置数据库的版本,入参为大于0的整数 - rdbStore.version = 3 - } + // 假设当前数据库版本为3 + relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + // 当数据库创建时,数据库默认版本为0 + if (store.version == 0) { + store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null); + // 设置数据库的版本,入参为大于0的整数 + store.version = 3; + } - // 当数据库存在并假定版本为1时,例应用从某一版本升级到当前版本,数据库需要从1版本升级到2版本 - if (rdbStore.version != 3 && rdbStore.version == 1) { - // version = 1:表结构:student (id, age) => version = 2:表结构:student (id, age, score) - rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) - rdbStore.version = 2 - } + // 当数据库存在并假定版本为1时,例应用从某一版本升级到当前版本,数据库需要从1版本升级到2版本 + if (store.version != 3 && store.version == 1) { + // version = 1:表结构:student (id, age) => version = 2:表结构:student (id, age, score) + store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null); + store.version = 2; + } - // 当数据库存在并假定版本为2时,例应用从某一版本升级到当前版本,数据库需要从2版本升级到3版本 - if (rdbStore.version != 3 && rdbStore.version == 2) { - // version = 2:表结构:student (id, age, score) => version = 3:表结构:student (id, score) - rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) - rdbStore.version = 3 - } - }) + // 当数据库存在并假定版本为2时,例应用从某一版本升级到当前版本,数据库需要从2版本升级到3版本 + if (store.version != 3 && store.version == 2) { + // version = 2:表结构:student (id, age, score) => version = 3:表结构:student (id, score) + store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null); + store.version = 3; + } + }) } } ``` @@ -284,23 +289,24 @@ 示例代码如下: ```js - let u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - let insertPromise = rdbStore.insert("test", valueBucket) + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }; + let insertPromise = store.insert("test", valueBucket); ``` ```js //使用事务插入数据 - beginTransaction() try { - let u8 = new Uint8Array([1, 2, 3]) - const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } - let insertPromise1 = rdbStore.insert("test", valueBucket1) - let insertPromise2 = rdbStore.insert("test", valueBucket2) - commit() - } catch (e) { - rollBack() + store.beginTransaction(); + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }; + let promise = store.insert("test", valueBucket); + promise.then(() => { + store.commit(); + }) + } catch (err) { + console.error(`Transaction failed, err: ${err}`); + store.rollBack(); } ``` @@ -315,17 +321,17 @@ 示例代码如下: ```js - let predicates = new data_rdb.RdbPredicates("test"); - predicates.equalTo("name", "Tom") - let promisequery = rdbStore.query(predicates) + let predicates = new relationalStore.RdbPredicates("test"); + predicates.equalTo("name", "Tom"); + let promisequery = store.query(predicates); promisequery.then((resultSet) => { - resultSet.goToFirstRow() - const id = resultSet.getLong(resultSet.getColumnIndex("id")) - const name = resultSet.getString(resultSet.getColumnIndex("name")) - const age = resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) - resultSet.close() + resultSet.goToFirstRow(); + const id = resultSet.getLong(resultSet.getColumnIndex("id")); + const name = resultSet.getString(resultSet.getColumnIndex("name")); + const age = resultSet.getLong(resultSet.getColumnIndex("age")); + const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")); + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")); + resultSet.close(); }) ``` @@ -335,9 +341,9 @@ ```json "requestPermissions": - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } ``` (2) 获取应用权限。 @@ -351,13 +357,13 @@ ```js let context = featureAbility.getContext(); context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { - console.info(`result.requestCode=${result.requestCode}`) + console.info(`result.requestCode=${result.requestCode}`); }) - let promise = rdbStore.setDistributedTables(["test"]) + let promise = store.setDistributedTables(["test"]); promise.then(() => { - console.info("setDistributedTables success.") + console.info(`setDistributedTables success.`); }).catch((err) => { - console.info("setDistributedTables failed.") + console.error(`setDistributedTables failed, ${err}`); }) ``` @@ -372,16 +378,16 @@ 示例代码如下: ```js - let predicate = new data_rdb.RdbPredicates('test') - predicate.inDevices(['12345678abcde']) - let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) + let predicate = new relationalStore.RdbPredicates('test'); + predicate.inDevices(['12345678abcde']); + let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicate); promise.then((result) => { - console.log('sync done.') - for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + 'status=' + result[i][1]) - } + console.info(`sync done.`); + for (let i = 0; i < result.length; i++) { + console.info(`device=${result[i][0]}, status=${result[i][1]}`); + } }).catch((err) => { - console.log('sync failed') + console.error(`sync failed, err: ${err}`); }) ``` @@ -395,15 +401,15 @@ ```js function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + device[i] + 'data changed') - } + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${device[i]} data changed`); + } } try { - rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.log('register observer failed') + console.error(`register observer failed, err: ${err}`); } ``` @@ -416,8 +422,24 @@ 示例代码如下: ```js - let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); - let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) + import deviceManager from '@ohos.distributedHardware.deviceManager' + + let deviceIds = []; + deviceManager.createDeviceManager('bundleName', (err, value) => { + if (!err) { + let devManager = value; + if (devManager != null) { + // 获取deviceIds + let devices = devManager.getTrustedDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].deviceId; + } + } + } + }) + + let tableName = store.obtainDistributedTableName(deviceIds[0], "test"); + let resultSet = store.querySql("SELECT * FROM " + tableName); ``` 8. 远程查询。 @@ -429,19 +451,19 @@ 示例代码如下: ```js - let rdbPredicate = new data_rdb.RdbPredicates('employee') - predicates.greaterThan("id", 0) - let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + let rdbPredicate = new relationalStore.RdbPredicates('employee'); + predicates.greaterThan("id", 0) ; + let promiseQuery = store.remoteQuery('12345678abcde', 'employee', rdbPredicate); promiseQuery.then((resultSet) => { - while (resultSet.goToNextRow()) { - let idx = resultSet.getLong(0); - let name = resultSet.getString(1); - let age = resultSet.getLong(2); - console.info(idx + " " + name + " " + age); - } - resultSet.close(); + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); + console.info(`indx: ${idx}, name: ${name}, age: ${age}`); + } + resultSet.close(); }).catch((err) => { - console.info("failed to remoteQuery, err: " + err) + console.error(`failed to remoteQuery, err: ${err}`); }) ``` @@ -452,11 +474,11 @@ 示例代码如下: ```js - let promiseBackup = rdbStore.backup("dbBackup.db") + let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(() => { - console.info('Backup success.') + console.info(`Backup success.`); }).catch((err) => { - console.info('Backup failed, err: ' + err) + console.error(`Backup failed, err: ${err}`); }) ``` @@ -465,11 +487,11 @@ 示例代码如下: ```js - let promiseRestore = rdbStore.restore("dbBackup.db") + let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(() => { - console.info('Restore success.') + console.info(`Restore success.`); }).catch((err) => { - console.info('Restore failed, err: ' + err) + console.error(`Restore failed, err: ${err}`); }) ``` diff --git a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-overview.md b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-overview.md index 4957e7a992b873fc1063325ea5e8e9a61df00e5a..ae2026a593a8d6fe32793e008890babbd6434519 100644 --- a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-overview.md +++ b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-overview.md @@ -36,5 +36,5 @@ 解除注册应用分组变化回调监听。 ## 设备使用信息统计使用权限 -- 设备使用信息统计的queryBundleActiveStates、queryBundleStateInfos、queryBundleStateInfoByInterval、queryBundleActiveEventStates、queryAppNotificationNumber、queryAppUsagePriorityGroup(bundleName?)、setBundleGroup、registerGroupCallBack、unRegisterGroupCallBack接口为系统api,调用前需要申请ohos.permission.BUNDLE_ACTIVE_INFO权限。 -- 设备使用信息统计的queryCurrentBundleActiveStates、queryAppUsagePriorityGroup()、isIdleState(三方应用只能查询自身的空闲状态)接口为三方api,调用时不需要申请权限。 \ No newline at end of file +- 设备使用信息统计的isIdleState、queryBundleEvents、queryBundleStatsInfos、queryBundleStatsInfoByInterval、queryDeviceEventStats、queryNotificationEventStats、queryAppGroup(bundleName)、setAppGroup、registerAppGroupCallBack、unregisterAppGroupCallBack、queryModuleUsageRecords和queryModuleUsageRecords(maxnum)接口为系统api,调用前需要申请ohos.permission.BUNDLE_ACTIVE_INFO权限。 +- 设备使用信息统计的queryCurrentBundleEvents、queryAppGroup()接口为三方api,调用时不需要申请权限。 \ No newline at end of file diff --git a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md index 86d25a09c14a0e3759e9fa52fd0befa7a2f4e34a..117ca956e802ceaa635f352d650333095f3cccdc 100644 --- a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md +++ b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md @@ -227,7 +227,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; } ``` -7. 判断指定Bundle Name的应用当前是否是空闲状态,不需要配置权限,三方应用只能查询自身的空闲状态。 +7. 判断指定Bundle Name的应用当前是否是空闲状态,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。 ```js import usageStatistics from '@ohos.resourceschedule.usageStatistics' diff --git a/zh-cn/application-dev/device/Readme-CN.md b/zh-cn/application-dev/device/Readme-CN.md index 92e9601bba6fe942749ef88c405ad27846a90ac9..a544ccb901e4848a3c15156ee69566e5b53947eb 100644 --- a/zh-cn/application-dev/device/Readme-CN.md +++ b/zh-cn/application-dev/device/Readme-CN.md @@ -17,3 +17,5 @@ - 升级服务 - [示例服务器开发概述](sample-server-overview.md) - [示例服务器开发指导](sample-server-guidelines.md) +- 设备状态 + - [设备状态开发指导](stationary-guidelines.md) diff --git a/zh-cn/application-dev/device/stationary-guidelines.md b/zh-cn/application-dev/device/stationary-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..2cce3c90983779331f1e4ae27ac7a5bdb64b3dfa --- /dev/null +++ b/zh-cn/application-dev/device/stationary-guidelines.md @@ -0,0 +1,84 @@ +# Stationary开发指导 + + +## 场景介绍 + +当应用需要获取当前设备状态时,可以调用Stationary模块,例如:需要判断当前设备处于绝对静止状态或者相对静止状态。 + +详细的接口介绍请参考[Stationary接口](../reference/apis/js-apis-stationary.md)。 + +## 设备状态类型参数说明 + +| 名称 | 描述 | +| -------- | -------- | +| still | 绝对静止。 | +| relativeStill | 相对静止。 | + +## 订阅设备状态事件参数说明 + +| 变量 | 值 | 说明 | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | 订阅进入事件。 | +| EXIT | 2 | 订阅退出事件。 | +| ENTER_EXIT | 3 | 订阅进入和退出事件。 | + +## 返回设备状态参数说明 + +| 变量 | 值 | 说明 | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | 返回进入状态。 | +| EXIT | 2 | 返回退出状态。 | + +## 接口说明 + +| 模块 | 接口名 | 描述 | +| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.stationary | on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback<ActivityResponse>): void | 订阅设备状态,结果通过callback返回。 | +| ohos.stationary | once(activity: ActivityType, callback: Callback<ActivityResponse>): void | 查询设备状态,结果通过callback返回。 | +| ohos.stationary | off(activity: ActivityType, event: ActivityEvent, callback?: Callback<ActivityResponse>): void | 取消订阅设备状态。 | + +## 约束与限制 + +设备需要支持加速度传感器。 + +## 开发步骤 + +1. 订阅绝对静止的进入事件,1秒上报一次。 + + ```js + import stationary from '@ohos.stationary'; + var reportLatencyNs = 1000000000; + try { + stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { + console.log('data='+ JSON.stringify(data)); + }) + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } + ``` + +2. 查询绝对静止状态的进入事件。 + + ```js + import stationary from '@ohos.stationary'; + try { + stationary.once('still', (data) => { + console.log('data='+ JSON.stringify(data)); + }) + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } + ``` + +3. 取消订阅绝对静止状态的进入事件。 + + ```js + import stationary from '@ohos.stationary'; + try { + stationary.off('still', stationary.ActivityEvent.ENTER, (data) => { + console.log('data='+ JSON.stringify(data)); + }) + } catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); + } + ``` diff --git a/zh-cn/application-dev/dfx/apprecovery-guidelines.md b/zh-cn/application-dev/dfx/apprecovery-guidelines.md index 028b2d6cfcb17e6ff8079389db49abc3be7edf1d..c2293d0eced73f280e532fca427d7e812eb62209 100644 --- a/zh-cn/application-dev/dfx/apprecovery-guidelines.md +++ b/zh-cn/application-dev/dfx/apprecovery-guidelines.md @@ -29,7 +29,7 @@ **restartApp:** 调用后框架会杀死当前应用进程,并重新拉起处于前台的Ability,其中启动原因为APP_RECOVERY。 -### 框架故障管理理流程示意 +### 框架故障管理流程示意 故障管理是应用提升用户体验的重要手段。应用程序框架为开发者提供了故障监听、故障恢复、以及故障查询三种方式来管理应用的故障。 @@ -39,7 +39,7 @@ - 故障查询指的是[faultLogger](../reference/apis/js-apis-faultLogger.md)通过其查询接口获取当前的故障信息。 -下图中并没有标记[faultLogger](../reference/apis/js-apis-faultLogger.md)的调用时机,开发者可以根据应用启动时传入的[LastExitReason](../reference/apis/js-apis-application-abilityConstant.md#abilityconstantlastexitreason)来决定是否调用[faultLogger](../reference/apis/js-apis-faultLogger.md)查询上次的故障信息。 +下图中并没有标记[faultLogger](../reference/apis/js-apis-faultLogger.md)的调用时机,开发者可以根据应用启动时传入的[LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason)来决定是否调用[faultLogger](../reference/apis/js-apis-faultLogger.md)查询上次的故障信息。 ![故障处理流程示意](./figures/20221106203527.png) 这里建议应用开发者使用[errorManager](../reference/apis/js-apis-application-errorManager.md)对应用的异常进行处理,处理完成后开发者可以选择调用状态保存接口并主动重启应用。 如果开发者没有注册[ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver)也没有使能自动恢复,则按照系统的默认逻辑执行进程退出。用户可以选择从启动器再次打开应用。 @@ -133,7 +133,7 @@ callback触发appRecovery.saveAppState()调用后,会触发EntryAbility的onSa - 数据恢复 -callback触发后appRecovery.restartApp()调用后,应用会重启,重启后会走到EntryAbility的onSaveState(state, wantParams)函数,保存的数据会在want参数的parameters里。 +callback触发后appRecovery.restartApp()调用后,应用会重启,重启后会走到EntryAbility的onCreate(want, launchParam)函数,保存的数据会在want参数的parameters里。 ```ts storage: LocalStorage diff --git a/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md index b150c7aed2273e763dce9b837e9fedacfc83963e..60043767345181ea2a247fd8b30ac155b7993d0c 100644 --- a/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md @@ -46,10 +46,10 @@ async function example() { const path = await media.getPublicDirectory(DIR_IMAGE); //myAlbum为新建文件保存路径,也是新建相册的名称 media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { - if (fileAsset != undefined) { - console.info('createAlbum successfully, message = ' + fileAsset); + if (fileAsset === undefined) { + console.error('createAlbum failed, message = ' + err); } else { - console.info('createAlbum failed, message = ' + err); + console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset)); } }); } @@ -85,10 +85,10 @@ async function example() { let album = albumList[0]; album.albumName = 'newAlbum'; //回调返回空 - album.commitModify().then(function() { + album.commitModify().then(() => { console.info("albumRename successfully"); - }).catch(function(err){ - console.info("albumRename failed with error: " + err); + }).catch((err) => { + console.error("albumRename failed with error: " + err); }); } ``` diff --git a/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md index 259774688fc5cc8031d31dd1909cb94e8a13f8c5..b42db693e0fe55e97061356d5040e4ff0b2cab0a 100644 --- a/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -30,7 +30,7 @@ Openharmony上用户数据统一由媒体库进行管理,用户数据用户数 **前提条件** - 获取媒体库mediaLibrary实例。 -- 申请媒体库读权限“ohos.permission.READ_MEDIA。 +- 申请媒体库读权限"ohos.permission.READ_MEDIA"。 下面以获取Camera文件保存的公共目录为例。 @@ -43,7 +43,7 @@ async function example(){ if (dicResult == 'Camera/') { console.info('mediaLibraryTest : getPublicDirectory passed'); } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); + console.error('mediaLibraryTest : getPublicDirectory failed'); } } ``` @@ -58,47 +58,52 @@ OpenHarmony提供应用沙箱机制,增加目录可见性数据访问防线, 通过接口[mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1)可以打开公共路径文件。 -通过接口[fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7)可以打开沙箱路径文件,沙箱路径必须通过应用上下文context进行访问。 +通过接口[fs.open](../reference/apis/js-apis-file-fs.md#fsopen)可以打开沙箱路径文件,沙箱路径必须通过应用上下文context进行访问。 **前提条件** - 获取媒体库mediaLibrary实例。 -- 申请媒体库读写权限“ohos.permission.WRITE_MEDIA。 -- 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.fileio](../reference/apis/js-apis-fileio.md)。 +- 申请媒体库读写权限"ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA"。 +- 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.file.fs](../reference/apis/js-apis-file-fs.md)。 +- 测试文件 "testFile.txt" 已创建且有文件内容。 **开发步骤** -1. 调用[context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir)获取应用沙箱路径。 +1. 调用[context.filesDir](../reference/apis/js-apis-file-fs.md)获取应用沙箱路径。 2. 调用MediaLibrary.getFileAssets和FetchFileResult.getFirstObject获取公共目录中的FileAsset实例。 -3. 调用fileio.open打开沙箱路径文件。 +3. 调用fs.open打开沙箱路径文件。 4. 调用fileAsset.open打开公共路径文件。 -5. 调用fileio.copyfile复制文件。 -6. 调用fileAsset.close和fileio.close关闭文件。 +5. 调用[fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile)复制文件。 +6. 调用fileAsset.close和[fs.close](../reference/apis/js-apis-file-fs.md#fsclose)关闭文件。 **示例1 将公共路径文件复制到沙箱路径下** ```ts async function copyPublic2Sandbox() { - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let sandboxDirPath = globalThis.context.filesDir; - let fileKeyObj = mediaLibrary.FileKey; - let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?', - selectionArgs: ['testFile.txt'], - }; - let fetchResult = await media.getFileAssets(fileAssetFetchOp); - let fileAsset = await fetchResult.getFirstObject(); + try { + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let sandboxDirPath = context.filesDir; + let fileKeyObj = mediaLibrary.FileKey; + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?', + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); - let fdPub = await fileAsset.open('rw'); - let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); - await fileio.copyFile(fdPub, fdSand); + let fdPub = await fileAsset.open('rw'); + let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + await fs.copyFile(fdPub, fdSand.fd); - await fileAsset.close(fdPub); - await fileio.close(fdSand); + await fileAsset.close(fdPub); + await fs.close(fdSand.fd); - let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); - console.log('content read from sandbox file: ', content_sand) + let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt'); + console.info('content read from sandbox file: ', content_sand) + } catch (err) { + console.info('[demo] copyPublic2Sandbox fail, err: ', err); + } } ``` @@ -108,7 +113,7 @@ async function copyPublic2Sandbox() { async function copySandbox2Public() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); - let sandboxDirPath = globalThis.context.filesDir; + let sandboxDirPath = context.filesDir; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); @@ -116,7 +121,7 @@ async function copySandbox2Public() { let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); console.info('createFile successfully, message = ' + fileAsset); } catch (err) { - console.info('createFile failed, message = ' + err); + console.error('createFile failed, message = ' + err); } try { let fileKeyObj = mediaLibrary.FileKey; @@ -127,35 +132,35 @@ async function copySandbox2Public() { let fetchResult = await media.getFileAssets(fileAssetFetchOp); var fileAsset = await fetchResult.getFirstObject(); } catch (err) { - console.info('file asset get failed, message = ' + err); + console.error('file asset get failed, message = ' + err); } 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 fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE); + await fs.copyFile(fdSand.fd, fdPub); + await fileAsset.close(fdPub); + await fs.close(fdSand.fd); let fdPubRead = await fileAsset.open('rw'); try { let arrayBuffer = new ArrayBuffer(4096); - await fileio.read(fdPubRead, arrayBuffer); + await fs.read(fdPubRead, arrayBuffer); var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); fileAsset.close(fdPubRead); } catch (err) { - console.log('read text failed, message = ', err); + console.error('read text failed, message = ', err); } - console.log('content read from public file: ', content_pub); + console.info('content read from public file: ', content_pub); } ``` ### 读写文件内容 -通过[mediaLibrary](../reference/apis/js-apis-medialibrary.md)的接口FileAsset.open和FileAsset.close可以打开和关闭文件。通过[fileio](../reference/apis/js-apis-fileio.md)的接口fileio.read和fileio.write可以读写文件。 +通过[mediaLibrary](../reference/apis/js-apis-medialibrary.md)的接口FileAsset.open和FileAsset.close可以打开和关闭文件。通过[file.fs](../reference/apis/js-apis-file-fs.md)中的接口fs.read和fs.write可以读写文件。 **前提条件** - 获取媒体库mediaLibrary实例。 -- 申请媒体库读写权限“ohos.permission.WRITE_MEDIA。 -- 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.fileio](../reference/apis/js-apis-fileio.md)。 +- 申请媒体库读写权限"ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA"。 +- 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.file.fs](../reference/apis/js-apis-file-fs.md)。 **开发步骤** @@ -168,19 +173,19 @@ async function copySandbox2Public() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); - media.createAsset(mediaType, "testFile.text", path).then (function (asset) { + media.createAsset(mediaType, "testFile.text", path).then((asset) => { console.info("createAsset successfully:" + JSON.stringify(asset)); - }).catch(function(err){ - console.info("createAsset failed with error: " + err); + }).catch((err) => { + console.error("createAsset failed with error: " + err); }); } ``` 2. 使用open打开文件。 -3. 使用fileio.write写入文件,以string形式传入写入数据。 +3. 使用[fs.write](../reference/apis/js-apis-file-fs.md#fswrite)写入文件,以string形式传入写入数据。 -4. 使用fileio.read读取文件,以 ArrayBuffer 形式保存读取结果。 +4. 使用[fs.read](../reference/apis/js-apis-file-fs.md#fsread)读取文件,以 ArrayBuffer 形式保存读取结果。 5. 将ArrayBuffer转化为string,以string形式得到文件内容。 @@ -204,10 +209,10 @@ async function writeOnlyPromise() { try { let fd = await fileAsset.open('w'); console.info('file descriptor: ', fd); - await fileio.write(fd, "Write file test content."); + await fs.write(fd, "Write file test content."); await fileAsset.close(fd); } catch (err) { - console.info('write file failed, message = ', err); + console.error('write file failed, message = ', err); } } ``` @@ -230,14 +235,14 @@ async function readOnlyPromise() { try { let fd = await fileAsset.open('r'); let arrayBuffer = new ArrayBuffer(4096); - await fileio.read(fd, arrayBuffer); + await fs.read(fd, arrayBuffer); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); globalThis.fileContent = fileContent; globalThis.fileName = fileAsset.displayName; console.info('file content: ', fileContent); await fileAsset.close(fd); } catch (err) { - console.info('read file failed, message = ', err); + console.error('read file failed, message = ', err); } } ``` diff --git a/zh-cn/application-dev/file-management/medialibrary-overview.md b/zh-cn/application-dev/file-management/medialibrary-overview.md index ca8a6c4516853d181a9f27dc0f10ced9853e7e13..fd8b9fb3eceddf04b6c87948703e5879702ba5bd 100644 --- a/zh-cn/application-dev/file-management/medialibrary-overview.md +++ b/zh-cn/application-dev/file-management/medialibrary-overview.md @@ -109,19 +109,19 @@ let media = mediaLibrary.getMediaLibrary(context); import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - let list : Array = ['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 { - permissionRequestResult=result; - console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); - } - }); - } - } + onWindowStageCreate(windowStage) { + let list : Array = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; + let permissionRequestResult; + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(this.context, list, (err, result) => { + if (err) { + console.error('requestPermissionsFromUserError: ' + JSON.stringify(err)); + } else { + permissionRequestResult=result; + console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + } + }); + } + } ``` diff --git a/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md index c64f25916fd0f07110d3d33079c9f71c9b268a2a..9277bfdf74bbd442f475e409b47325ba785f4a79 100644 --- a/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-resource-guidelines.md @@ -42,21 +42,24 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; + fetchFileResult.getFirstObject().then((fileAsset) => { + console.log('getFirstObject.displayName : ' + fileAsset.displayName); + for (let i = 1; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }).catch((err) => { + console.error('Failed to get next object: ' + err); + }); } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); } ``` ### 指定日期 -下面以查询指定添加日期的媒体资源为例。实际开发中可以设置添加日期、修改日期、拍摄日期。 +下面以查询指定添加日期至今的所有媒体资源为例。实际开发中可以设置添加日期、修改日期、拍摄日期。 selections: FileKey.DATE_ADDED,根据文件添加日期检索。 @@ -66,21 +69,24 @@ selectionArgs:2022-8-5,具体添加时间的字符串。 async function example() { let fileKeyObj = mediaLibrary.FileKey; let option = { - selections: fileKeyObj.DATE_ADDED + '= ?', - selectionArgs: ['2022-8-5'], + selections: fileKeyObj.DATE_ADDED + '> ?', + selectionArgs: ['2022-8-5'], }; const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; + fetchFileResult.getFirstObject().then((fileAsset) => { + console.info('getFirstObject.displayName : ' + fileAsset.displayName); + for (let i = 1; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }).catch((err) => { + console.error('Failed to get next object: ' + err); + }); } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); } ``` @@ -102,15 +108,18 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; + fetchFileResult.getFirstObject().then((fileAsset) => { + console.info('getFirstObject.displayName : ' + fileAsset.displayName); + for (let i = 1; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }).catch((err) => { + console.error('Failed to get next object: ' + err); + }); } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); } ``` @@ -133,15 +142,15 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + if (albumList.length > 0) { + fetchFileResult.getFirstObject().then((album) => { + console.info('getFirstObject.displayName : ' + album.albumName); + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); + } else { + console.info('getAlbum list is: 0'); + } } ``` @@ -172,10 +181,10 @@ async function example() { ```ts let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.VIDEO; - let imagesFetchOp = { + let videoType = mediaLibrary.MediaType.VIDEO; + let videoFetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], + selectionArgs: [videoType.toString()], } ``` @@ -188,10 +197,10 @@ async function getCameraImagePromise() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let imagesFetchOp = { + let videoType = mediaLibrary.MediaType.VIDEO; + let videoFetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], + selectionArgs: [videoType.toString()], } let AlbumNoArgsFetchOp = { selections: fileKeyObj.ALBUM_NAME + '= ?', @@ -201,9 +210,9 @@ async function getCameraImagePromise() { let albumList = await media.getAlbums(AlbumNoArgsFetchOp); if (albumList.length > 0) { const album = albumList[0]; - let fetchFileResult = await album.getFileAssets(imagesFetchOp); + let fetchFileResult = await album.getFileAssets(videoFetchOp); let count = fetchFileResult.getCount(); - console.info("get mediaLibrary IMAGE number", count); + console.info("get mediaLibrary VIDEO number", count); } else { console.info('getAlbum list is: 0'); } @@ -245,19 +254,20 @@ async function getFirstThumbnailPromise() { let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(imagesFetchOp); - if (fetchFileResult != undefined) { + if (fetchFileResult === undefined) { + console.error("get image failed with error"); + return; + } else { const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size).then((pixelMap) => { - pixelMap.getImageInfo().then((info) => { + pixelMap.getImageInfo().then((info) => { console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); - }).catch((err) => { - console.info("getImageInfo failed with error:" + err); - }); + }).catch((err) => { + console.error("getImageInfo failed with error: " + err); + }); }).catch((err) => { - console.info("getImageInfo failed with error:" + err); + console.error("getImageInfo failed with error: " + err); }); - } else { - console.info("get image failed with error"); } } ``` @@ -281,10 +291,10 @@ async function example() { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); - media.createAsset(mediaType, "testFile.text", path).then ((asset) => { + media.createAsset(mediaType, "testFile.text", path).then((asset) => { console.info("createAsset successfully:"+ JSON.stringify(asset)); }).catch((err) => { - console.info("createAsset failed with error:"+ err); + console.error("createAsset failed with error: " + err); }); } ``` @@ -321,15 +331,15 @@ async function example() { 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; + if (asset === undefined) { + console.error('asset not exist'); + return; } //回调为空 asset.trash(true).then(() => { console.info("trash successfully"); }).catch((err) => { - console.info("trash failed with error: " + err); + console.error("trash failed with error: " + err); }); } ``` @@ -347,7 +357,7 @@ async function example() { - 获取媒体库mediaLibrary实例。 - 申请媒体库读写权限“ohos.permission.WRITE_MEDIA”。 -下面以将文件检索结果中第一个文件重命名为“newtitle.text”为例。 +下面以将文件检索结果中第一个文件重命名为“newImage.jpg”为例。 **开发步骤** @@ -360,7 +370,7 @@ async function example() { ```ts async function example() { let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.FILE; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], @@ -369,18 +379,18 @@ async function example() { 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; + if (asset === undefined) { + console.error('asset not exist'); + return; } asset.displayName = 'newImage.jpg'; //回调为空 asset.commitModify((err) => { - if (err) { - console.error('fileRename Failed '); - return; - } - console.log('fileRename successful.'); + if (err) { + console.error('fileRename Failed '); + return; + } + console.info('fileRename successful.'); }); } ``` diff --git a/zh-cn/application-dev/quick-start/module-configuration-file.md b/zh-cn/application-dev/quick-start/module-configuration-file.md index e61eb1974c057c930b54e8593380fcba94b86f51..2ae449cfe1733abc349b7a57f8ec7c43418c1860 100644 --- a/zh-cn/application-dev/quick-start/module-configuration-file.md +++ b/zh-cn/application-dev/quick-start/module-configuration-file.md @@ -81,8 +81,8 @@ module.json5配置文件包含以下标签。 | deliveryWithInstall | 标识当前Module是否在用户主动安装的时候安装,表示该Module对应的HAP是否跟随应用一起安装。
- true:主动安装时安装。
- false:主动安装时不安装。 | 布尔值 | 该标签不可缺省。 | | installationFree | 标识当前Module是否支持免安装特性。
- true:表示支持免安装特性,且符合免安装约束。
- false:表示不支持免安装特性。
**说明:**
- 当应用的entry类型Module的该字段配置为true时,该应用的feature类型的该字段也需要配置为true。
- 当应用的entry类型Module的该字段配置为false时,该应用的feature类型的该字段根据业务需求配置true或false。 | 布尔值 | 该标签不可缺省。 | | virtualMachine | 标识当前Module运行的目标虚拟机类型,供云端分发使用,如应用市场和分发中心。
该标签值为字符串。如果目标虚拟机类型为ArkTS引擎,则其值为“ark+版本号”。 | 字符串 | 该标签由IDE构建HAP的时候自动插入。 | -| uiSyntax(deprecated) | 标识当前Module syntax定义该JS Component的语法类型。
- hml:标识该JS Component使用hml/css/js进行开发。
- ets:标识该JS Component使用ArkTS声明式语法进行开发。 | 字符串 | 该标签可缺省,默认值为hml,该标签从API9开始废弃。 | -| [pages](#pages标签) | 标识当前Module的profile资源,用于列举JS Component中每个页面信息。该标签最大长度为255个字节。 | 字符串 | 在有UIAbility的场景下,该标签不可缺省。 | +| uiSyntax(deprecated) | 标识当前Module syntax定义该组件的语法类型。
- hml:标识该组件使用hml/css/js进行开发。
- ets:标识该组件使用ArkTS声明式语法进行开发。 | 字符串 | 该标签可缺省,默认值为hml,该标签从API9开始废弃。 | +| [pages](#pages标签) | 标识当前Module的profile资源,用于列举每个页面信息。该标签最大长度为255个字节。 | 字符串 | 在有UIAbility的场景下,该标签不可缺省。 | | [metadata](#metadata标签) | 标识当前Module的自定义元信息,标签值为数组类型,只对当前Module、UIAbility、ExtensionAbility生效。 | 对象数组 | 该标签可缺省,缺省值为空。 | | [abilities](#abilities标签) | 标识当前Module中UIAbility的配置信息,标签值为数组类型,只对当前UIAbility生效。 | 对象 | 该标签可缺省,缺省值为空。 | | [extensionAbilities](#extensionabilities标签) | 标识当前Module中ExtensionAbility的配置信息,标签值为数组类型,只对当前ExtensionAbility生效。 | 对象 | 该标签可缺省,缺省值为空。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md index 4b9d2ab5077ce660f7240f245c8512ba2d11e24f..9fbf316d05afb22bf7870b8b9dcb2e073e0fc59f 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md @@ -1603,7 +1603,7 @@ bundle.getNameForUid(uid, (err, data) => { ## bundle.getAbilityIcon8+ deprecated -> 从API version 9开始不再维护,建议使用[bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon)替代。 +> 从API version 9开始不再维护,建议使用[resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9)替代。 getAbilityIcon(bundleName: string, abilityName: string): Promise\; @@ -1646,7 +1646,7 @@ bundle.getAbilityIcon(bundleName, abilityName) ## bundle.getAbilityIcon8+ deprecated -> 从API version 9开始不再维护,建议使用[bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon)替代。 +> 从API version 9开始不再维护,建议使用[resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9)替代。 getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md index ac466f330f74b1a43c047e7cb92fe8fc713704fa..b8008bef08ef4d25e8e35b4bc77982f8a06aea69 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md @@ -65,7 +65,7 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapplication", abilityName: "MyAbility" }; @@ -107,7 +107,7 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | **错误码:** @@ -121,12 +121,12 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var options = { + let options = { windowMode: 0 }; @@ -166,7 +166,7 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 否 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **返回值:** @@ -185,11 +185,11 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapplication", abilityName: "MyAbility" }; - var options = { + let options = { windowMode: 0, }; @@ -216,7 +216,10 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(callback形式)。 +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -243,7 +246,7 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -272,7 +275,10 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(callback形式)。 +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -286,7 +292,7 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want |[Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 执行结果回调函数。 | **错误码:** @@ -300,12 +306,12 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var options = { + let options = { windowMode: 0, }; @@ -333,7 +339,10 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(promise形式)。 +启动一个Ability。Ability被启动后,有如下情况(promise形式): + - 正常情况下可通过调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#abilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -347,7 +356,7 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityRes | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 否 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **返回值:** @@ -367,11 +376,11 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityRes **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapplication", abilityName: "MyAbility" }; - var options = { + let options = { windowMode: 0, }; @@ -429,12 +438,12 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { @@ -479,7 +488,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | **错误码:** @@ -493,13 +502,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -546,7 +555,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 否 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **返回值:** @@ -565,13 +574,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -621,7 +630,7 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -672,7 +681,7 @@ startServiceExtensionAbility(want: Want): Promise\; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -727,12 +736,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -782,12 +791,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId) @@ -834,7 +843,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -891,7 +900,7 @@ stopServiceExtensionAbility(want: Want): Promise\; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -952,12 +961,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -1013,12 +1022,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -1144,13 +1153,13 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi **示例:** ```ts - var want = { + let want = { bundleName: "com.extreme.myapplication", abilityName: "SecondAbility" } - var resultCode = 100; + let resultCode = 100; // 返回给接口调用方AbilityResult信息 - var abilityResult = { + let abilityResult = { want, resultCode } @@ -1207,13 +1216,13 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; **示例:** ```ts - var want = { + let want = { bundleName: "com.extreme.myapplication", abilityName: "SecondAbility" } - var resultCode = 100; + let resultCode = 100; // 返回给接口调用方AbilityResult信息 - var abilityResult = { + let abilityResult = { want, resultCode } @@ -1270,18 +1279,18 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var options = { + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { @@ -1329,19 +1338,19 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { @@ -1383,7 +1392,7 @@ disconnectServiceExtensionAbility(connection: number): Promise\; ```ts // connection为connectServiceExtensionAbility中的返回值 - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection) @@ -1430,7 +1439,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\ { @@ -1482,10 +1491,10 @@ startAbilityByCall(want: Want): Promise<Caller>; 后台启动: ```ts - var caller = undefined; + let caller = undefined; // 后台启动Ability,不配置parameters - var wantBackground = { + let wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "EntryAbility", @@ -1513,10 +1522,10 @@ startAbilityByCall(want: Want): Promise<Caller>; 前台启动: ```ts - var caller = undefined; + let caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true - var wantForeground = { + let wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "EntryAbility", @@ -1580,12 +1589,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -1629,7 +1638,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。| -| options | [StartOptions](js-apis-application-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | **错误码:** @@ -1643,13 +1652,13 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -1695,7 +1704,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | -| options | [StartOptions](js-apis-application-startOptions.md) | 否 | 启动Ability所携带的参数。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **错误码:** @@ -1708,13 +1717,13 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -1810,9 +1819,9 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; ```ts import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -1857,9 +1866,9 @@ setMissionIcon(icon: image.PixelMap): Promise\; ```ts import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -1897,7 +1906,7 @@ restoreWindowStage(localStorage: LocalStorage) : void; **示例:** ```ts - var storage = new LocalStorage(); + let storage = new LocalStorage(); this.context.restoreWindowStage(storage); ``` @@ -1918,6 +1927,6 @@ isTerminating(): boolean; **示例:** ```ts - var isTerminating = this.context.isTerminating(); + let isTerminating = this.context.isTerminating(); console.log('ability state :' + isTerminating); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md b/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md index cdbdf0668e836a5419d9daebb7e72b8781bb5b6d..c2eeaf878020e583b60a3f33713c8b21be58c52f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -145,7 +145,7 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper ```ts import featureAbility from '@ohos.ability.featureAbility'; -var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); ``` @@ -154,7 +154,10 @@ var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#featureabilityterminateselfwithresult7)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(callback形式)。 +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](#featureabilityterminateselfwithresult7)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#featureabilityterminateselfwithresult7)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -200,7 +203,10 @@ featureAbility.startAbilityForResult( startAbilityForResult(parameter: StartAbilityParameter): Promise\ -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#featureabilityterminateselfwithresult7)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(Promise形式)。 +启动一个Ability。Ability被启动后,有如下情况(Promise形式): + - 正常情况下可通过调用[terminateSelfWithResult](#featureabilityterminateselfwithresult7)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#featureabilityterminateselfwithresult7)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -475,7 +481,7 @@ getContext(): Context ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext() +let context = featureAbility.getContext() context.getBundleName((err, data) => { console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -570,7 +576,7 @@ function onDisconnectCallback(element){ function onFailedCallback(code){ console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) } -var connectId = featureAbility.connectAbility( +let connectId = featureAbility.connectAbility( { deviceId: "", bundleName: "com.ix.ServiceAbility", @@ -613,7 +619,7 @@ function onDisconnectCallback(element){ function onFailedCallback(code){ console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) } -var connectId = featureAbility.connectAbility( +let connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", abilityName: "com.ix.ServiceAbility.ServiceAbilityA", @@ -665,7 +671,7 @@ function onDisconnectCallback(element){ function onFailedCallback(code){ console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) } -var connectId = featureAbility.connectAbility( +let connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", abilityName: "com.ix.ServiceAbility.ServiceAbilityA", diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md b/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md index a2d3419000655db621e818610d4ce2ca87b8446b..32f3fa7da00c1f8d4fb7ec543e9b486777462595 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -196,7 +196,7 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper ```ts import particleAbility from '@ohos.ability.particleAbility' -var uri = ""; +let uri = ""; particleAbility.acquireDataAbilityHelper(uri) ``` @@ -428,7 +428,7 @@ function onFailedCallback(code) { console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) } -var connId = particleAbility.connectAbility( +let connId = particleAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", abilityName: "ServiceAbilityA", @@ -479,7 +479,7 @@ function onFailedCallback(code) { console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) } -var connId = particleAbility.connectAbility( +let connId = particleAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", abilityName: "ServiceAbilityA", @@ -530,7 +530,7 @@ function onFailedCallback(code) { console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) } -var connId = particleAbility.connectAbility( +let connId = particleAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", abilityName: "ServiceAbilityA", diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index a4f459ec1c423e310c375f900f8f26e1620c3cdf..44505896b362644cbb641cfe6eda6c02216d854a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md @@ -24,9 +24,8 @@ import common from '@ohos.app.ability.common' | Context | [Context](js-apis-inner-application-context.md) | Context二级模块。 | | ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | ExtensionContext二级模块。 | | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | FormExtensionContext二级模块。 | -| AreaMode | [AreaMode](#areamode) | AreaMode枚举值。 | +| ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | ServiceExtensionContext二级模块。 | | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | EventHub二级模块。 | -| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | PermissionRequestResult二级模块。 | | PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | PacMap二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | @@ -42,21 +41,8 @@ let baseContext: common.BaseContext; let context: common.Context; let extensionContext: common.ExtensionContext; let formExtensionContext: common.FormExtensionContext; -let areaMode: common.AreaMode; let eventHub: common.EventHub; -let permissionRequestResult: common.PermissionRequestResult; let pacMap: common.PacMap; let abilityResult: common.AbilityResult; let connectOptions: common.ConnectOptions; ``` - -## AreaMode - -数据加密等级的枚举。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| --------------- | ---- | --------------- | -| EL1 | 0 | 设备级加密区,设备开机后可访问的数据区。 | -| EL2 | 1 | 用户级加密区,设备开机,首次输入密码后才能够访问的数据区。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md index c15f167775b6004cd8439f5942e5dbb49f23f9c1..cfc4bb44e4f08fd0cbba4d98efa0ceca2f29a323 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md @@ -36,7 +36,7 @@ getId(uri: string): number ```ts try { - var id = dataUriUtils.getId("com.example.dataUriUtils/1221") + let id = dataUriUtils.getId("com.example.dataUriUtils/1221") console.info('get id: ' + id) } catch(err) { console.error('get id err ,check the uri' + err) @@ -69,9 +69,9 @@ attachId(uri: string, id: number): string **示例:** ```ts -var id = 1122; +let id = 1122; try { - var uri = dataUriUtils.attachId( + let uri = dataUriUtils.attachId( "com.example.dataUriUtils", id, ) @@ -108,7 +108,7 @@ deleteId(uri: string): string ```ts try { - var uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") + let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") console.info('delete id with the uri is: ' + uri) } catch(err) { console.error('delete uri err, check the input uri' + err) @@ -144,8 +144,8 @@ updateId(uri: string, id: number): string ```ts try { - var id = 1122; - var uri = dataUriUtils.updateId( + let id = 1122; + let uri = dataUriUtils.updateId( "com.example.dataUriUtils/1221", id ) diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md new file mode 100644 index 0000000000000000000000000000000000000000..557a9b69837c19c6aaa3b95888cc40a8c7db570e --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md @@ -0,0 +1,262 @@ +# @ohos.app.ability.dialogRequest (dialogRequest模块) + +dialogRequest模块用于处理模态弹框的能力,包括获取RequestInfo(用于绑定模态弹框)、获取RequestCallback(用于设置结果)。 +模态弹框是指一个系统弹出框,其特点在于:该弹出框会拦截弹框之下的页面的鼠标、键盘、触屏等事件,销毁该弹框,才能操作下面的页面。 + +> **说明:** +> +> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块接口在ServiceExtensionAbility下使用,如果ServiceExtensionAbility实现了模态弹框,则可以使用本模块的接口获取请求方的RequestInfo、RequestCallback并返回请求结果。 + +## 导入模块 + +```js +import dialogRequest from '@ohos.app.ability.dialogRequest'; +``` + +## dialogRequest.getRequestInfo + +getRequestInfo(want: Want): RequestInfo + +从Want中获取请求方的RequestInfo。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---- | ------ | ---- | --------------------------- | +| want | [Want](js-apis-application-want.md) | 是 | 表示发起方请求弹框时传入的want信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------ | +| [RequestInfo](#requestinfo) | 请求方RequestInfo,用于绑定模态窗口。 | + +**示例:** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestInfo = dialogRequest.getRequestInfo(want) + } catch(err) { + console.error('getRequestInfo err= ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +## dialogRequest.getRequestCallback + +getRequestCallback(want: Want): RequestCallback + +从Want中获取请求方的RequestCallback。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---- | ------ | ---- | --------------------------- | +| want | [Want](js-apis-application-want.md) | 是 | 表示发起方请求弹框时传入的want信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------ | +| [RequestCallback](#requestcallback) | 请求方RequestCallback,用于设置返回结果。 | + +**示例:** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestCallback = dialogRequest.getRequestCallback(want) + } catch(err) { + console.error('getRequestInfo err= ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +## RequestInfo + +表示发起方请求信息,作为窗口绑定模态弹框的入参。 +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**示例:** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + import window from '@ohos.window'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestInfo = dialogRequest.getRequestInfo(want) + window.bindDialogTarget(requestInfo, () => { + console.info('Dialog Window Need Destroy.'); + }, (err) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target.'); + }); + } catch(err) { + console.error('getRequestInfo err= ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +## ResultCode + +模态弹框请求结果码。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore。 + +| 名称 | 值 | 说明 | +| ------------ | ------------------ | ---------------------- | +| RESULT_OK | 0 | 表示成功。 | +| RESULT_CANCEL | 1 | 表示失败。 | + +## RequestResult +模态弹框请求结果,当前只包含结果码,即RequestResult只当前只有ResultCode这一个成员。 + +## 属性 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| result | [ResultCode](#resultcode) | 是 | 是 | 表示结果码。 | + +## RequestCallback + +用于设置模态弹框请求结果的callback接口。 + +### RequestCallback.setRequestResult + +setRequestResult(result: RequestResult): void; + +设置请求结果 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| result | [RequestResult](#requestresult) | 是 | 模态弹框请求结果信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestCallback = dialogRequest.getRequestCallback(want); + let myResult = { + result : dialogRequest.ResultCode.RESULT_CANCEL, + }; + requestCallback.setRequestResult(myResult); + } catch(err) { + console.error('getRequestInfo err= ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index 30e002a04ab439ab1ad727842dfe58274aa0bc1a..00027f98bf6f70a607b9b1d090a3627807701479 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -35,7 +35,7 @@ onConfigurationUpdated(config: Configuration): void; ```ts import UIAbility from "@ohos.app.ability.Ability"; -var callbackId; +let callbackId; export default class MyAbility extends UIAbility { onCreate() { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md index ab177fe4d31398b203fdfb4c39e399d1a9ddd0f8..d55eec06406661ffe5af8e51e8601f27991d0899 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -35,12 +35,12 @@ on(type: "error", observer: ErrorObserver): number; **示例:** ```ts -var observer = { +let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) } } -var observerId = -1; +let observerId = -1; try { observerId = errorManager.on("error", observer); } catch (paramError) { @@ -67,7 +67,7 @@ off(type: "error", observerId: number, callback: AsyncCallback\): void; **示例:** ```ts -var observerId = 100; +let observerId = 100; function unregisterErrorObserverCallback(err) { if (err) { @@ -105,7 +105,7 @@ off(type: "error", observerId: number): Promise\; **示例:** ```ts -var observerId = 100; +let observerId = 100; try { errorManager.off("error", observerId) .then((data) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 8eb3864949618b18eca6178966ebe0e91862fcce..b4d0064e147bb480d54ea5cca53727784265dfb9 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -46,7 +46,7 @@ on(type:"mission", listener: MissionListener): number; import missionManager from '@ohos.app.ability.missionManager'; import UIAbility from '@ohos.app.ability.UIAbility'; -var listener = { +let listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, @@ -56,7 +56,7 @@ var listener = { onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; -var listenerId = -1; +let listenerId = -1; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { @@ -128,7 +128,7 @@ off(type: "mission", listenerId: number, callback: AsyncCallback<void>): v import missionManager from '@ohos.app.ability.missionManager'; import UIAbility from '@ohos.app.ability.UIAbility'; -var listener = { +let listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, @@ -138,7 +138,7 @@ var listener = { onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; -var listenerId = -1; +let listenerId = -1; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { @@ -215,7 +215,7 @@ off(type: "mission", listenerId: number): Promise<void>; import missionManager from '@ohos.app.ability.missionManager'; import UIAbility from '@ohos.app.ability.UIAbility'; -var listener = { +let listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, @@ -225,7 +225,7 @@ var listener = { onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; -var listenerId = -1; +let listenerId = -1; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { @@ -299,7 +299,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<M let testMissionId = 1; try { - var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); + let allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); if (allMissions && allMissions.length > 0) { testMissionId = allMissions[0].missionId; } diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index c6a282f6ed3676297c7475fa681b57ffb2257a26..c7e4da9d4bb8e69d824b9789e6a4d8a63401519e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -359,8 +359,8 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; return true; } }; - var method = 'call_Function'; // 约定的通知消息字符串 - var caller; + let method = 'call_Function'; // 约定的通知消息字符串 + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -440,8 +440,8 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa return true; } }; - var method = 'call_Function'; - var caller; + let method = 'call_Function'; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -490,7 +490,7 @@ release(): void; **示例:** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -530,7 +530,7 @@ release(): void; **示例:** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -581,7 +581,7 @@ release(): void; **示例:** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -631,7 +631,7 @@ off(type: "release", callback: OnReleaseCallback): void; **示例:** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -682,7 +682,7 @@ off(type: "release"): void; **示例:** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -760,7 +760,7 @@ on(method: string, callback: CalleeCallback): void; return true; } }; - var method = 'call_Function'; + let method = 'call_Function'; function funcCallBack(pdata) { console.log('Callee funcCallBack is called ' + pdata); let msg = new MyMessageAble("test", ""); @@ -806,7 +806,7 @@ off(method: string): void; **示例:** ```ts - var method = 'call_Function'; + let method = 'call_Function'; export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md index de78f53fb4a00138ca88cf8ff0ae5e95a05e3810..5568419351962441f45374f0e4a83f5b3842642c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -12,61 +12,21 @@ wantConstant模块提供want中操作want常数和解释Flags说明的能力。 import wantConstant from '@ohos.app.ability.wantConstant'; ``` -## wantConstant.Action -want操作的常数。用于表示要执行的通用操作。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase +## wantConstant.Params -| 名称 | 值 | 说明 | -| ------------ | ------------------ | ---------------------- | -| ACTION_HOME | ohos.want.action.home | 指示返回原点的操作。 | -| ACTION_DIAL | ohos.want.action.dial | 指示启动显示小键盘的页面功能的操作 | -| ACTION_SEARCH | ohos.want.action.search | 指示启动页面搜索功能的操作。 | -| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | 指示启动提供无线网络设置的页面功能的操作,例如,Wi-Fi选项。 | -| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | 指示启动管理已安装应用程序的页面功能的操作。 | -| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | 指示启动显示指定应用程序详细信息的页面功能的操作。 | -| ACTION_SET_ALARM | ohos.want.action.setAlarm | 指示启动页面功能以设置闹钟的操作。 | -| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | 指示启动显示所有警报的页面功能的操作时钟。 | -| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | 指示启动用于使闹钟睡眠的页面功能的操作。 | -| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | 指示启动删除闹钟的页面功能的操作。 | -| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | 指示启动页面功能以关闭计时器的操作。 | -| ACTION_SEND_SMS | ohos.want.action.sendSms | 指示启动发送sms的页面功能的操作。 | -| ACTION_CHOOSE | ohos.want.action.choose | 指示启动页面功能以打开联系人或图片的操作。 | -| ACTION_IMAGE_CAPTURE | ohos.want.action.imageCapture | 指示启动页面拍照功能的操作。 | -| ACTION_VIDEO_CAPTURE | ohos.want.action.videoCapture | 指示启动页面功能以拍摄视频的操作。 | -| ACTION_SELECT | ohos.want.action.select | 指示显示应用程序选择对话框的操作。 | -| ACTION_SEND_DATA | ohos.want.action.sendData | 指示发送单个数据记录的操作。 | -| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | 指示发送多个数据记录的操作。 | -| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | 指示请求媒体扫描仪扫描文件并将文件添加到媒体库的操作。 | -| ACTION_VIEW_DATA | ohos.want.action.viewData | 指示查看数据的操作。 | -| ACTION_EDIT_DATA | ohos.want.action.editData | 指示编辑数据的操作。 | -| INTENT_PARAMS_INTENT | ability.want.params.INTENT | 指示用行为选择器来展示选择的操作。 | -| INTENT_PARAMS_TITLE | ability.want.params.TITLE | 指示与行为选择器一起使用时的字符序列对话框标题。 | -| ACTION_FILE_SELECT | ohos.action.fileSelect | 指示选择文件的操作。 | -| PARAMS_STREAM | ability.params.stream | 指示发送数据时与目标关联的数据流的URI | -| ACTION_APP_ACCOUNT_AUTH | account.appAccount.action.auth | 指示提供auth服务的操作。 | -| ACTION_MARKET_DOWNLOAD | ohos.want.action.marketDownload | 表示从应用程序市场下载应用程序的的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| ACTION_MARKET_CROWDTEST | ohos.want.action.marketCrowdTest | 指示从应用程序市场众测应用程序的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_SANDBOX |ohos.dlp.params.sandbox | 指示沙盒标志的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_BUNDLE_NAME |ohos.dlp.params.bundleName |指示DLP Bundle名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_MODULE_NAME |ohos.dlp.params.moduleName |指示DLP模块名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_ABILITY_NAME |ohos.dlp.params.abilityName |指示DLP能力名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -| DLP_PARAMS_INDEX |ohos.dlp.params.index |指示DLP索引参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | - -## wantConstant.Entity - -want实体的常数。用于表示目标Ability额外的类别信息。 +want的Params操作的常量。 + +| 名称 | 值 | 说明 | +| ----------------------- | --------------------------- | ------------------------------------------------------------ | +| DLP_PARAMS_SANDBOX | ohos.dlp.params.sandbox | 指示沙盒标志的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | +| DLP_PARAMS_BUNDLE_NAME | ohos.dlp.params.bundleName | 指示DLP Bundle名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | +| DLP_PARAMS_MODULE_NAME | ohos.dlp.params.moduleName | 指示DLP模块名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | +| DLP_PARAMS_ABILITY_NAME | ohos.dlp.params.abilityName | 指示DLP能力名称的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | +| DLP_PARAMS_INDEX | ohos.dlp.params.index | 指示DLP索引参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase -| 名称 | 值 | 说明 | -| ------------ | ------------------ | ---------------------- | -| ENTITY_DEFAULT | entity.system.default | 指示默认实体,如果未指定该实体,则使用该实体。 | -| ENTITY_HOME | entity.system.home | 指示主屏幕实体。 | -| ENTITY_VOICE | entity.system.voice | 表示语音交互实体。 | -| ENTITY_BROWSABLE | entity.system.browsable | 指示浏览器类别。 | -| ENTITY_VIDEO | entity.system.video | 指示视频类别。 | ## wantConstant.Flags diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md index 61c0e1007ae44cc7dda18a55f8355643b99f6a05..766965c889caca098946b9f039cad9a0f9eb484c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -48,8 +48,8 @@ createFormBindingData(obj?: Object | string): FormBindingData **示例:** ```ts -import fs from '@ohos.file.fs'; import formBindingData from '@ohos.app.form.formBindingData'; +import fs from '@ohos.file.fs'; try { let fd = fs.openSync('/path/to/form.png') diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md index 5d6a41a9d89bbc1416b8b8dab8a68de2797a6438..1740b1694057fb926d6634026f980d20a2c702f6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -31,7 +31,6 @@ import formInfo from '@ohos.app.form.formInfo'; | isDefault | boolean | 是 | 否 | 卡片是否是默认卡片。 | | updateEnabled | boolean | 是 | 否 | 卡片是否使能更新。 | | formVisibleNotify | boolean | 是 | 否 | 卡片是否使能可见通知。 | -| relatedBundleName | string | 是 | 否 | 卡片所属的相关联Bundle名称。 | | scheduledUpdateTime | string | 是 | 否 | 卡片更新时间。 | | formConfigAbility | string | 是 | 否 | 卡片配置ability。指定长按卡片弹出的选择框内,编辑选项所对应的ability。 | | updateDuration | number | 是 | 否 | 卡片更新周期。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md index 0f422ebb87ae2ff1710133ece24c273741bc3d8c..60aefc098fad8ba143d99203d891fdc8cd4cefe8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md @@ -306,7 +306,7 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | 是 | 回调返回内存微调级别,显示当前内存使用状态。| + | level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | 是 | 回调返回内存微调级别,显示当前内存使用状态。| **示例:** @@ -330,7 +330,7 @@ onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}) | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | reason | [AbilityConstant.StateType](js-apis-application-abilityConstant.md#abilityconstantstatetype) | 是 | 回调保存状态的原因。 | + | reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | 是 | 回调保存状态的原因。 | | wantParam | {[key: string]: any} | 是 | want相关参数。 | **返回值:** @@ -414,8 +414,8 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; return true; } }; - var method = 'call_Function'; // 约定的通知消息字符串 - var caller; + let method = 'call_Function'; // 约定的通知消息字符串 + let caller; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -499,8 +499,8 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa return true; } }; - var method = 'call_Function'; - var caller; + let method = 'call_Function'; + let caller; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ @@ -551,7 +551,7 @@ release(): void; ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - var caller; + let caller; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { @@ -594,7 +594,7 @@ release(): void; ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - var caller; + let caller; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { @@ -673,7 +673,7 @@ on(method: string, callback: CalleeCallBack): void; return true; } }; - var method = 'call_Function'; + let method = 'call_Function'; function funcCallBack(pdata) { console.log('Callee funcCallBack is called ' + pdata); let msg = new MyMessageAble("test", ""); @@ -720,7 +720,7 @@ off(method: string): void; ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - var method = 'call_Function'; + let method = 'call_Function'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index c776ad0b8b2ce35ebd4e83d1b36660edb9c58210..db018c3171cb5f795305b196e334634c701d353c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -43,7 +43,7 @@ getAbilityDelegator(): AbilityDelegator **示例:** ```ts -var abilityDelegator; +let abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` @@ -65,7 +65,7 @@ getArguments(): AbilityDelegatorArgs **示例:** ```ts -var args = AbilityDelegatorRegistry.getArguments(); +let args = AbilityDelegatorRegistry.getArguments(); console.info("getArguments bundleName:" + args.bundleName); console.info("getArguments testCaseNames:" + args.testCaseNames); console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index cd2faf8c5843b1eea4af6bf3129b9cbd974f38a9..5937d5c23e0d9ec5a86d0ad7fc1d4594cbcea81c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,6 +1,6 @@ # @ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback) -AbilityLifecycleCallback模块提供应用上下文ApplicationContext的生命周期监听方法的回调类的能力,包括onAbilityCreate、onWindowStageCreate、onWindowStageDestroy等方法,可以作为[registerAbilityLifecycleCallback](js-apis-inner-application-applicationContext.md#applicationcontextregisterabilitylifecyclecallback)的入参。 +AbilityLifecycleCallback模块提供应用上下文ApplicationContext的生命周期监听方法的回调类的能力,包括onAbilityCreate、onWindowStageCreate、onWindowStageDestroy等方法,可以作为[on(type: "abilityLifecycle", callback: AbilityLifecycleCallback)](js-apis-inner-application-applicationContext.md#applicationcontextontype-abilitylifecycle-callback-abilitylifecyclecallback)的入参。 > **说明:** > @@ -158,7 +158,7 @@ onAbilityContinue(ability: Ability): void; ```ts import AbilityStage from "@ohos.app.ability.AbilityStage"; -var lifecycleId; +let lifecycleId; export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -210,4 +210,5 @@ export default class MyAbilityStage extends AbilityStage { }); } } -``` \ No newline at end of file +``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md index 23fdbd6b920d84212fbef244a8db5729b832cec4..437b02ddf75a8404c12e7dc8b945aa54b4ac8679 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -49,7 +49,7 @@ updateConfiguration(config: Configuration, callback: AsyncCallback\): void **示例**: ```ts -var config = { +let config = { language: 'chinese' } @@ -83,7 +83,7 @@ updateConfiguration(config: Configuration): Promise\ **示例**: ```ts -var config = { +let config = { language: 'chinese' } diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md index c92c70766e1047b2cb991940f18c89274062967b..a25e60f928746f38fd5213260d49b029c5a2e9c8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md @@ -231,7 +231,7 @@ unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\ **示例:** ```ts - var observerId = 100; + let observerId = 100; function unregisterApplicationStateObserverCallback(err) { if (err) { @@ -268,7 +268,7 @@ unregisterApplicationStateObserver(observerId: number): Promise\; **示例:** ```ts - var observerId = 100; + let observerId = 100; appManager.unregisterApplicationStateObserver(observerId) .then((data) => { @@ -362,8 +362,8 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\ **示例:** ```ts -var bundleName = 'bundleName'; -var accountId = 0; +let bundleName = 'bundleName'; +let accountId = 0; appManager.killProcessWithAccount(bundleName, accountId) .then((data) => { console.log('------------ killProcessWithAccount success ------------', data); @@ -397,8 +397,8 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal **示例:** ```ts -var bundleName = 'bundleName'; -var accountId = 0; +let bundleName = 'bundleName'; +let accountId = 0; function killProcessWithAccountCallback(err, data) { if (err) { console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); @@ -431,7 +431,7 @@ killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); **示例:** ```ts - var bundleName = 'bundleName'; + let bundleName = 'bundleName'; function killProcessesByBundleNameCallback(err, data) { if (err) { console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); @@ -469,7 +469,7 @@ killProcessesByBundleName(bundleName: string): Promise\; **示例:** ```ts - var bundleName = 'com.example.myapplication'; + let bundleName = 'com.example.myapplication'; appManager.killProcessesByBundleName(bundleName) .then((data) => { console.log('------------ killProcessesByBundleName success ------------', data); @@ -501,7 +501,7 @@ clearUpApplicationData(bundleName: string, callback: AsyncCallback\); **示例:** ```ts - var bundleName = 'bundleName'; + let bundleName = 'bundleName'; function clearUpApplicationDataCallback(err, data) { if (err) { console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); @@ -539,7 +539,7 @@ clearUpApplicationData(bundleName: string): Promise\; **示例:** ```ts - var bundleName = 'bundleName'; + let bundleName = 'bundleName'; appManager.clearUpApplicationData(bundleName) .then((data) => { console.log('------------ clearUpApplicationData success ------------', data); diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-environmentCallback.md b/zh-cn/application-dev/reference/apis/js-apis-application-environmentCallback.md index d64165b09cd34581f2caed1e833b5aba949e99e5..c9880f1d89270accc880e4d6289c657867530e77 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-application-environmentCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-environmentCallback.md @@ -41,14 +41,14 @@ onMemoryLevel(level: number): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | 是 | 表示当前内存的基线水平。 | + | level | [MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | 是 | 表示当前内存的基线水平。 | **示例:** ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onCreate() { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md index b3f85620f65ef55dc1da14fe22c6042239ef1566..c769608e6b208cfb117d783e451c2c6523bac08c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-errorManager.md @@ -28,7 +28,7 @@ registerErrorObserver(observer: ErrorObserver): number; **示例:** ```ts -var observer = { +let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) } @@ -54,7 +54,7 @@ unregisterErrorObserver(observerId: number, callback: AsyncCallback\): vo **示例:** ```ts -var observerId = 100; +let observerId = 100; function unregisterErrorObserverCallback(err) { if (err) { @@ -88,7 +88,7 @@ unregisterErrorObserver(observerId: number): Promise\; **示例:** ```ts -var observerId = 100; +let observerId = 100; errorManager.unregisterErrorObserver(observerId) .then((data) => { console.log('----------- unregisterErrorObserver success ----------', data); diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md b/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md index 78f507d1bc172f864f28c6ea597d3e99ca6939f8..efe8b66391532656d4eb094b8c56cb7cafa14f4d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -58,7 +58,7 @@ try { "formImages": { "image": fd } }; formBindingData.createFormBindingData(obj); -} catch (error.code) { +} catch (error) { console.log('catch error, error:' + JSON.stringify(error)); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formExtension.md b/zh-cn/application-dev/reference/apis/js-apis-application-formExtension.md deleted file mode 100644 index 741a99c544f9beaab9111eb5de9813e70645370d..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formExtension.md +++ /dev/null @@ -1,284 +0,0 @@ -# @ohos.application.FormExtension (FormExtension) - -FormExtension模块提供了FormExtension卡片扩展相关接口。 - -> **说明:** -> -> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 从API version 9 开始不再维护,建议使用[FormExtensionAbility](js-apis-app-form-formExtensionAbility.md)替代。 -> 本模块接口仅可在Stage模型下使用。 - -## 导入模块 - -```ts -import FormExtension from '@ohos.application.FormExtension'; -``` - -## 属性 - -**系统能力**:SystemCapability.Ability.Form - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | 是 | 否 | FormExtension的上下文环境,继承自ExtensionContext。 | - -## onCreate - -onCreate(want: Want): formBindingData.FormBindingData - -卡片提供方接收创建卡片的通知接口。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | 是 | 当前Extension相关的Want类型信息,包括卡片ID、卡片名称、卡片样式等。这些卡片信息必须作为持久数据进行管理,以便后续更新和删除卡片。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------------------ | ----------------------------------------------------------- | -| [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | formBindingData.FormBindingData对象,卡片要显示的数据。 | - -**示例:** - -```ts -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onCreate(want) { - console.log('FormExtension onCreate, want:' + want.abilityName); - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -} -``` - -## FormExtension.onCastToNormal - -onCastToNormal(formId: string): void - -卡片提供方接收临时卡片转常态卡片的通知接口。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------------ | -| formId | string | 是 | 请求转换为常态的卡片标识。 | - -**示例:** - -```ts -export default class MyFormExtension extends FormExtension { - onCastToNormal(formId) { - console.log('FormExtension onCastToNormal, formId:' + formId); - } -} -``` - -## FormExtension.onUpdate - -onUpdate(formId: string): void - -卡片提供方接收更新卡片的通知接口。获取最新数据后调用[FormExtensionContext](js-apis-inner-application-formExtensionContext.md)的updateForm接口刷新卡片数据。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| formId | string | 是 | 请求更新的卡片ID。 | - -**示例:** - -```ts -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2).then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } -} -``` - -## FormExtension.onVisibilityChange - -onVisibilityChange(newStatus: { [key: string]: number }): void - -卡片提供方接收修改可见性的通知接口。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------- | -| newStatus | { [key: string]: number } | 是 | 请求修改的卡片ID和可见状态。 | - -**示例:** - -```ts -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onVisibilityChange(newStatus) { - console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2).then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } -} -``` - -## FormExtension.onEvent - -onEvent(formId: string, message: string): void - -卡片提供方接收处理卡片事件的通知接口。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------ | ---- | ---------------------- | -| formId | string | 是 | 请求触发事件的卡片标识。 | -| message | string | 是 | 事件消息。 | - -**示例:** - -```ts -export default class MyFormExtension extends FormExtension { - onEvent(formId, message) { - console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); - } -} -``` - -## FormExtension.onDestroy - -onDestroy(formId: string): void - -卡片提供方接收销毁卡片的通知接口。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| formId | string | 是 | 请求销毁的卡片标识。 | - -**示例:** - -```ts -export default class MyFormExtension extends FormExtension { - onDestroy(formId) { - console.log('FormExtension onDestroy, formId:' + formId); - } -} -``` - -## FormExtension.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -当系统配置更新时调用。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | 是 | 表示需要更新的配置信息。 | - -**示例:** - -```ts -class MyFormExtension extends FormExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } -} -``` - -## FormExtension.onAcquireFormState - -onAcquireFormState?(want: Want): formInfo.FormState; - -卡片提供方接收查询卡片状态通知接口。默认返回卡片初始状态。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | 是 | want表示获取卡片状态的描述。描述包括Bundle名称、能力名称、模块名称、卡片名和卡片维度。 | - -**示例:** - -```ts -import formInfo from '@ohos.application.formInfo' -class MyFormExtension extends FormExtension { - onAcquireFormState(want) { - console.log('FormExtension onAcquireFormState, want:' + want); - return formInfo.FormState.UNKNOWN; - } -} -``` - -## FormExtension.onShare - -onShare?(formId: string): {[key: string]: any}; - -卡片提供方接收卡片分享的通知接口。 - -**系统接口**: 此接口为系统接口。 - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| formId | string | 是 | 卡片标识。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------------------ | ----------------------------------------------------------- | -| {[key: string]: any} | 卡片要分享的数据,由开发者自行决定传入的键值对。 | - -**示例:** - -```ts -class MyFormExtension extends FormExtension { - onShare(formId) { - console.log('FormExtension onShare, formId:' + formId); - let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", - }; - return wantParams; - } -} -``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md index 46506dd17acce9b94600f0f24fb34fa827d5a826..83cbfb25fb8f02c191c10c5c6d973467b7488773 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md @@ -1117,138 +1117,3 @@ formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); }); ``` -## shareForm9+ - -shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void - -指定formId和远程设备Id进行卡片分享。使用callback异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM 和 ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| formId | string | 是 | 卡片标识。 | -| deviceId | string | 是 | 远程设备标识。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当指定formId和远程设备Id进行卡片分享成功,error为undefined,否则为错误对象。 | - -**示例:** - -```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; -formHost.shareForm(formId, deviceId, (error, data) => { - if (error.code) { - console.error('formHost shareForm, error:' + JSON.stringify(error)); - } -}); -``` - -## shareForm9+ - -shareForm(formId: string, deviceId: string): Promise<void> - -指定formId和远程设备Id进行卡片分享。使用Promise异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| formId | string | 是 | 卡片标识。 | -| deviceId | string | 是 | 远程设备标识。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**参数:** - -```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; -formHost.shareForm(formId, deviceId).then(() => { - console.log('formHost shareForm success'); -}).catch((error) => { - console.error('formHost shareForm, error:' + JSON.stringify(error)); -}); -``` - -## notifyFormsPrivacyProtected9+ - -notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean, callback: AsyncCallback<void>): void - -通知指定卡片隐私保护状态改变。使用callback异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| formId | string | 是 | 卡片标识。 | -| deviceId | string | 是 | 远程设备标识。 | - -```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); -formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost shareForm success'); -}).catch((error) => { - console.error('formHost shareForm, error:' + JSON.stringify(error)); -}); -``` - -## notifyFormsPrivacyProtected - -function notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean): Promise<void>; - -通知指定卡片隐私保护状态改变。使用Promise异步回调。 - -**需要权限**:ohos.permission.REQUIRE_FORM - -**系统能力**:SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | --------------- | ---- | -------------------------------- | -| formIds | Array<string> | 是 | 需要修改隐私保护的卡片标识列表。 | -| isProtected | boolean | 是 | 是否进行隐私保护。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - - -```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); -try { - formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost notifyFormsPrivacyProtected success'); - }).catch((error) => { - console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); - }); -} catch(error) { - console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); -} -``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formInfo.md b/zh-cn/application-dev/reference/apis/js-apis-application-formInfo.md index 37b32fbecf14df7d0734b44f31064a47f80c0dd3..5ef129c5b662757befb2de692c8ea5cb053e442a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formInfo.md @@ -49,7 +49,6 @@ import formInfo from '@ohos.application.formInfo'; | 名称 | 值 | 说明 | | ----------- | ---- | ------------ | | JS | 1 | 卡片类型为JS。 | -| eTS9+ | 2 | 卡片类型为eTS。 | ## ColorMode @@ -94,48 +93,11 @@ import formInfo from '@ohos.application.formInfo'; | 名称 | 值 | 说明 | | ----------- | ---- | ------------ | -| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | 卡片标识。
**系统接口**: 此接口为系统接口。 | +| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | 卡片标识。
**系统接口**: 此接口为系统接口。 | | DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | 卡片规格样式。 | | NAME_KEY | "ohos.extra.param.key.form_name" | 卡片名称。 | | MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | 卡片所属模块名称。 | | WIDTH_KEY | "ohos.extra.param.key.form_width" | 卡片宽度。 | | HEIGHT_KEY | "ohos.extra.param.key.form_height" | 卡片高度。 | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | 临时卡片。 | -| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | ability名称。 | -| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | 设备标识。 | -| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | 指示指定要获取的捆绑包名称的键。| -## FormDimension9+ - -定义卡片尺寸枚举。 - -**系统能力**:SystemCapability.Ability.Form - -| 名称 | 值 | 说明 | -| ----------- | ---- | ------------ | -| Dimension_1_2 9+ | 1 | 1 x 2 form。 | -| Dimension_2_2 9+ | 2 | 2 x 2 form。 | -| Dimension_2_4 9+ | 3 | 2 x 4 form。 | -| Dimension_4_4 9+ | 4 | 4 x 4 form。 | -| Dimension_2_1 9+ | 5 | 2 x 1 form。 | - -## FormInfoFilter9+ - -卡片信息过滤器,仅将符合过滤器内要求的卡片信息返回。 - -**系统能力**:SystemCapability.Ability.Form - -| 名称 | 说明 | -| ----------- | ------------ | -| moduleName9+ | 选填。仅保留moduleName与提供值相符的卡片信息。
未填写时则不通过moduleName进行过滤。 | - -## VisibilityType9+ - -卡片当前可见类型枚举。 - -**系统能力**:SystemCapability.Ability.Form - -| 名称 | 值 | 说明 | -| ----------- | ---- | ------------ | -| FORM_VISIBLE9+ | 1 | 表示卡片为可见。 | -| FORM_INVISIBLE9+ | 2 | 表示卡片为不可见。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md index 6f78d8cb6fb2b2c16f62c648e1dc5533ae77c2c3..7bb591aef8fcf1a80725ca779c6aa0f976e9e572 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md @@ -142,307 +142,4 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr }); ``` -## getFormsInfo9+ -getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void - -获取设备上当前应用程序的卡片信息,使用callback异步回调。 - -**系统能力:** SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | 是 | 回调函数。返回查询到的卡片信息。 | - -**示例:** - -```ts -import formProvider from '@ohos.app.form.formProvider'; - -formProvider.getFormsInfo((error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } -}); -``` -## getFormsInfo9+ - -getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void - -获取设备上当前应用程序的卡片信息,并筛选符合条件的信息,使用callback异步回调。 - -**系统能力:** SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | 是 | 卡片信息过滤器。 | -| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | 是 | 回调函数。返回查询到符合条件的卡片信息。 | - -**示例:** - -```ts -import formInfo from '@ohos.application.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" -}; -formProvider.getFormsInfo(filter, (error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } -}); -``` - -## getFormsInfo9+ - -getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>> - -获取设备上当前应用程序的卡片信息,使用Promise异步回调。 - -**系统能力:** SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md) | 否 | 卡片信息过滤器。 | - -**返回值:** - -| 类型 | 说明 | -| :------------ | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise对象。返回查询到符合条件的卡片信息。 | - -**示例:** - -```ts -import formInfo from '@ohos.application.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" -}; -formProvider.getFormsInfo(filter).then((data) => { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); -}).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); -}); -``` - -## requestPublishForm9+ - -requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void - -请求发布一张卡片到使用方。使用方通常为桌面。 - -**系统能力:** SystemCapability.Ability.Form - -**系统接口**: 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。
abilityName: 目标卡片ability
parameters:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | 是 | 创建卡片的数据。 | -| callback | AsyncCallback<string> | 是 | 回调函数。返回卡片标识。 | - -**示例:** - - ```ts - import formBindingData from '@ohos.application.formBindingData'; - import formProvider from '@ohos.app.form.formProvider'; - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - formProvider.requestPublishForm(want, obj, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } - }); - ``` - -## requestPublishForm9+ - -requestPublishForm(want: Want, callback: AsyncCallback<string>): void - -请求发布一张卡片到使用方。使用方通常为桌面。 - -**系统能力:** SystemCapability.Ability.Form - -**系统接口**: 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。
abilityName: 目标卡片ability
parameters:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| callback | AsyncCallback<string> | 是 | 回调函数。返回卡片标识。 | - -**示例:** - - ```ts - import formProvider from '@ohos.app.form.formProvider'; - - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } - }); - ``` - -## requestPublishForm9+ - -requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string> - -请求发布一张卡片到使用方。使用方通常为桌面。 - -**系统能力:** SystemCapability.Ability.Form - -**系统接口**: 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。
abilityName: 目标卡片ability
parameters:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | 是 | 创建卡片的数据。 | - -**返回值:** - -| 类型 | 说明 | -| :------------ | :---------------------------------- | -| Promise<string> | Promise对象。返回卡片标识。 | - -**示例:** - - ```ts - import formProvider from '@ohos.app.form.formProvider'; - - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); - }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - }); - ``` - -## isRequestPublishFormSupported9+ - -isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void - -查询是否支持发布一张卡片到使用方。 - -**系统接口**: 此接口为系统接口。 - -**系统能力:** SystemCapability.Ability.Form - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<boolean> | 是 | 回调函数。返回是否支持发布一张卡片到使用方。| - -**示例:** - -```ts -formProvider.isRequestPublishFormSupported((error, isSupported) => { - if (error.code) { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); - } else { - if (isSupported) { - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } - }); - } - } -}); -``` - -## isRequestPublishFormSupported9+ - -isRequestPublishFormSupported(): Promise<boolean> - -查询是否支持发布一张卡片到使用方。 - -**系统接口**: 此接口为系统接口。 - -**系统能力:** SystemCapability.Ability.Form - -**返回值:** - -| 类型 | 说明 | -| :------------ | :---------------------------------- | -| Promise<boolean> | Promise对象。返回是否支持发布一张卡片到使用方。 | - -**示例:** - -```ts -formProvider.isRequestPublishFormSupported().then((isSupported) => { - if (isSupported) { - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); - }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - }); - } -}).catch((error) => { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); -}); -``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md index deb071195ff0101ee49e8d7f15c73bc6373677f4..90d99a04cd382418e46f8ce05332fb527fbc7d8d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-missionManager.md @@ -43,7 +43,7 @@ registerMissionListener(listener: MissionListener): number; **示例:** ```ts -var listener = { +let listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, @@ -53,7 +53,7 @@ var listener = { onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") -var listenerid = missionManager.registerMissionListener(listener); +let listenerid = missionManager.registerMissionListener(listener); ``` @@ -79,7 +79,7 @@ unregisterMissionListener(listenerId: number, callback: AsyncCallback<void> **示例:** ```ts - var listener = { + let listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, @@ -89,7 +89,7 @@ unregisterMissionListener(listenerId: number, callback: AsyncCallback<void> onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); + let listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid, (error) => { console.log("unregisterMissionListener"); @@ -124,7 +124,7 @@ unregisterMissionListener(listenerId: number): Promise<void>; **示例:** ```ts - var listener = { + let listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, @@ -134,7 +134,7 @@ unregisterMissionListener(listenerId: number): Promise<void>; onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); + let listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid).catch(function (err) { console.log(err); @@ -167,7 +167,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<M ```ts import missionManager from '@ohos.application.missionManager' - var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); + let allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { if (error.code) { console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + @@ -215,7 +215,7 @@ getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; ```ts import missionManager from '@ohos.application.missionManager' - var mission = missionManager.getMissionInfo("", 10).catch(function (err){ + let mission = missionManager.getMissionInfo("", 10).catch(function (err){ console.log(err); }); ``` @@ -288,7 +288,7 @@ getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionIn ```ts import missionManager from '@ohos.application.missionManager' - var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ + let allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); ``` @@ -327,7 +327,7 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback& } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + let id = missions[0].missionId; missionManager.getMissionSnapShot("", id, (error, snapshot) => { if (error.code) { @@ -371,15 +371,15 @@ getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnaps ```ts import missionManager from '@ohos.application.missionManager' - var allMissions; + let allMissions; missionManager.getMissionInfos("",10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + let id = allMissions[0].missionId; - var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ + let snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ console.log(err); }); ``` @@ -417,7 +417,7 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: A } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + let id = missions[0].missionId; missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { if (error.code) { @@ -461,15 +461,15 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\ { @@ -382,7 +382,7 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); @@ -769,7 +769,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" try { var rand = cryptoFramework.createRandom(); } catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } ``` @@ -808,7 +808,7 @@ var rand; try { rand = cryptoFramework.createRandom(); } catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } rand.generateRandom(12, (err, randData) => { if (err) { @@ -918,10 +918,10 @@ rand.generateRandom(12, (err, randData) => { | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | ------ | ---- | ---- | ----------------------- | -| algoName | string | 是 | 是 | 指明对称加解密参数的算法模式。可选值如下:
- "IvParamsSpec": 适用于CBC\|CTR\|OFB\|CFB模式
- "GcmParamsSpec": 适用于GCM模式
- "CcmParamsSpec": 适用于CCM模式 | +| algName | string | 是 | 是 | 指明对称加解密参数的算法模式。可选值如下:
- "IvParamsSpec": 适用于CBC\|CTR\|OFB\|CFB模式
- "GcmParamsSpec": 适用于GCM模式
- "CcmParamsSpec": 适用于CCM模式 | -> **说明:** -> 由于[init()](#init-2)的params参数是ParamsSpec类型(父类),而实际需要传入具体的子类对象(如IvParamsSpec),因此在构造子类对象时应设置其父类ParamsSpec的algoName参数,使算法库在init()时知道传入的是哪种子类对象。 +> **说明:** +> 由于[init()](#init-2)的params参数是ParamsSpec类型(父类),而实际需要传入具体的子类对象(如IvParamsSpec),因此在构造子类对象时应设置其父类ParamsSpec的algName参数,使算法库在init()时知道传入的是哪种子类对象。 ## IvParamsSpec @@ -933,8 +933,8 @@ rand.generateRandom(12, (err, randData) => { | ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | | iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv。常见取值如下:
- AES的CBC\|CTR\|OFB\|CFB模式:iv长度为16字节
- 3DES的CBC\|OFB\|CFB模式:iv长度为8字节 | -> **说明:** -> 传入[init()](#init-2)方法前需要指定其algoName属性(来源于父类[ParamsSpec](#paramsspec))。 +> **说明:** +> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。 ## GcmParamsSpec @@ -948,8 +948,8 @@ rand.generateRandom(12, (err, randData) => { | aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节 | | authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为16字节。
采用GCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),取出其末尾16字节作为解密时[init()](#init-2)方法的入参[GcmParamsSpec](#gcmparamsspec)中的的authTag | -> **说明:** -> 传入[init()](#init-2)方法前需要指定其algoName属性(来源于父类[ParamsSpec](#paramsspec))。 +> **说明:** +> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。 ## CcmParamsSpec @@ -963,8 +963,8 @@ rand.generateRandom(12, (err, randData) => { | aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节 | | authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为12字节。
采用CCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),取出其末尾12字节作为解密时[init()](#init-2)方法的入参[CcmParamsSpec](#ccmparamsspec)中的authTag | -> **说明:** -> 传入[init()](#init-2)方法前需要指定其algoName属性(来源于父类[ParamsSpec](#paramsspec))。 +> **说明:** +> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。 ## CryptoMode @@ -983,7 +983,7 @@ rand.generateRandom(12, (err, randData) => { ### 属性 -**系统能力:** SystemCapability.Security.CryptoFramework +**系统能力:** SystemCapability.Security.CryptoFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------- | ------ | ---- | ---- | ---------------------------- | @@ -1055,7 +1055,7 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // 输出全 ### 属性 -**系统能力:** SystemCapability.Security.CryptoFramework +**系统能力:** SystemCapability.Security.CryptoFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------- | ------ | ---- | ---- | ---------------------------- | @@ -1099,7 +1099,7 @@ console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ### 属性 -**系统能力:** SystemCapability.Security.CryptoFramework +**系统能力:** SystemCapability.Security.CryptoFramework | 名称 | 类型 | 可读 | 可写 | 说明 | | ------- | ------ | ---- | ---- | ---------------------------- | @@ -1228,8 +1228,8 @@ generateSymKey(callback : AsyncCallback\) : void ```js import cryptoFramework from '@ohos.security.cryptoFramework'; -let symAlgoName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); symKeyGenerator.generateSymKey((err, symKey) => { if (err) { console.error(`Generate symKey failed, ${err.code}, ${err.message}`); @@ -1263,8 +1263,8 @@ generateSymKey() : Promise\ ```js import cryptoFramework from '@ohos.security.cryptoFramework'; -let symAlgoName = 'AES128'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); +let symAlgName = 'AES128'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); symKeyGenerator.generateSymKey() .then(symKey => { console.info(`Generate symKey success, algName: ${symKey.algName}`); @@ -1308,8 +1308,8 @@ function genKeyMaterialBlob() { return {data : keyMaterial}; } -let symAlgoName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); let keyMaterialBlob = genKeyMaterialBlob(); symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { if (err) { @@ -1360,8 +1360,8 @@ function genKeyMaterialBlob() { return {data : keyMaterial}; } -let symAlgoName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); let keyMaterialBlob = genKeyMaterialBlob(); symKeyGenerator.convertKey(keyMaterialBlob) .then(symKey => { @@ -1582,7 +1582,7 @@ createCipher(transformation : string) : Cipher | -------------- | ------ | ---- | ------------------------------------------------------------ | | transformation | string | 是 | 待生成Cipher的算法名称(含密钥长度)、加密模式以及填充方法的组合。
具体取值详见框架概述“[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)”一节中的“字符串参数”。 | -> **说明:** +> **说明:** > 1. 目前对称加解密中,PKCS5和PKCS7的实现相同,其padding长度和分组长度保持一致(即PKCS5和PKCS7在3DES中均按照8字节填充,在AES中均按照16字节填充),另有NoPadding表示不填充。
开发者需要自行了解密码学不同分组模式的差异,以便选择合适的参数规格。例如选择ECB和CBC模式时,建议启用填充,否则必须确保明文长度是分组大小的整数倍;选择其他模式时,可以不启用填充,此时密文长度和明文长度一致(即可能不是分组大小的整数倍)。 > 2. 使用RSA进行非对称加解密时,必须创建两个Cipher对象分别进行加密和解密操作,而不能对同一个Cipher对象进行加解密。对称加解密没有此要求(即只要算法规格一样,可以对同一个Cipher对象进行加解密操作)。 @@ -1597,10 +1597,10 @@ createCipher(transformation : string) : Cipher ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let cipherAlgoName = '3DES192|ECB|PKCS7'; +let cipherAlgName = '3DES192|ECB|PKCS7'; var cipher; try { - cipher = cryptoFramework.createCipher(cipherAlgoName); + cipher = cryptoFramework.createCipher(cipherAlgName); console.info(`cipher algName: ${cipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); @@ -1718,7 +1718,7 @@ update(data : DataBlob, callback : AsyncCallback\) : void 分段更新加密或者解密数据操作,通过注册回调函数获取加/解密数据。
必须在对[Cipher](#cipher)实例使用[init()](init-2)初始化后,才能使用本函数。 -> **说明:** +> **说明:** > 1. 在进行对称加解密操作的时候,如果开发者对各个分组模式不够熟悉,建议对每次update和doFinal的结果都判断是否为null,并在结果不为null时取出其中的数据进行拼接,形成完整的密文/明文。这是因为选择的分组模式等各项规格都可能对update和[doFinal](#dofinal-2)结果产生影响。
(例如对于ECB和CBC模式,不论update传入的数据是否为分组长度的整数倍,都会以分组作为基本单位进行加/解密,并输出本次update新产生的加/解密分组结果。
可以理解为,update只要凑满一个新的分组就会有输出,如果没有凑满则此次update输出为null,把当前还没被加/解密的数据留着,等下一次update/doFinal传入数据的时候,拼接起来继续凑分组。
最后doFinal的时候,会把剩下的还没加/解密的数据,根据[createCipher](#cryptoframeworkcreatecipher)时设置的padding模式进行填充,补齐到分组的整数倍长度,再输出剩余加解密结果。
而对于可以将分组密码转化为流模式实现的模式,还可能出现密文长度和明文长度相同的情况等。) > 2. 根据数据量,可以不调用update(即[init](#init-2)完成后直接调用[doFinal](#dofinal-2))或多次调用update。
算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的对称加解密,采用多次update的方式传入数据。 > 3. RSA非对称加解密不支持update操作。 @@ -1775,7 +1775,7 @@ update(data : DataBlob) : Promise\ 分段更新加密或者解密数据操作,通过通过Promise获取加/解密数据。
必须在对[Cipher](#cipher)实例使用[init()](init-2)初始化后,才能使用本函数。 -> **说明:** +> **说明:** > 1. 在进行对称加解密操作的时候,如果开发者对各个分组模式不够熟悉,建议对每次update和doFinal的结果都判断是否为null,并在结果不为null时取出其中的数据进行拼接,形成完整的密文/明文。这是因为选择的分组模式等各项规格都可能对update和[doFinal](#dofinal-2)结果产生影响。
(例如对于ECB和CBC模式,不论update传入的数据是否为分组长度的整数倍,都会以分组作为基本单位进行加/解密,并输出本次update新产生的加/解密分组结果。
可以理解为,update只要凑满一个新的分组就会有输出,如果没有凑满则此次update输出为null,把当前还没被加/解密的数据留着,等下一次update/doFinal传入数据的时候,拼接起来继续凑分组。
最后doFinal的时候,会把剩下的还没加/解密的数据,根据[createCipher](#cryptoframeworkcreatecipher)时设置的padding模式进行填充,补齐到分组的整数倍长度,再输出剩余加解密结果。
而对于可以将分组密码转化为流模式实现的模式,还可能出现密文长度和明文长度相同的情况等。) > 2. 根据数据量,可以不调用update(即[init](#init-2)完成后直接调用[doFinal](#dofinal-2))或多次调用update。
算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的对称加解密,可以采用多次update的方式传入数据。 > 3. RSA非对称加解密不支持update操作。 @@ -1841,7 +1841,7 @@ doFinal(data : DataBlob, callback : AsyncCallback\) : void (2)在RSA非对称加解密中,doFinal加/解密本次传入的数据,通过注册回调函数获取加密或者解密数据。如果数据量较大,可以多次调用doFinal,拼接结果得到完整的明文/密文。 -> **说明:** +> **说明:** > 1. 对称加解密中,调用doFinal标志着一次加解密流程已经完成,即[Cipher](#cipher)实例的状态被清除,因此当后续开启新一轮加解密流程时,需要重新调用[init()](init-2)并传入完整的参数列表进行初始化
(比如即使是对同一个Cipher实例,采用同样的对称密钥,进行加密然后解密,则解密中调用init的时候仍需填写params参数,而不能直接省略为null)。 > 2. 如果遇到解密失败,需检查加解密数据和[init](#init-2)时的参数是否匹配,包括GCM模式下加密得到的authTag是否填入解密时的GcmParamsSpec等。 @@ -1893,7 +1893,7 @@ doFinal(data : DataBlob) : Promise\ (2)在RSA非对称加解密中,doFinal加/解密本次传入的数据,通过Promise获取加密或者解密数据。如果数据量较大,可以多次调用doFinal,拼接结果得到完整的明文/密文。 -> **说明:** +> **说明:** > 1. 对称加解密中,调用doFinal标志着一次加解密流程已经完成,即[Cipher](#cipher)实例的状态被清除,因此当后续开启新一轮加解密流程时,需要重新调用[init()](init-2)并传入完整的参数列表进行初始化
(比如即使是对同一个Cipher实例,采用同样的对称密钥,进行加密然后解密,则解密中调用init的时候仍需填写params参数,而不能直接省略为null)。 > 2. 如果遇到解密失败,需检查加解密数据和[init](#init-2)时的参数是否匹配,包括GCM模式下加密得到的authTag是否填入解密时的GcmParamsSpec等。 @@ -1993,7 +1993,7 @@ keyGenPromise.then(rsaKeyPair => { }); ``` -> **说明:** +> **说明:** > 更多加解密流程的完整示例可参考开发指导中的“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”一节。 ## cryptoFramework.createSign diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md index f4d7e48663787ed4085aae8363ce98c32d8f0123..c94780f46579a103230146e7abe796914e6b353a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -15,10 +15,10 @@ ## 导入模块 ```js -import data_rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore' ``` -## data_rdb.getRdbStore +## relationalStore.getRdbStore getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void @@ -51,20 +51,23 @@ FA模型示例: import featureAbility from '@ohos.ability.featureAbility' +var store; + // 获取context -let context = featureAbility.getContext() +let context = featureAbility.getContext(); const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} - -data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - if (err) { - console.info("Get RdbStore failed, err: " + err) - return - } - console.log("Get RdbStore successfully.") + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; + +relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + if (err) { + console.error(`Get RdbStore failed, err: ${err}`); + return; + } + console.info(`Get RdbStore successfully.`); }) ``` @@ -74,24 +77,26 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + onWindowStageCreate(windowStage) { + var store; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 + }; - data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { - if (err) { - console.info("Get RdbStore failed, err: " + err) - return - } - console.log("Get RdbStore successfully.") - }) - } + relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + if (err) { + console.error(`Get RdbStore failed, err: ${err}`); + return; + } + console.info(`Get RdbStore successfully.`); + }) + } } ``` -## data_rdb.getRdbStore +## relationalStore.getRdbStore getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> @@ -128,19 +133,22 @@ FA模型示例: ```js import featureAbility from '@ohos.ability.featureAbility' +var store; + // 获取context -let context = featureAbility.getContext() +let context = featureAbility.getContext(); const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; -let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +let promise = relationalStore.getRdbStore(context, STORE_CONFIG); promise.then(async (rdbStore) => { - console.log("Get RdbStore successfully.") + store = rdbStore; + console.info(`Get RdbStore successfully.`); }).catch((err) => { - console.log("Get RdbStore failed, err: " + err) + console.error(`Get RdbStore failed, err: ${err}`); }) ``` @@ -150,23 +158,25 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + onWindowStageCreate(windowStage) { + var store; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 + }; - let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG); - promise.then(async (rdbStore) => { - console.log("Get RdbStore successfully.") - }).catch((err) => { - console.log("Get RdbStore failed, err: " + err) - }) - } + let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG); + promise.then(async (rdbStore) => { + store = rdbStore; + console.info(`Get RdbStore successfully.`) + }).catch((err) => { + console.error(`Get RdbStore failed, err: ${err}`); + }) + } } ``` -## data_rdb.deleteRdbStore +## relationalStore.deleteRdbStore deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void @@ -200,12 +210,12 @@ import featureAbility from '@ohos.ability.featureAbility' // 获取context let context = featureAbility.getContext() -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStore failed, err: " + err) - return - } - console.log("Delete RdbStore successfully.") +relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.error(`Delete RdbStore failed, err: ${err}`); + return; + } + console.info(`Delete RdbStore successfully.`); }) ``` @@ -215,19 +225,19 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStore failed, err: " + err) - return - } - console.log("Delete RdbStore successfully.") - }) - } + onWindowStageCreate(windowStage){ + relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) { + if (err) { + console.error(`Delete RdbStore failed, err: ${err}`); + return; + } + console.info(`Delete RdbStore successfully.`); + }) + } } ``` -## data_rdb.deleteRdbStore +## relationalStore.deleteRdbStore deleteRdbStore(context: Context, name: string): Promise<void> @@ -264,13 +274,13 @@ FA模型示例: import featureAbility from '@ohos.ability.featureAbility' // 获取context -let context = featureAbility.getContext() +let context = featureAbility.getContext(); -let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +let promise = relationalStore.deleteRdbStore(context, "RdbTest.db"); promise.then(()=>{ - console.log("Delete RdbStore successfully.") + console.info(`Delete RdbStore successfully.`); }).catch((err) => { - console.info("Delete RdbStore failed, err: " + err) + console.error(`Delete RdbStore failed, err: ${err}`); }) ``` @@ -280,14 +290,14 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") - promise.then(()=>{ - console.log("Delete RdbStore successfully.") - }).catch((err) => { - console.info("Delete RdbStore failed, err: " + err) - }) - } + onWindowStageCreate(windowStage){ + let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); + promise.then(()=>{ + console.info(`Delete RdbStore successfully.`); + }).catch((err) => { + console.error(`Delete RdbStore failed, err: ${err}`); + }) + } } ``` @@ -397,7 +407,7 @@ constructor(name: string) **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); ``` ### inDevices @@ -424,8 +434,8 @@ inDevices(devices: Array<string>): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inDevices(['12345678abcde']) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.inDevices(['12345678abcde']); ``` ### inAllDevices @@ -446,8 +456,8 @@ inAllDevices(): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inAllDevices() +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.inAllDevices(); ``` ### equalTo @@ -475,8 +485,8 @@ equalTo(field: string, value: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "lisi"); ``` @@ -505,8 +515,8 @@ notEqualTo(field: string, value: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notEqualTo("NAME", "lisi") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notEqualTo("NAME", "lisi"); ``` @@ -528,7 +538,7 @@ beginWrap(): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) @@ -554,7 +564,7 @@ endWrap(): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) @@ -580,7 +590,7 @@ or(): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") @@ -603,7 +613,7 @@ and(): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) @@ -633,8 +643,8 @@ contains(field: string, value: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.contains("NAME", "os") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.contains("NAME", "os"); ``` ### beginsWith @@ -661,8 +671,8 @@ beginsWith(field: string, value: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.beginsWith("NAME", "os") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.beginsWith("NAME", "os"); ``` ### endsWith @@ -689,8 +699,8 @@ endsWith(field: string, value: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.endsWith("NAME", "se") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.endsWith("NAME", "se"); ``` ### isNull @@ -716,8 +726,8 @@ isNull(field: string): RdbPredicates **示例**: ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNull("NAME") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNull("NAME"); ``` ### isNotNull @@ -743,8 +753,8 @@ isNotNull(field: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNotNull("NAME") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNotNull("NAME"); ``` ### like @@ -771,8 +781,8 @@ like(field: string, value: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.like("NAME", "%os%") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.like("NAME", "%os%"); ``` ### glob @@ -799,8 +809,8 @@ glob(field: string, value: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.glob("NAME", "?h*g") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.glob("NAME", "?h*g"); ``` ### between @@ -828,8 +838,8 @@ between(field: string, low: ValueType, high: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.between("AGE", 10, 50) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.between("AGE", 10, 50); ``` ### notBetween @@ -857,8 +867,8 @@ notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notBetween("AGE", 10, 50) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notBetween("AGE", 10, 50); ``` ### greaterThan @@ -885,8 +895,8 @@ greaterThan(field: string, value: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThan("AGE", 18) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.greaterThan("AGE", 18); ``` ### lessThan @@ -913,8 +923,8 @@ lessThan(field: string, value: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThan("AGE", 20) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThan("AGE", 20); ``` ### greaterThanOrEqualTo @@ -941,8 +951,8 @@ greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThanOrEqualTo("AGE", 18) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.greaterThanOrEqualTo("AGE", 18); ``` ### lessThanOrEqualTo @@ -969,8 +979,8 @@ lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThanOrEqualTo("AGE", 20) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThanOrEqualTo("AGE", 20); ``` ### orderByAsc @@ -996,8 +1006,8 @@ orderByAsc(field: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByAsc("NAME") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByAsc("NAME"); ``` ### orderByDesc @@ -1023,8 +1033,8 @@ orderByDesc(field: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByDesc("AGE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByDesc("AGE"); ``` ### distinct @@ -1044,8 +1054,8 @@ distinct(): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").distinct() +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").distinct(); ``` ### limitAs @@ -1071,8 +1081,8 @@ limitAs(value: number): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").limitAs(3) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").limitAs(3); ``` ### offsetAs @@ -1098,8 +1108,8 @@ offsetAs(rowOffset: number): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").offsetAs(3) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").offsetAs(3); ``` ### groupBy @@ -1125,8 +1135,8 @@ groupBy(fields: Array<string>): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.groupBy(["AGE", "NAME"]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.groupBy(["AGE", "NAME"]); ``` ### indexedBy @@ -1153,8 +1163,8 @@ indexedBy(field: string): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.indexedBy("SALARY_INDEX") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.indexedBy("SALARY_INDEX"); ``` ### in @@ -1181,8 +1191,8 @@ in(field: string, value: Array<ValueType>): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.in("AGE", [18, 20]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.in("AGE", [18, 20]); ``` ### notIn @@ -1209,8 +1219,8 @@ notIn(field: string, value: Array<ValueType>): RdbPredicates **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notIn("NAME", ["Lisa", "Rose"]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notIn("NAME", ["Lisa", "Rose"]); ``` ## RdbStore @@ -1231,9 +1241,9 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) ```js // 设置数据库版本 -rdbStore.version = 3 +store.version = 3; // 获取数据库版本 -console.info("Get RdbStore version is " + rdbStore.version) +console.info(`RdbStore version is ${store.version}`); ``` ### insert @@ -1256,17 +1266,17 @@ insert(table: string, values: ValuesBucket, callback: AsyncCallback<number> ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { - if (status) { - console.log("Insert is failed"); - return; - } - console.log("Insert is successful, rowId = " + rowId); + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +store.insert("EMPLOYEE", valueBucket, function (err, rowId) { + if (err) { + console.error(`Insert is failed, err: ${err}`); + return; + } + console.info(`Insert is successful, rowId = ${rowId}`); }) ``` @@ -1291,17 +1301,17 @@ insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callb ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (status, rowId) { - if (status) { - console.log("Insert is failed"); - return; - } - console.log("Insert is successful, rowId = " + rowId); + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) { + if (err) { + console.error(`Insert is failed, err: ${err}`); + return; + } + console.info(`Insert is successful, rowId = ${rowId}`); }) ``` @@ -1330,16 +1340,16 @@ insert(table: string, values: ValuesBucket):Promise<number> ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let promise = rdbStore.insert("EMPLOYEE", valueBucket) + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let promise = store.insert("EMPLOYEE", valueBucket); promise.then((rowId) => { - console.log("Insert is successful, rowId = " + rowId); -}).catch((status) => { - console.log("Insert is failed"); + console.info(`Insert is successful, rowId = ${rowId}`); +}).catch((err) => { + console.error(`Insert is failed, err: ${err}`); }) ``` @@ -1369,16 +1379,16 @@ insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promi ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let promise = rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); promise.then((rowId) => { - console.log("Insert is successful, rowId = " + rowId); -}).catch((status) => { - console.log("Insert is failed"); + console.info(`Insert is successful, rowId = ${rowId}`); +}).catch((err) => { + console.error(`Insert is failed, err: ${err}`); }) ``` @@ -1402,31 +1412,31 @@ batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCal ```js const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) -} + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +}; const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) -} + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +}; const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) -} + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +}; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { - if (status) { - console.log("batchInsert is failed, status = " + status); - return; - } - console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +store.batchInsert("EMPLOYEE", valueBuckets, function(err, insertNum) { + if (err) { + console.error(`batchInsert is failed, err: ${err}`); + return; + } + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); }) ``` @@ -1455,30 +1465,30 @@ batchInsert(table: string, values: Array<ValuesBucket>):Promise<number& ```js const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) -} + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +}; const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) -} + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +}; const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) -} + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +}; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +let promise = store.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { - console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); -}).catch((status) => { - console.log("batchInsert is failed, status = " + status); + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); +}).catch((err) => { + console.error(`batchInsert is failed, err: ${err}`); }) ``` @@ -1502,19 +1512,19 @@ update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback& ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, rows) { - if (err) { - console.info("Updated failed, err: " + err) - return - } - console.log("Updated row count: " + rows) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +store.update(valueBucket, predicates, function (err, rows) { + if (err) { + console.error(`Updated failed, err: ${err}`); + return; + } + console.info(`Updated row count: ${rows}`); }) ``` @@ -1539,19 +1549,19 @@ update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolu ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { - if (err) { - console.info("Updated failed, err: " + err) - return - } - console.log("Updated row count: " + rows) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { + if (err) { + console.error(`Updated failed, err: ${err}`); + return; + } + console.info(`Updated row count: ${rows}`); }) ``` @@ -1580,18 +1590,18 @@ update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update(valueBucket, predicates) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +let promise = store.update(valueBucket, predicates); promise.then(async (rows) => { - console.log("Updated row count: " + rows) + console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.info("Updated failed, err: " + err) + console.error(`Updated failed, err: ${err}`); }) ``` @@ -1621,18 +1631,18 @@ update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolu ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +let promise = store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); promise.then(async (rows) => { - console.log("Updated row count: " + rows) + console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.info("Updated failed, err: " + err) + console.error(`Updated failed, err: ${err}`); }) ``` @@ -1664,15 +1674,15 @@ const valueBucket = { "AGE": 22, "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { - if (err) { - console.info("Updated failed, err: " + err) - return - } - console.log("Updated row count: " + rows) +}; +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +store.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { + if (err) { + console.error(`Updated failed, err: ${err}`); + return; + } + console.info(`Updated row count: ${rows}`); }) ``` @@ -1705,18 +1715,18 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +let promise = store.update("EMPLOYEE", valueBucket, predicates); promise.then(async (rows) => { - console.log("Updated row count: " + rows) + console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.info("Updated failed, err: " + err) + console.error(`Updated failed, err: ${err}`); }) ``` @@ -1738,14 +1748,14 @@ delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.delete(predicates, function (err, rows) { - if (err) { - console.info("Delete failed, err: " + err) - return - } - console.log("Delete rows: " + rows) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +store.delete(predicates, function (err, rows) { + if (err) { + console.error(`Delete failed, err: ${err}`); + return; + } + console.info(`Delete rows: ${rows}`); }) ``` @@ -1772,13 +1782,13 @@ delete(predicates: RdbPredicates):Promise<number> **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete(predicates) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +let promise = store.delete(predicates); promise.then((rows) => { - console.log("Delete rows: " + rows) + console.info(`Delete rows: ${rows}`); }).catch((err) => { - console.info("Delete failed, err: " + err) + console.error(`Delete failed, err: ${err}`); }) ``` @@ -1804,14 +1814,14 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callb ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { - if (err) { - console.info("Delete failed, err: " + err) - return - } - console.log("Delete rows: " + rows) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +store.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.error(`Delete failed, err: ${err}`); + return; + } + console.info(`Delete rows: ${rows}`); }) ``` @@ -1842,13 +1852,13 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promi ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +let promise = store.delete("EMPLOYEE", predicates); promise.then((rows) => { - console.log("Delete rows: " + rows) + console.info(`Delete rows: ${rows}`); }).catch((err) => { - console.info("Delete failed, err: " + err) + console.error(`Delete failed, err: ${err}`); }) ``` @@ -1871,15 +1881,15 @@ query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCa **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose") -rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Query failed, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose"); +store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.error(`Query failed, err: ${err}`); + return; + } + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }) ``` @@ -1907,14 +1917,14 @@ query(predicates: RdbPredicates, columns?: Array<string>):Promise<Resul **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Query failed, err: " + err) + console.error(`Query failed, err: ${err}`); }) ``` @@ -1941,15 +1951,15 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Query failed, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Rose"); +store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.error(`Query failed, err: ${err}`); + return; + } + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }) ``` @@ -1981,14 +1991,14 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Rose"); +let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Query failed, err: " + err) + console.error(`Query failed, err: ${err}`); }) ``` @@ -2013,17 +2023,18 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A **示例:** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ +let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); +predicates.greaterThan("id", 0); +store.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSet) { if (err) { - console.info("Failed to remoteQuery, err: " + err) - return + console.error(`Failed to remoteQuery, err: ${err}`); + return; } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); + } +) ``` ### remoteQuery @@ -2052,14 +2063,14 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A **示例:** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); +predicates.greaterThan("id", 0); +let promise = store.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) + console.error(`Failed to remoteQuery, err: ${err}`); }) ``` @@ -2082,13 +2093,13 @@ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback& **示例:** ```js -rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { - if (err) { - console.info("Query failed, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { + if (err) { + console.error(`Query failed, err: ${err}`); + return; + } + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }) ``` @@ -2116,12 +2127,12 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> **示例:** ```js -let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']); promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Query failed, err: " + err) + console.error(`Query failed, err: ${err}`); }) ``` @@ -2145,12 +2156,12 @@ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallbac ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" -rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { - if (err) { - console.info("ExecuteSql failed, err: " + err) - return - } - console.info('Create table done.') +store.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.error(`ExecuteSql failed, err: ${err}`); + return; + } + console.info(`Create table done.`); }) ``` @@ -2179,11 +2190,11 @@ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" -let promise = rdbStore.executeSql(SQL_CREATE_TABLE) +let promise = store.executeSql(SQL_CREATE_TABLE); promise.then(() => { - console.info('Create table done.') + console.info(`Create table done.`); }).catch((err) => { - console.info("ExecuteSql failed, err: " + err) + console.error(`ExecuteSql failed, err: ${err}`); }) ``` @@ -2199,19 +2210,25 @@ beginTransaction():void ```js import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { - rdbStore.beginTransaction() - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() +let context = featureAbility.getContext(); +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; +relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { + if (err) { + console.error(`GetRdbStore failed, err: ${err}`); + return; + } + store.beginTransaction(); + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + }; + await store.insert("test", valueBucket); + store.commit(); }) ``` @@ -2227,19 +2244,25 @@ commit():void ```js import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { - rdbStore.beginTransaction() - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() +let context = featureAbility.getContext(); +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; +relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { + if (err) { + console.error(`GetRdbStore failed, err: ${err}`); + return; + } + store.beginTransaction(); + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + }; + await store.insert("test", valueBucket); + store.commit(); }) ``` @@ -2255,24 +2278,31 @@ rollBack():void ```js import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { - try { - rdbStore.beginTransaction() - const valueBucket = { - "id": 1, - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() - } catch (e) { - rdbStore.rollBack() - } +let context = featureAbility.getContext(); +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; +relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { + if (err) { + console.error(`GetRdbStore failed, err: ${err}`); + return; + } + try { + store.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + }; + await store.insert("test", valueBucket); + store.commit(); + } catch (err) { + console.error(`Transaction failed, err: ${err}`); + store.rollBack(); + } }) ``` @@ -2294,12 +2324,12 @@ backup(destName:string, callback: AsyncCallback<void>):void **示例:** ```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Backup failed, err: ' + err) - return - } - console.info('Backup success.') +store.backup("dbBackup.db", function(err) { + if (err) { + console.error(`Backup failed, err: ${err}`); + return; + } + console.info(`Backup success.`); }) ``` @@ -2326,11 +2356,11 @@ backup(destName:string): Promise<void> **示例:** ```js -let promiseBackup = rdbStore.backup("dbBackup.db") +let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(()=>{ - console.info('Backup success.') + console.info(`Backup success.`); }).catch((err)=>{ - console.info('Backup failed, err: ' + err) + console.error(`Backup failed, err: ${err}`); }) ``` @@ -2352,12 +2382,12 @@ restore(srcName:string, callback: AsyncCallback<void>):void **示例:** ```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Restore failed, err: ' + err) - return - } - console.info('Restore success.') +store.restore("dbBackup.db", function(err) { + if (err) { + console.error(`Restore failed, err: ${err}`); + return; + } + console.info(`Restore success.`); }) ``` @@ -2384,11 +2414,11 @@ restore(srcName:string): Promise<void> **示例:** ```js -let promiseRestore = rdbStore.restore("dbBackup.db") +let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(()=>{ - console.info('Restore success.') + console.info(`Restore success.`); }).catch((err)=>{ - console.info('Restore failed, err: ' + err) + console.error(`Restore failed, err: ${err}`); }) ``` @@ -2412,12 +2442,12 @@ setDistributedTables(tables: Array<string>, callback: AsyncCallback<voi **示例:** ```js -rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { - if (err) { - console.info('SetDistributedTables failed, err: ' + err) - return - } - console.info('SetDistributedTables successfully.') +store.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.error(`SetDistributedTables failed, err: ${err}`); + return; + } + console.info(`SetDistributedTables successfully.`); }) ``` @@ -2446,11 +2476,11 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { **示例:** ```js -let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) +let promise = store.setDistributedTables(["EMPLOYEE"]); promise.then(() => { - console.info("SetDistributedTables successfully.") + console.info(`SetDistributedTables successfully.`); }).catch((err) => { - console.info("SetDistributedTables failed, err: " + err) + console.error(`SetDistributedTables failed, err: ${err}`); }) ``` @@ -2475,12 +2505,12 @@ obtainDistributedTableName(device: string, table: string, callback: AsyncCallbac **示例:** ```js -rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { +store.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { if (err) { - console.info('ObtainDistributedTableName failed, err: ' + err) - return + console.error(`ObtainDistributedTableName failed, err: ${err}`); + return; } - console.info('ObtainDistributedTableName successfully, tableName=.' + tableName) + console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }) ``` @@ -2510,11 +2540,11 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, **示例:** ```js -let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +let promise = store.obtainDistributedTableName("12345678abcde", "EMPLOYEE"); promise.then((tableName) => { - console.info('ObtainDistributedTableName successfully, tableName= ' + tableName) + console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }).catch((err) => { - console.info('ObtainDistributedTableName failed, err: ' + err) + console.error(`ObtainDistributedTableName failed, err: ${err}`); }) ``` @@ -2539,17 +2569,17 @@ sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array **示例:** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.inDevices(['12345678abcde']) -rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { - if (err) { - console.log('Sync failed, err: ' + err) - return - } - console.log('Sync done.') - for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + ' status=' + result[i][1]) - } +let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); +predicates.inDevices(['12345678abcde']); +store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { + if (err) { + console.error(`Sync failed, err: ${err}`); + return; + } + console.info(`Sync done.`); + for (let i = 0; i < result.length; i++) { + console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); + } }) ``` @@ -2579,16 +2609,16 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul **示例:** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.inDevices(['12345678abcde']) -let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) +let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); +predicates.inDevices(['12345678abcde']); +let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates); promise.then((resultSet) =>{ - console.log('Sync done.') - for (let i = 0; i < resultSet.length; i++) { - console.log('device=' + resultSet[i][0] + ' status=' + resultSet[i][1]) - } + console.info(`Sync done.`); + for (let i = 0; i < resultSet.length; i++) { + console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); + } }).catch((err) => { - console.log('Sync failed') + console.error(`Sync failed, err: ${err}`); }) ``` @@ -2612,14 +2642,14 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri ```js function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + devices[i] + ' data changed') - } + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } } try { - rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.log('Register observer failed') + console.error(`Register observer failed, err: ${err}`); } ``` @@ -2643,14 +2673,14 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri ```js function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + devices[i] + ' data changed') - } + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } } try { - rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.log('Unregister observer failed') + console.error(`Unregister observer failed, err: ${err}`); } ``` @@ -2660,16 +2690,15 @@ try { ### 使用说明 -需要通过[RdbStore.query()](#query)获取resultSet对象。 +首先需要获取resultSet对象。 ```js -import dataRdb from '@ohos.data.rdb'; -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("AGE", 18); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); + console.info(`resultSet columnNames: ${resultSet.columnNames}`); + console.info(`resultSet columnCount: ${resultSet.columnCount}`); }); ``` @@ -2794,13 +2823,13 @@ goTo(offset:number): boolean **示例:** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise= rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise= store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goTo(1); - resultSet.close(); + resultSet.goTo(1); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2835,13 +2864,13 @@ goToRow(position: number): boolean **示例:** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.(5); - resultSet.close(); + resultSet.(5); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2871,13 +2900,13 @@ goToFirstRow(): boolean **示例:** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToFirstRow(); - resultSet.close(); + resultSet.goToFirstRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2906,13 +2935,13 @@ goToLastRow(): boolean **示例:** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToLastRow(); - resultSet.close(); + resultSet.goToLastRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2941,13 +2970,13 @@ goToNextRow(): boolean **示例:** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToNextRow(); - resultSet.close(); + resultSet.goToNextRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2976,13 +3005,13 @@ goToPreviousRow(): boolean **示例:** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToPreviousRow(); - resultSet.close(); + resultSet.goToPreviousRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -3135,12 +3164,12 @@ close(): void **示例:** ```js -let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); -let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicatesClose = new relationalStore.RdbPredicates("EMPLOYEE"); +let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promiseClose.then((resultSet) => { - resultSet.close(); + resultSet.close(); }).catch((err) => { - console.log('resultset close failed'); + console.error(`resultset close failed, err: ${err}`); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-device-info.md b/zh-cn/application-dev/reference/apis/js-apis-device-info.md index 15e04717e5e360bff9dcb9bbf9e97de030ab6a45..c452d6cc62b1a0e4f66c358c177ffc1e58f0d487 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-device-info.md +++ b/zh-cn/application-dev/reference/apis/js-apis-device-info.md @@ -29,7 +29,7 @@ import deviceInfo from '@ohos.deviceInfo' | softwareModel | string | 是 | 否 | 内部软件子型号。 | | hardwareModel | string | 是 | 否 | 硬件版本号。 | | hardwareProfile | string | 是 | 否 | 硬件Profile。 | -| serial | string | 是 | 否 | 设备序列号。
**需要权限**:ohos.permission.sec.ACCESS_UDID,该权限为系统权限 | +| serial | string | 是 | 否 | 设备序列号。
**需要权限**:ohos.permission.sec.ACCESS_UDID | | bootloaderVersion | string | 是 | 否 | Bootloader版本号。 | | abiList | string | 是 | 否 | 应用二进制接口(Abi)列表。 | | securityPatchTag | string | 是 | 否 | 安全补丁级别。 | @@ -49,4 +49,4 @@ import deviceInfo from '@ohos.deviceInfo' | buildHost | string | 是 | 否 | 构建主机。 | | buildTime | string | 是 | 否 | 构建时间。 | | buildRootHash | string | 是 | 否 | 构建版本Hash。 | -| udid7+ | string | 是 | 否 | 设备Udid。
**需要权限**:ohos.permission.sec.ACCESS_UDID,该权限为系统权限| +| udid7+ | string | 是 | 否 | 设备Udid。
**需要权限**:ohos.permission.sec.ACCESS_UDID| diff --git a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md index 73bec5e09525301cb9c639c6c6729cf1cacd97f3..befb737bed6c6630c514dd57286252ba8f78c768 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md @@ -78,6 +78,7 @@ createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager | deviceType | [DeviceType](#devicetype) | 是 | 设备类型。 | | networkId8+ | string | 是 | 设备网络标识。 | | range9+ | number | 是 | 发现设备的距离。 | +| authForm10+ | [AuthForm](#authform) | 是 | 设备认证类型 | ## DeviceType @@ -95,6 +96,18 @@ createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager | CAR | 0x83 | 车 | | UNKNOWN_TYPE | 0 | 未知设备 | +## AuthForm + +表示设备认证类型的枚举类。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.DistributedHardware.DeviceManager + +| 名称 | 值 | 说明 | +| ------------------- | ---- | --------------- | +| INVALID_TYPE | -1 | 设备没有认证 | +| PEER_TO_PEER | 0 | 无账号设备点对点认证 | +| IDENTICAL_ACCOUNT | 1 | 设备同账号认证 | +| ACROSS_ACCOUNT | 2 | 设备跨账号认证 | ## DeviceStateChangeAction diff --git a/zh-cn/application-dev/reference/apis/js-apis-display.md b/zh-cn/application-dev/reference/apis/js-apis-display.md index 971af855e30f098cc3baa450bf883e1d4bf201bd..8b73f026dcdc1864fcde3cc02707a890f3c39a9e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-display.md +++ b/zh-cn/application-dev/reference/apis/js-apis-display.md @@ -28,6 +28,19 @@ import display from '@ohos.display'; | STATE_VR | 5 | 表示显示设备为VR模式。| | STATE_ON_SUSPEND | 6 | 表示显示设备为开启状态,CPU为挂起状态。 | +## Orientation10+ + +显示设备当前显示的方向枚举。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| PORTRAIT | 0 | 表示设备当前以竖屏方式显示。| +| LANDSCAPE | 1 | 表示设备当前以横屏方式显示。 | +| PORTRAIT_INVERTED | 2 | 表示设备当前以反向竖屏方式显示。| +| LANDSCAPE_INVERTED | 3 | 表示设备当前以反向横屏方式显示。| + ## Rect9+ 矩形区域。 @@ -420,6 +433,7 @@ promise.then((data) => { | width | number | 是 | 否 | 显示设备的宽度,单位为像素。| | height | number | 是 | 否 | 显示设备的高度,单位为像素。| | densityDPI | number | 是 | 否 | 显示设备的屏幕密度,表示每英寸点数。一般取值160,480等。 | +| orientation10+ | [Orientation](#orientation10) | 是 | 否 | 表示屏幕当前显示的方向。 | | densityPixels | number | 是 | 否 | 显示设备的逻辑密度,是像素单位无关的缩放系数。一般取值1,3等。 | | scaledDensity | number | 是 | 否 | 显示设备的显示字体的缩放因子。通常与densityPixels相同。 | | xDPI | number | 是 | 否 | x方向中每英寸屏幕的确切物理像素值。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md new file mode 100644 index 0000000000000000000000000000000000000000..d497f07be910d4aeba6949dce61f4ac7b94e9cf6 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @@ -0,0 +1,101 @@ +# @ohos.enterprise.deviceControl (设备控制管理) + +本模块提供设备控制能力。仅企业设备管理员应用才能调用。 + +> **说明**: +> +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import deviceControl from '@ohos.enterprise.deviceControl' +``` + +## deviceControl.resetFactory + +resetFactory(admin: Want, callback: AsyncCallback): void + +恢复出厂设置。使用callback异步回调。 + +**需要权限:** ohos.permission.ENTERPRISE_RESET_DEVICE + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback\ | 是 | 回调函数。当系统时间设置成功err为null,否则为错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)。 + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +deviceControl.resetFactory(wantTemp, (error) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}) +``` + +## deviceControl.resetFactory + +resetFactory(admin: Want): Promise + +恢复出厂设置。使用Promise异步回调。 + +**需要权限:** ohos.permission.ENTERPRISE_RESET_DEVICE + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | + +**返回值:** + +| 类型 | 说明 | +| ----- | ----------------------------------- | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)。 + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**示例:** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +deviceControl.resetFactory(wantTemp).then(() => { +}).catch((error) => { + console.log("error code:" + error.code + " error message:" + error.message); +}) +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-http.md b/zh-cn/application-dev/reference/apis/js-apis-http.md index eaa385f4290563062b7512c7eb4115b91a9e932a..4bc6e949c95ee6ef216b4195bc92c64cfca0cf06 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-http.md +++ b/zh-cn/application-dev/reference/apis/js-apis-http.md @@ -103,6 +103,21 @@ request\(url: string, callback: AsyncCallback\\):void | url | string | 是 | 发起网络请求的URL地址。 | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300007 | Couldn't connect to server. | +| 2300028 | Timeout was reached. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300999 | Unknown Other Error. | + +>**错误码说明:** +> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-http.md)。 +> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) + **示例:** ```js @@ -136,6 +151,45 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**错误码说明:** +> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-http.md)。 +> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) + **示例:** ```js @@ -184,6 +238,44 @@ request\(url: string, options? : HttpRequestOptions\): Promise | :------------------------------------- | :-------------------------------- | | Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +|---------|-------------------------------------------------------| +| 401 | Parameter error. | +| 2300001 | Unsupported protocol. | +| 2300003 | URL using bad/illegal format or missing URL. | +| 2300005 | Couldn't resolve proxy name. | +| 2300006 | Couldn't resolve host name. | +| 2300007 | Couldn't connect to server. | +| 2300008 | Weird server reply. | +| 2300009 | Access denied to remote resource. | +| 2300016 | Error in the HTTP2 framing layer. | +| 2300018 | Transferred a partial file. | +| 2300023 | Failed writing received data to disk/application. | +| 2300025 | Upload failed. | +| 2300026 | Failed to open/read local data from file/application. | +| 2300027 | Out of memory. | +| 2300028 | Timeout was reached. | +| 2300047 | Number of redirects hit maximum amount. | +| 2300052 | Server returned nothing (no headers, no data). | +| 2300055 | Failed sending data to the peer. | +| 2300056 | Failure when receiving data from the peer. | +| 2300058 | Problem with the local SSL certificate. | +| 2300059 | Couldn't use specified SSL cipher. | +| 2300060 | SSL peer certificate or SSH remote key was not OK. | +| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| +| 2300063 | Maximum file size exceeded. | +| 2300070 | Disk full or allocation exceeded. | +| 2300073 | Remote file already exists. | +| 2300077 | Problem with the SSL CA cert (path? access rights?). | +| 2300078 | Remote file not found. | +| 2300094 | An authentication function returned an error. | +| 2300999 | Unknown Other Error. | + +>**错误码说明:** +> 以上错误码的详细介绍参见[HTTP错误码](../errorcodes/errorcode-http.md)。 +> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) **示例:** @@ -438,9 +530,9 @@ request方法回调函数的返回值类型。 | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | result | string \| Object \| ArrayBuffer6+ | 是 | HTTP请求根据响应头中Content-type类型返回对应的响应格式内容:
- application/json:返回JSON格式的字符串,如需HTTP响应具体内容,需开发者自行解析
- application/octet-stream:ArrayBuffer
- 其他:string | | resultType9+ | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 | -| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码)。 | +| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 | | header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:
- Content-Type:header['Content-Type'];
- Status-Line:header['Status-Line'];
- Date:header.Date/header['Date'];
- Server:header.Server/header['Server']; | -| cookies8+ | Array\ | 是 | 服务器返回的 cookies。 | +| cookies8+ | string | 是 | 服务器返回的 cookies。 | ## http.createHttpResponseCache9+ @@ -572,17 +664,6 @@ httpResponseCache.delete().then(() => { }); ``` -## Response常用错误码 - -| 错误码 | 说明 | -| ------ | ------------------------------------------------------------ | -| -1 | 参数错误。检查参数的个数与类型是否正确。 | -| 3 | URL格式错误。检查URL的格式与语法是否正确。 | -| 4 | 构建时无法找到内置的请求功能、协议或选项。一个功能或选项是不启用或明确禁用时,为了得到它的功能,你需要得到一个重建的libcurl。 | -| 5 | 无法解析代理,指定的代理服务器主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。 | -| 6 | 无法解析主机,指定的远程主机无法解析。建议排查:1、url地址是否正确。2、联网是否正常,网络是否可以和外部进行通信。3、是否有网络访问权限。 | -| 7 | 无法连接代理或主机。建议排查:1、端口号是否有问题。 2、查看本地是否开启http的代理影响的。 | - ## HttpDataType9+ http的数据类型。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 24eb8fc7be651d7ecf925e2ed22e00559769766d..5a632ee11780e5b965e5f8cccea3e6b65b979c44 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -35,10 +35,10 @@ openFile(uri: string, mode: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rw"; +let mode = "rw"; DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -69,10 +69,10 @@ openFile(uri: string, mode: string): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rw"; +let mode = "rw"; DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { console.info("openFile data: " + JSON.stringify(data)); }); @@ -98,7 +98,7 @@ on(type: 'dataChange', uri: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { @@ -131,7 +131,7 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { @@ -167,7 +167,7 @@ getType(uri: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { @@ -199,7 +199,7 @@ getType(uri: string): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { @@ -227,7 +227,7 @@ getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback { @@ -260,7 +260,7 @@ getFileTypes(uri: string, mimeTypeFilter: string): Promise\> ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { @@ -287,7 +287,7 @@ normalizeUri(uri: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { @@ -319,7 +319,7 @@ normalizeUri(uri: string): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { @@ -346,7 +346,7 @@ denormalizeUri(uri: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { @@ -378,7 +378,7 @@ denormalizeUri(uri: string): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { @@ -405,7 +405,7 @@ notifyChange(uri: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { @@ -437,7 +437,7 @@ notifyChange(uri: string): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => { @@ -465,7 +465,7 @@ insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); const valueBucket = { @@ -538,10 +538,10 @@ batchInsert(uri: string, valuesBuckets: Array\, callback: Asyn ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, +let cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => { @@ -574,10 +574,10 @@ batchInsert(uri: string, valuesBuckets: Array): Promise\ { @@ -606,7 +606,7 @@ delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: Asy ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); let da = new ohos_data_ability.DataAbilityPredicates(); @@ -641,7 +641,7 @@ delete(uri: string, predicates?: dataAbility.DataAbilityPredicates): Promise\, predicates: dataAbility.DataAbilityP ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var cars=new Array("value1", "value2", "value3", "value4"); +let cars=new Array("value1", "value2", "value3", "value4"); let da = new ohos_data_ability.DataAbilityPredicates(); DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => { console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); @@ -790,10 +790,10 @@ query(uri: string, columns?: Array\, predicates?: dataAbility.DataAbilit ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( +let DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var cars = new Array("value1", "value2", "value3", "value4"); +let cars = new Array("value1", "value2", "value3", "value4"); let da = new ohos_data_ability.DataAbilityPredicates(); DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => { console.info("query data: " + JSON.stringify(data)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-app-context.md b/zh-cn/application-dev/reference/apis/js-apis-inner-app-context.md index 509d227c4a0ece66eeef92422eb9ecb36ef440c8..7a35c79c2345d91336e17da78a597d0e9031a614 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-app-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-app-context.md @@ -13,7 +13,7 @@ Context对象是在featureAbility中创建实例,并通过featureAbility的[ge ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); }); @@ -39,7 +39,7 @@ getOrCreateLocalDir(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateLocalDir((err, data)=>{ console.info("getOrCreateLocalDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -67,7 +67,7 @@ getOrCreateLocalDir(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); }); @@ -94,7 +94,7 @@ verifyPermission(permission: string, options: PermissionOptions, callback: Async ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle.bundleManager'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); @@ -124,7 +124,7 @@ verifyPermission(permission: string, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.verifyPermission("com.example.permission", (err, data) =>{ console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -155,8 +155,8 @@ verifyPermission(permission: string, options?: PermissionOptions): Promise\ { console.info("verifyPermission data: " + JSON.stringify(data)); }); @@ -184,7 +184,7 @@ requestPermissionsFromUser(permissions: Array\, requestCode: number, res ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.requestPermissionsFromUser( ["com.example.permission1", "com.example.permission2", @@ -224,7 +224,7 @@ requestPermissionsFromUser(permissions: Array\, requestCode: number): Pr ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.requestPermissionsFromUser( ["com.example.permission1", "com.example.permission2", @@ -257,7 +257,7 @@ getApplicationInfo(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getApplicationInfo((err, data) => { console.info("getApplicationInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -283,7 +283,7 @@ getApplicationInfo(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getApplicationInfo().then((data) => { console.info("getApplicationInfo data: " + JSON.stringify(data)); }); @@ -309,7 +309,7 @@ getBundleName(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getBundleName((err, data) => { console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -335,7 +335,7 @@ getBundleName(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getBundleName().then((data) => { console.info("getBundleName data: " + JSON.stringify(data)); }); @@ -359,7 +359,7 @@ getDisplayOrientation(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getDisplayOrientation((err, data) => { console.info("getDisplayOrientation err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -383,7 +383,7 @@ getDisplayOrientation(): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getDisplayOrientation().then((data) => { console.info("getDisplayOrientation data: " + JSON.stringify(data)); }); @@ -407,7 +407,7 @@ getExternalCacheDir(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getExternalCacheDir((err, data) => { console.info("getExternalCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -431,7 +431,7 @@ getExternalCacheDir(): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getExternalCacheDir().then((data) => { console.info("getExternalCacheDir data: " + JSON.stringify(data)); }); @@ -457,8 +457,8 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCal ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -var context = featureAbility.getContext(); -var orientation = bundle.DisplayOrientation.UNSPECIFIED; +let context = featureAbility.getContext(); +let orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation, (err) => { console.info("setDisplayOrientation err: " + JSON.stringify(err)); }); @@ -484,8 +484,8 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -var context = featureAbility.getContext(); -var orientation = bundle.DisplayOrientation.UNSPECIFIED; +let context = featureAbility.getContext(); +let orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation).then((data) => { console.info("setDisplayOrientation data: " + JSON.stringify(data)); }); @@ -510,8 +510,8 @@ setShowOnLockScreen(show: boolean, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var show = true; +let context = featureAbility.getContext(); +let show = true; context.setShowOnLockScreen(show, (err) => { console.info("setShowOnLockScreen err: " + JSON.stringify(err)); }); @@ -541,8 +541,8 @@ setShowOnLockScreen(show: boolean): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var show = true; +let context = featureAbility.getContext(); +let show = true; context.setShowOnLockScreen(show).then((data) => { console.info("setShowOnLockScreen data: " + JSON.stringify(data)); }); @@ -567,8 +567,8 @@ setWakeUpScreen(wakeUp: boolean, callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var wakeUp = true; +let context = featureAbility.getContext(); +let wakeUp = true; context.setWakeUpScreen(wakeUp, (err) => { console.info("setWakeUpScreen err: " + JSON.stringify(err)); }); @@ -598,8 +598,8 @@ setWakeUpScreen(wakeUp: boolean): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var wakeUp = true; +let context = featureAbility.getContext(); +let wakeUp = true; context.setWakeUpScreen(wakeUp).then((data) => { console.info("setWakeUpScreen data: " + JSON.stringify(data)); }); @@ -626,7 +626,7 @@ getProcessInfo(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo((err, data) => { console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -652,7 +652,7 @@ getProcessInfo(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo().then((data) => { console.info("getProcessInfo data: " + JSON.stringify(data)); }); @@ -680,7 +680,7 @@ getElementName(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getElementName((err, data) => { console.info("getElementName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -708,7 +708,7 @@ getElementName(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getElementName().then((data) => { console.info("getElementName data: " + JSON.stringify(data)); }); @@ -732,7 +732,7 @@ getProcessName(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessName((err, data) => { console.info("getProcessName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -758,7 +758,7 @@ getProcessName(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessName().then((data) => { console.info("getProcessName data: " + JSON.stringify(data)); }); @@ -784,7 +784,7 @@ getCallingBundle(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCallingBundle((err, data) => { console.info("getCallingBundle err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -810,7 +810,7 @@ getCallingBundle(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCallingBundle().then((data) => { console.info("getCallingBundle data: " + JSON.stringify(data)); }); @@ -834,7 +834,7 @@ getCacheDir(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCacheDir((err, data) => { console.info("getCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -858,7 +858,7 @@ getCacheDir(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCacheDir().then((data) => { console.info("getCacheDir data: " + JSON.stringify(data)); }); @@ -882,7 +882,7 @@ getFilesDir(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getFilesDir((err, data) => { console.info("getFilesDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -906,7 +906,7 @@ getFilesDir(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getFilesDir().then((data) => { console.info("getFilesDir data: " + JSON.stringify(data)); }); @@ -932,7 +932,7 @@ getOrCreateDistributedDir(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateDistributedDir((err, data) => { console.info("getOrCreateDistributedDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -958,7 +958,7 @@ getOrCreateDistributedDir(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateDistributedDir().then((data) => { console.info("getOrCreateDistributedDir data: " + JSON.stringify(data)); }); @@ -982,7 +982,7 @@ getAppType(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppType((err, data) => { console.info("getAppType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -1006,7 +1006,7 @@ getAppType(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppType().then((data) => { console.info("getAppType data: " + JSON.stringify(data)); }); @@ -1030,7 +1030,7 @@ getHapModuleInfo(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getHapModuleInfo((err, data) => { console.info("getHapModuleInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -1054,7 +1054,7 @@ getHapModuleInfo(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getHapModuleInfo().then((data) => { console.info("getHapModuleInfo data: " + JSON.stringify(data)); }); @@ -1078,7 +1078,7 @@ getAppVersionInfo(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppVersionInfo((err, data) => { console.info("getAppVersionInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -1102,7 +1102,7 @@ getAppVersionInfo(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppVersionInfo().then((data) => { console.info("getAppVersionInfo data: " + JSON.stringify(data)); }); @@ -1126,7 +1126,7 @@ getAbilityInfo(callback: AsyncCallback\): void ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAbilityInfo((err, data) => { console.info("getAbilityInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -1150,7 +1150,7 @@ getAbilityInfo(): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAbilityInfo().then((data) => { console.info("getAbilityInfo data: " + JSON.stringify(data)); }); @@ -1174,7 +1174,7 @@ getApplicationContext(): Context ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext().getApplicationContext(); +let context = featureAbility.getContext().getApplicationContext(); ``` ## Context.isUpdatingConfigurations7+ @@ -1195,7 +1195,7 @@ isUpdatingConfigurations(callback: AsyncCallback\): void; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.isUpdatingConfigurations((err, data) => { console.info("isUpdatingConfigurations err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); @@ -1219,7 +1219,7 @@ isUpdatingConfigurations(): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.isUpdatingConfigurations().then((data) => { console.info("isUpdatingConfigurations data: " + JSON.stringify(data)); }); @@ -1243,7 +1243,7 @@ printDrawnCompleted(callback: AsyncCallback\): void; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.printDrawnCompleted((err) => { console.error('printDrawnCompleted err: ' + JSON.stringify(err)); }); @@ -1267,7 +1267,7 @@ printDrawnCompleted(): Promise\; ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.printDrawnCompleted().then((data) => { console.info("printDrawnCompleted data: " + JSON.stringify(data)); }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md index 13053095ec4607da64923e7427d4369e43db0df1..48f54e84fb3bcc274649ab1be9bc1527e62a4326 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -17,7 +17,7 @@ ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo((err, data) => { if (err.code != 0) { console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index 0913bdd260950f4039b5ce52869d0b5bf14ad46e..a8b15e26993ee71e2516410df96b22408855eee4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -28,5 +28,5 @@ AbilityDelegatorArgs模块提供在应用程序执行测试用例期间,获取 ```ts import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; -var args = AbilityDelegatorRegistry.getArguments(); +let args = AbilityDelegatorRegistry.getArguments(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md index 7bd8dd4411a14448a3a9539c59e513aa82abe076..fa41b00fd9bea92058f7be3e26db61b923652840 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -36,12 +36,12 @@ function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor, (err : any) => { console.info("addAbilityMonitor callback"); }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index 41dc3d57e5bd6782f1f8a2e32d27a6ddb41ab46e..e03b28ec9d958d242c123563cf55a009a077dcf1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -41,7 +41,7 @@ on(type: "abilityLifecycle", callback: AbilityLifecycleCallback): **number**; ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var lifecycleId; +let lifecycleId; export default class EntryAbility extends UIAbility { onCreate() { @@ -109,7 +109,7 @@ off(type: "abilityLifecycle", callbackId: **number**, callback: AsyncCallback<* ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var lifecycleId; +let lifecycleId; export default class EntryAbility extends UIAbility { onDestroy() { @@ -142,7 +142,7 @@ off(type: "abilityLifecycle", callbackId: **number**): **void**; ```ts import Ability from "@ohos.app.ability.UIAbility"; -var lifecycleId; +let lifecycleId; export default class MyAbility extends Ability { onDestroy() { @@ -179,7 +179,7 @@ on(type: "environment", callback: EnvironmentCallback): **number**; ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onCreate() { @@ -223,7 +223,7 @@ off(type: "environment", callbackId: **number**, callback: AsyncCallback<**void ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onDestroy() { @@ -255,7 +255,7 @@ off(type: "environment", callbackId: **number**, callback: AsyncCallback<**void ```ts import Ability from "@ohos.app.ability.UIAbility"; -var callbackId; +let callbackId; export default class MyAbility extends Ability { onDestroy() { @@ -325,9 +325,9 @@ applicationContext.getProcessRunningInformation((err, data) => { }) ``` -## ApplicationContext.killProcessesBySelf9+ +## ApplicationContext.killAllProcesses9+ -killProcessesBySelf(): Promise; +killAllProcesses(): Promise\; 杀死应用所在的进程。 @@ -337,22 +337,18 @@ killProcessesBySelf(): Promise; | 类型 | 说明 | | -------- | -------- | -| Promise\> | 以Promise方式返回杀死应用所在的进程结果。 | +| Promise\ | 以Promise方式返回杀死应用所在的进程结果。 | **示例:** ```ts let applicationContext = this.context.getApplicationContext(); -applicationContext.killProcessesBySelf().then((data) => { - console.log("The process running information is:" + JSON.stringify(data)); -}).catch((error) => { - console.error("error:" + JSON.stringify(error)); -}); +applicationContext.killAllProcesses() ``` -## ApplicationContext.killProcessesBySelf9+ +## ApplicationContext.killAllProcesses9+ -killProcessesBySelf(callback: AsyncCallback); +killAllProcesses(callback: AsyncCallback\); 杀死应用所在的进程。 @@ -362,15 +358,13 @@ killProcessesBySelf(callback: AsyncCallback); | 类型 | 说明 | | -------- | -------- | -|AsyncCallback\ | 以callback方式返回杀死应用所在的进程结果。 | +|AsyncCallback\ | 以callback方式返回杀死应用所在的进程结果。 | **示例:** ```ts let applicationContext = this.context.getApplicationContext(); -applicationContext.killProcessesBySelf(err => { - if (err.code !== 0) { - console.error("killProcessesBySelf faile, err: " + JSON.stringify(err)); - } +applicationContext.killAllProcesses(err => { + console.error("killAllProcesses result: " + JSON.stringify(err)); }) ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md index c2f6b786eea4594a65731753f2513efa7d493e55..d5dca1bf8a94fa284d7dd4cf47c5856436b8ce13 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-context.md @@ -23,7 +23,7 @@ Context模块提供了ability或application的上下文的能力,包括访问 | bundleCodeDir | string | 是 | 否 | 安装包目录。 | | distributedFilesDir | string | 是 | 否 | 分布式文件目录。 | | eventHub | [EventHub](js-apis-inner-application-eventHub.md) | 是 | 否 | 事件中心,提供订阅、取消订阅、触发事件对象。 | -| area | [AreaMode](#areamode) | 是 | 否 | 文件分区信息。 | +| area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | 是 | 否 | 文件分区信息。 | ## Context.createBundleContext @@ -172,13 +172,3 @@ try { } ``` -## AreaMode - -文件分区 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| EL1 | 0 | 设备级加密区,设备开机后可访问的数据区。 | -| EL2 | 1 | 用户级加密区,设备开机,首次输入密码后才能够访问的数据区。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index f45abf105bdaa9d18ffd2ee8b07405a44204249a..dc559a56448e8ced24f37a5939c5f65997bbcaef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -90,7 +90,7 @@ export default class ServiceModel { return; } - var moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; + let moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; this.moduleName = moduleInfo.name; // 根据moduleName执行不同的业务逻辑,实现对不同性能设备的区分 switch (this.moduleName) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md index 13e4ce5df6b37cb85cf82fd9e7e9841c3dca9fc1..4d9e0ab0999147dacc1aa6c459d92d106108f7ff 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -29,7 +29,7 @@ ExtensionRunningInfo模块封装了Extension运行的相关信息,可以通过 ```ts import abilityManager from '@ohos.app.ability.abilityManager' -var upperLimit = 1; +let upperLimit = 1; function getExtensionInfos() { abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { if (error && error.code) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index 2310755f6bc2fd5ac0720e75060152ce6b050588..430fda3c1172ecd6076ed15a32c35def4661780e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -33,7 +33,7 @@ } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + let id = missions[0].missionId; missionManager.getMissionSnapShot("", id, (err, snapshot) => { if (err.code) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index d59f2a3549016e385b674bcb74e34c151cdbd9b4..621d6e03bee8e8b037f10497e82d01e18e31f87b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -68,7 +68,7 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapp", abilityName: "MyAbility" }; @@ -141,11 +141,11 @@ startAbility(want: Want, options?: StartOptions): Promise\; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapp", abilityName: "MyAbility" }; - var options = { + let options = { windowMode: 0, }; @@ -212,12 +212,12 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var options = { + let options = { windowMode: 0 }; @@ -290,12 +290,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -367,13 +367,13 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -453,13 +453,13 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -518,7 +518,7 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -584,7 +584,7 @@ startServiceExtensionAbility(want: Want): Promise\; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -650,12 +650,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -721,12 +721,12 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId) @@ -780,7 +780,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -843,7 +843,7 @@ stopServiceExtensionAbility(want: Want): Promise\; **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" @@ -905,12 +905,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -973,12 +973,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId) @@ -1118,17 +1118,17 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; **示例:** ```ts - var want = { + let want = { bundleName: "com.example.myapp", abilityName: "MyAbility" }; - var options = { + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { @@ -1178,19 +1178,19 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options **示例:** ```ts - var want = { + let want = { deviceId: "", bundleName: "com.example.myapplication", abilityName: "EntryAbility" }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { @@ -1232,7 +1232,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback< ```ts // connection为connectServiceExtensionAbility中的返回值 - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection, (error) => { @@ -1289,7 +1289,7 @@ disconnectServiceExtensionAbility(connection: number): Promise<void>; ```ts // connection为connectServiceExtensionAbility中的返回值 - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection) @@ -1355,10 +1355,10 @@ startAbilityByCall(want: Want): Promise<Caller>; 后台启动: ```ts - var caller = undefined; + let caller = undefined; // 后台启动Ability,不配置parameters - var wantBackground = { + let wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "EntryAbility", @@ -1386,10 +1386,10 @@ startAbilityByCall(want: Want): Promise<Caller>; 前台启动: ```ts - var caller = undefined; + let caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true - var wantForeground = { + let wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "EntryAbility", diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 3795cea282673dc5feada8c9183114809b5d2669..3f0c8ff804d172a393f331f7e88f4db375f5f332 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -230,7 +230,10 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(callback形式)。 +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -295,7 +298,10 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(callback形式)。 +启动一个Ability。Ability被启动后,有如下情况(callback形式): + - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -365,7 +371,10 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -启动一个Ability。Ability被启动后,正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用者。异常情况下比如杀死Ability会返回异常信息给调用者(promise形式)。 +启动一个Ability。Ability被启动后,有如下情况(promise形式): + - 正常情况下可通过调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止并且返回结果给调用方。 + - 异常情况下比如杀死Ability会返回异常信息给调用方, 异常信息中resultCode为-1。 + - 如果被启动的Ability模式是单实例模式, 不同应用多次调用该接口启动这个Ability,当这个Ability调用[terminateSelfWithResult](#uiabilitycontextterminateselfwithresult)接口使之终止时,只将正常结果返回给最后一个调用方, 其它调用方返回异常信息, 异常信息中resultCode为-1。 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 @@ -1584,8 +1593,6 @@ startAbilityByCall(want: Want): Promise<Caller>; **系统能力**:SystemCapability.Ability.AbilityRuntime.Core -**系统API**: 此接口为系统接口,三方应用不支持调用。 - **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2123,3 +2130,105 @@ isTerminating(): boolean; let isTerminating = this.context.isTerminating(); console.log('ability state :' + isTerminating); ``` + +## UIAbilityContext.requestDialogService + +requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestResult>): void; + +启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限。 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限。 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 | +| result | AsyncCallback<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | 是 | 执行结果回调函数。 | + +**示例:** + + ```ts + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + let want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "AuthAccountServiceExtension" + }; + + try { + this.context.requestDialogService(want, (error, result) => { + if (error && error.code) { + // 处理业务逻辑错误 + console.log('requestDialogService failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("requestDialogService succeed, result = " + JSON.stringify(result)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('requestDialogService failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + ## UIAbilityContext.requestDialogService + +requestDialogService(want: Want): Promise<dialogRequest.RequestResult>; + +启动一个支持模态弹框的ServiceExtensionAbility。ServiceExtensionAbility被启动后,应用弹出模态弹框,通过调用[setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult)接口返回结果给调用者(promise形式)。 + +使用规则: + - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限。 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限。 + - 组件启动规则详见:[组件启动规则(Stage模型)](../../application-models/component-startup-rules.md)。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Promise形式返回执行结果。 + +**示例:** + + ```ts +import dialogRequest from '@ohos.app.ability.dialogRequest'; + +let want = { + bundleName: "com.example.myapplication", + abilityName: "AuthAccountServiceExtension" +}; + +try { + this.context.requestDialogService(want) + .then((result) => { + // 执行正常业务 + console.log("requestDialogService succeed, result = " + JSON.stringify(result)); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('requestDialogService failed, error= ' + JSON.stringify(error)); + }); +} catch (paramError) { + // 处理入参错误异常 + console.log('requestDialogService failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} + ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..78e9566b0e4effc0f54e7c727b7963f89fab10fa --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @@ -0,0 +1,123 @@ +# WindowExtensionContext + +WindowExtensionContext模块是WindowExtensionAbility的上下文环境,继承自[ExtensionContext](js-apis-inner-application-extensionContext.md)。 + +WindowExtensionContext模块提供[WindowExtensionAbility](js-apis-application-windowExtensionAbility.md)具有的能力,包括启动Ability。 + +> **说明:** +> +> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> - 本模块接口为系统接口。 +> +> - 本模块接口仅可在Stage模型下使用。 + +## 使用说明 + +在使用WindowExtensionContext的功能前,需要通过WindowExtensionAbility子类实例获取。 + +```ts + import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; + + let context = undefined; + class WindowExtAbility extends WindowExtensionAbility { + onConnect() { + context = this.context; // 获取WindowExtensionContext + } + } +``` + +## WindowExtensionContext.startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void + +启动Ability,使用callback异步回调。 + +**系统能力**:SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | +| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | + +**示例:** + + ```ts + var want = { + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var options = { + windowMode: 102 + }; + + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.error('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## WindowExtensionContext.startAbility + +startAbility(want: Want, options?: StartOptions): Promise\ + +启动Ability,使用Promise异步回调。 + +**系统能力**:SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如Ability名称,Bundle名称等。 | +| options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MainAbility" + }; + var options = { + windowMode: 102, + }; + + try { + this.context.startAbility(want, options) + .then((data) => { + // 执行正常业务 + console.log('startAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.error('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-InputMethodCommon.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-InputMethodCommon.md new file mode 100644 index 0000000000000000000000000000000000000000..325d2f7aca6ddf2f093409faa8ac96e6c9bf84fd --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-InputMethodCommon.md @@ -0,0 +1,41 @@ +# InputMethodCommon + +> **说明:** +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +输入法框架接口定义的公共属性信息。 + +## Direction + +光标移动方向类型枚举。 + + **系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 值 | 说明 | +| ------------ | ---- | ---------- | +| CURSOR_UP | 1 | 光标上移。 | +| CURSOR_DOWN | 2 | 光标下移。 | +| CURSOR_LEFT | 3 | 光标左移。 | +| CURSOR_RIGHT | 4 | 光标右移。 | + +## Range + +描述选中文本的范围。 + + **系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | ---------------------------------- | +| start | number | 是 | 是 | 选中文本的首字符在编辑框的索引值。 | +| end | number | 是 | 是 | 选中文本的末字符在编辑框的索引值。 | + +## Movement + +描述进行选中文本动作时光标移动的方向。 + + **系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ----------------------- | ---- | ---- | ---------------------------------- | +| direction | [Direction](#direction) | 是 | 是 | 进行选中文本动作时光标移动的方向。 | + diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md index 25bc2f7229a365c222303352657433ca22f2b65c..454e533f1ee846fd3105c038cf69b98719578d7a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @@ -839,6 +839,92 @@ inputMethodController.stopInput().then((result) => { }) ``` +### on('selectByRange')10+ + +on(type: 'selectByRange', callback: Callback<Range>): void + +订阅输入法应用按范围选中文本事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘selectByRange’时表示订阅输入法应用按范围选中文本事件监听。 | +| callback | Callback<[Range](./js-apis-inputmethod-InputMethodCommon.md#range)> | 是 | 回调函数,返回需要选中的文本的范围。
开发者需要在回调函数中根据传入的范围选中编辑框中相应文本。 | + +**示例:** + +```js +inputMethodController.on('selectByRange', (range) => { + console.info('Succeeded in subscribing selectByRange: start: ' + range.start + " , end: " + range.end); +}); +``` + +### off('selectByRange')10+ + +off(type: 'selectByRange'): void + +取消订阅输入法应用按范围选中文本事件。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘selectByRange’时表示取消订阅输入法应用按范围选中文本事件监听。 | + +**示例:** + +```js +inputMethodController.off('selectByRange'); +``` + +### on('selectByMovement')10+ + +on(type: 'selectByMovement', callback: Callback<Range>): void + +订阅输入法应用按光标动作选中文本事件。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘selectByMovement’时表示订阅输入法应用按光标移动动作选中文本事件监听。 | +| callback | Callback<[Movement](./js-apis-inputmethod-InputMethodCommon.md#movement)> | 是 | 回调函数,返回需要选中的文本的范围。
开发者需要在回调函数中根据传入的光标动作选中编辑框中相应文本。 | + +**示例:** + +```js +inputMethodController.on('selectByMovement', (movement) => { + console.info('Succeeded in subscribing selectByMovement: direction: ' + movement.direction); +}); +``` + +### off('selectByMovement')10+ + +off(type: 'selectByMovement'): void + +取消订阅输入法应用按光标动作选中文本事件。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 设置监听类型。
-type为‘selectByMovement’时表示取消订阅输入法应用按范围选中文本事件监听。 | + +**示例:** + +```js +inputMethodController.off('selectByMovement'); +``` + ## InputMethodSetting8+ 下列API示例中都需使用[getSetting](#inputmethodgetsetting9)获取到InputMethodSetting实例,再通过此实例调用对应方法。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md index 72f116c900e3921315385e2dab0d54dd277e6bec..551562a61c610c300fc0c789ebd47b16a5f6dff9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1495,6 +1495,241 @@ try { } ``` +### selectByRange10+ + +selectByRange(range: Range, callback: AsyncCallback<void>): void + +根据索引范围选中文本。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| range | [Range](./js-apis-inputmethod-InputMethodCommon.md#range) | 是 | 选中文本的范围。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当成功发送选中事件后,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +try { + inputClient.selectByRange({start: 0, end: 1}, (err) => { + if (err !== undefined) { + console.error('Failed to selectByRange: ${err.message}'); + return; + } + console.info('Succeeded in selecting by range.'); + }); +} catch (err) { + console.error('Failed to selectByRange: ${err.message}'); +} +``` + +### selectByRange10+ + +selectByRange(range: Range): Promise<void> + +根据索引范围选中文本。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------------------------------------------------------- | ---- | ---------------- | +| range | [Range](./js-apis-inputmethod-InputMethodCommon.md#range) | 是 | 选中文本的范围。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +try { + inputClient.selectByRange({start: 0, end:1}).then(() => { + console.log('Succeeded in selecting by range.'); + }).catch((err) => { + console.error('Failed to selectByRange: ${err.message}'); + }); +} catch (err) { + console.log('Failed to selectByRange: ${err.message}'); +} +``` + +### selectByMovement10+ + +selectByMovement(movement: Movement, callback: AsyncCallback<void>): void + +根据光标移动方向选中文本。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| movement | [Movement](./js-apis-inputmethod-InputMethodCommon.md#movement) | 是 | 选中时光标移动的方向。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当成功发送选中事件后,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +try { + inputClient.selectByMovement({direction: 1}, (err) => { + if (err !== undefined) { + console.error('Failed to selectByMovement: ${err.message}'); + return; + } + console.info('Succeeded in selecting by movement.'); + }); +} catch (err) { + console.error('Failed to selectByMovement: ${err.message}'); +} +``` + +### selectByMovement10+ + +selectByMovement(range: Range): Promise<void> + +根据索引范围选中文本。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| movement | [Movement](./js-apis-inputmethod-InputMethodCommon.md#movement) | 是 | 选中时光标移动的方向。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**示例:** + +```js +try { + inputClient.selectByMovement({direction: 1}).then(() => { + console.log('Succeeded in selecting by movement.'); + }).catch((err) => { + console.error('Failed to selectByMovement: ${err.message}'); + }); +} catch (err) { + console.log('Failed to selectByMovement: ${err.message}'); +} +``` + +### getTextIndexAtCursor10+ + +getTextIndexAtCursor(callback: AsyncCallback<number>): void + +获取光标所在处的文本索引。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | 是 | 回调函数。当文本索引获取成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 401 | parameter error. | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** + +```js +inputClient.getTextIndexAtCursor((err, index) => { + if (err !== undefined) { + console.error('Failed to getTextIndexAtCursor: ${err.message}'); + return; + } + console.info('Succeeded in getTextIndexAtCursor: ' + index); +}); +``` + +### getTextIndexAtCursor10+ + +getTextIndexAtCursor(): Promise<number> + +获取光标所在处的文本索引。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------------------------- | +| Promise<number> | Promise对象,返回光标所在处的文本索引。 | + +**错误码:** + +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**示例:** + +```js +inputClient.getTextIndexAtCursor().then((index) => { + console.info('Succeeded in getTextIndexAtCursor: ' + index); +}).catch((err) => { + console.error('Failed to getTextIndexAtCursor: ${err.message}'); +}); +``` + ## EditorAttribute 编辑框属性值。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index 4571be9d7ba6db66e689b23c4fc96d01b8722ee6..f77b0245cac97512dbd2a9a227a29faa4f2ae890 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -118,14 +118,14 @@ media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { console.error('Failed to get first object: ' + err); return; } - console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); for (let i = 1; i < count; i++) { fetchFileResult.getNextObject((err, fileAsset) => { if (fileAsset == undefined) { console.error('Failed to get next object: ' + err); return; } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); }) } }); @@ -174,10 +174,10 @@ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { } console.info('Get fetchFileResult success, count: ' + count); fetchFileResult.getFirstObject().then(function(fileAsset) { - console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); for (let i = 1; i < count; i++) { fetchFileResult.getNextObject().then(function(fileAsset) { - console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); }).catch(function(err) { console.error('Failed to get next object: ' + err); }) @@ -264,9 +264,9 @@ async function example() { const path = await media.getPublicDirectory(DIR_IMAGE); media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => { if (fileAsset != undefined) { - console.info('createAsset successfully, message = ' + err); + console.info('createAsset successfully, message'); } else { - console.info('createAsset failed, message = ' + err); + console.error('createAsset failed, message = ' + err); } }); } @@ -307,7 +307,7 @@ async function example() { media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); }).catch((err) => { - console.info('createAsset failed, message = ' + err); + console.error('createAsset failed, message = ' + err); }); } ``` @@ -354,7 +354,7 @@ async function example() { media.deleteAsset(asset.uri).then(() => { console.info("deleteAsset successfully"); }).catch((err) => { - console.info("deleteAsset failed with error:"+ err); + console.error("deleteAsset failed with error:"+ err); }); } ``` @@ -397,7 +397,7 @@ async function example() { if (err != undefined) { console.info("deleteAsset successfully"); } else { - console.info("deleteAsset failed with error:"+ err); + console.error("deleteAsset failed with error:"+ err); } }); } @@ -426,7 +426,7 @@ media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { if (dicResult == 'Camera/') { console.info('mediaLibraryTest : getPublicDirectory passed'); } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); + console.error('mediaLibraryTest : getPublicDirectory failed'); } }); ``` @@ -460,7 +460,7 @@ async function example() { if (dicResult == 'Camera/') { console.info('MediaLibraryTest : getPublicDirectory'); } else { - console.info('MediaLibraryTest : getPublicDirectory failed'); + console.error('MediaLibraryTest : getPublicDirectory failed'); } } ``` @@ -495,7 +495,7 @@ media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { console.info('album.albumName = ' + album.albumName); console.info('album.count = ' + album.count); } else { - console.info('getAlbum fail, message = ' + err); + console.error('getAlbum fail, message = ' + err); } }) ``` @@ -532,7 +532,7 @@ let AlbumNoArgsfetchOp = { media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ console.info("getAlbums successfully:"+ JSON.stringify(albumList)); }).catch(function(err){ - console.info("getAlbums failed with error:"+ err); + console.error("getAlbums failed with error: " + err); }); ``` @@ -607,10 +607,10 @@ let option = { }; mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { if (err) { - console.log("An error occurred when storing media resources."); + console.error("An error occurred when storing media resources."); return; } - console.log("Media resources stored. "); + console.info("Media resources stored. "); // Obtain the URI that stores media resources. }); ``` @@ -647,10 +647,10 @@ let option = { relativePath : "Pictures/" }; mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { - console.log("Media resources stored."); + console.info("Media resources stored."); // Obtain the URI that stores media resources. }).catch((err) => { - console.log("An error occurred when storing media resources."); + console.error("An error occurred when storing media resources."); }); ``` @@ -689,10 +689,10 @@ let images = [ let index = 1; mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { if (err) { - console.log("An error occurred when previewing the images."); + console.error("An error occurred when previewing the images."); return; } - console.log("Succeeded in previewing the images."); + console.info("Succeeded in previewing the images."); }); ``` @@ -729,10 +729,10 @@ let images = [ */ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { if (err) { - console.log("An error occurred when previewing the images."); + console.error("An error occurred when previewing the images."); return; } - console.log("Succeeded in previewing the images."); + console.info("Succeeded in previewing the images."); }); ``` @@ -775,9 +775,9 @@ let images = [ */ let index = 1; mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { - console.log("Succeeded in previewing the images."); + console.info("Succeeded in previewing the images."); }).catch((err) => { - console.log("An error occurred when previewing the images."); + console.error("An error occurred when previewing the images."); }); ``` @@ -808,10 +808,10 @@ let option : mediaLibrary.MediaSelectOption = { }; mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { if (err) { - console.log("An error occurred when selecting media resources."); + console.error("An error occurred when selecting media resources."); return; } - console.log("Media resources selected."); + console.info("Media resources selected."); // Obtain the media selection value. }); ``` @@ -847,10 +847,10 @@ let option : mediaLibrary.MediaSelectOption = { count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { - console.log("Media resources selected."); + console.info("Media resources selected."); // Obtain the media selection value. }).catch((err) => { - console.log("An error occurred when selecting media resources."); + console.error("An error occurred when selecting media resources."); }); ``` @@ -885,7 +885,7 @@ async function example() { console.info('get distributed info is undefined!') } }).catch((err) => { - console.info("get distributed info failed with error:" + err); + console.error("get distributed info failed with error:" + err); }); } ``` @@ -918,7 +918,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail, message = ' + err) + console.error('get distributed fail, message = ' + err) } }) } @@ -956,7 +956,7 @@ async function example() { console.info('get distributed info is undefined!') } }).catch((err) => { - console.info("get distributed info failed with error:" + err); + console.error("get distributed info failed with error: " + err); }); } ``` @@ -989,7 +989,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail, message = ' + err) + console.error('get distributed fail, message = ' + err) } }) } @@ -1019,7 +1019,7 @@ async function example() { | parent8+ | number | 是 | 否 | 父目录id | | size | number | 是 | 否 | 文件大小(单位:字节) | | dateAdded | number | 是 | 否 | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| dateModified | number | 是 | 否 | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| dateModified | number | 是 | 否 | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新)| | dateTaken | number | 是 | 否 | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) | | artist8+ | string | 是 | 否 | 作者 | | audioAlbum8+ | string | 是 | 否 | 专辑 | @@ -1101,7 +1101,7 @@ async function example() { asset.isDirectory().then(function(isDirectory){ console.info("isDirectory result:"+ isDirectory); }).catch(function(err){ - console.info("isDirectory failed with error:"+ err); + console.error("isDirectory failed with error: " + err); }); } ``` @@ -1209,7 +1209,7 @@ async function example() { if(fd > 0){ asset.close(fd); }else{ - console.info('File Open Failed!' + openError); + console.error('File Open Failed!' + openError); } }); } @@ -1252,7 +1252,7 @@ async function example() { console.info('File fd!' + fd); }) .catch((err) => { - console.info('File err!' + err); + console.error('File err!' + err); }); } ``` @@ -1292,15 +1292,15 @@ async function example() { console.info('File fd!' + fd); asset.close(fd, (closeErr) => { if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + console.error('mediaLibraryTest : close : FAIL ' + closeErr); + console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); } else { console.info("=======asset.close success====>"); } }); }) .catch((err) => { - console.info('File err!' + err); + console.error('File err!' + err); }); } ``` @@ -1345,8 +1345,8 @@ async function example() { console.info('File fd!' + fd); asset.close(fd).then((closeErr) => { if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + console.error('mediaLibraryTest : close : FAIL ' + closeErr); + console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); } else { console.info("=======asset.close success====>"); @@ -1354,7 +1354,7 @@ async function example() { }); }) .catch((err) => { - console.info('File err!' + err); + console.error('File err!' + err); }); } ``` @@ -1475,7 +1475,7 @@ async function example() { console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); }) .catch((err) => { - console.info('mediaLibraryTest : getThumbnail fail'+ err); + console.error('mediaLibraryTest : getThumbnail fail, err: ' + err); }); } ``` @@ -1556,7 +1556,7 @@ async function example() { asset.favorite(true).then(function() { console.info("favorite successfully"); }).catch(function(err){ - console.info("favorite failed with error:"+ err); + console.error("favorite failed with error: " + err); }); } ``` @@ -1634,7 +1634,7 @@ async function example() { asset.isFavorite().then(function(isFavorite){ console.info("isFavorite result:"+ isFavorite); }).catch(function(err){ - console.info("isFavorite failed with error:"+ err); + console.error("isFavorite failed with error: " + err); }); } ``` @@ -1720,7 +1720,7 @@ async function example() { asset.trash(true).then(function() { console.info("trash successfully"); }).catch(function(err){ - console.info("trash failed with error:"+ err); + console.error("trash failed with error: " + err); }); } ``` @@ -1875,7 +1875,6 @@ async function example() { console.info('mediaLibraryTest : isAfterLast:' + result); console.info('mediaLibraryTest : isAfterLast end'); fetchFileResult.close(); - } } } @@ -1938,7 +1937,7 @@ async function example() { console.error('Failed '); return; } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1973,7 +1972,7 @@ async function example() { fetchFileResult.getFirstObject().then(function(fileAsset){ console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); }).catch(function(err){ - console.info("getFirstObject failed with error:"+ err); + console.error("getFirstObject failed with error: " + err); }); } ``` @@ -2080,7 +2079,7 @@ async function example() { console.error('Failed '); return; } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -2149,7 +2148,7 @@ async function example() { console.error('Failed '); return; } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -2188,9 +2187,9 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }).catch(function (err) { - console.info("getFileAssets failed with error:" + err); + console.error("getFileAssets failed with error: " + err); }); } ``` @@ -2228,7 +2227,7 @@ async function example() { return; } for (let i = 0; i < fetchFileResult.getCount(); i++) { - console.log('fileAsset.displayName : ' + fileAsset[i].displayName); + console.info('fileAsset.displayName : ' + fileAsset[i].displayName); } }) } @@ -2315,7 +2314,7 @@ async function example() { console.error('Failed '); return; } - console.log('Modify successful.'); + console.info('Modify successful.'); }) } ``` @@ -2350,7 +2349,7 @@ async function example() { album.commitModify().then(function() { console.info("commitModify successfully"); }).catch(function(err){ - console.info("commitModify failed with error:"+ err); + console.error("commitModify failed with error: " + err); }); } ``` @@ -2430,9 +2429,9 @@ async function example() { const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + console.info("getFileAssets successfully: " + JSON.stringify(albumFetchFileResult)); }).catch(function(err){ - console.info("getFileAssets failed with error:"+ err); + console.error("getFileAssets failed with error: " + err); }); } ``` @@ -2486,7 +2485,7 @@ async function example() { | MEDIA_TYPE | "media_type" | 媒体类型 | | SIZE | "size" | 文件大小(单位:字节) | | DATE_ADDED | "date_added" | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | "date_modified" | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| DATE_MODIFIED | "date_modified" | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | | DATE_TAKEN | "date_taken" | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) | | TITLE | "title" | 文件标题 | | ARTIST | "artist" | 作者 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md index 4b02345124af20ab8459506ad3ff72bb1e7d9edb..b77ba93c2760ff1d1a37259c2dba371013b5b5bb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-connection.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-connection.md @@ -3,7 +3,6 @@ 网络连接管理提供管理网络一些基础能力,包括获取默认激活的数据网络、获取所有激活数据网络列表、开启关闭飞行模式、获取网络能力信息等功能。 > **说明:** -> > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -11,6 +10,40 @@ ```js import connection from '@ohos.net.connection' ``` +## connection.createNetConnection + +createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection + +返回一个NetConnection对象,netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络。 + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| netSpecifier | [NetSpecifier](#netspecifier) | 否 | 指定网络的各项特征,不指定则关注默认网络。 | +| timeout | number | 否 | 获取netSpecifier指定的网络时的超时时间,仅netSpecifier存在时生效。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------- | -------------------- | +| [NetConnection](#netconnection) | 所关注的网络的句柄。 | + +**示例:** + +```js +// 关注默认网络 +let netConnection = connection.createNetConnection() + +// 关注蜂窝网络 +let netConnectionCellular = connection.createNetConnection({ + netCapabilities: { + bearerTypes: [connection.NetBearType.BEARER_CELLULAR] + } +}) +``` ## connection.getDefaultNet @@ -26,14 +59,22 @@ getDefaultNet(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是 | 回调函数。 | +| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是 | 回调函数。当成功获取默认激活的数据网络时,err为undefined,data为默认激活的数据网络;否则为错误对象 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -connection.getDefaultNet(function (error, netHandle) { +connection.getDefaultNet(function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(netHandle)) + console.log(JSON.stringify(data)) }) ``` @@ -53,85 +94,348 @@ getDefaultNet(): Promise\ | --------------------------------- | ------------------------------------- | | Promise\<[NetHandle](#nethandle)> | 以Promise形式返回默认激活的数据网络。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js -connection.getDefaultNet().then(function (netHandle) { - console.log(JSON.stringify(netHandle)) +connection.getDefaultNet().then(function (data) { + console.log(JSON.stringify(data)) }) ``` -## connection.getDefaultNetSync9+ +## connection.getGlobalHttpProxy10+ -getDefaultNetSync(): NetHandle; +getGlobalHttpProxy(callback: AsyncCallback\): void -使用同步方法获取默认激活的数据网络。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。 +获取网络的全局代理配置信息,使用callback方式作为异步方法。 -**需要权限**:ohos.permission.GET_NETWORK_INFO +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | 是 | 回调函数。当成功获取网络的全局代理配置信息时,err为undefined,data为网络的全局代理配置信息;否则为错误对象| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.getGlobalHttpProxy((error,data) => { + console.info(JSON.stringify(error)); + console.info(JSON.stringify(data)); +}) +``` + +## connection.getGlobalHttpProxy10+ + +getGlobalHttpProxy(): Promise\; + +获取网络的全局代理配置信息,使用Promise方式作为异步方法。 **系统能力**:SystemCapability.Communication.NetManager.Core **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------- | -| NetHandle | 以同步方式返回默认激活的数据网络。 | +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\<[HttpProxy](#httpproxy)> | 以Promise形式返回网络的全局代理配置信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -let netHandle = connection.getDefaultNetSync(); +connection.getGlobalHttpProxy().then((data) => { + console.info(JSON.stringify(data)); +}).catch(error => { + console.info(JSON.stringify(error)); +}) ``` -## connection.hasDefaultNet +## connection.setGlobalHttpProxy10+ -hasDefaultNet(callback: AsyncCallback\): void +setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\): void -检查默认数据网络是否被激活,使用callback方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。 +设置网络全局Http代理配置信息,使用callback方式作为异步方法。 -**需要权限**:ohos.permission.GET_NETWORK_INFO +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL **系统能力**:SystemCapability.Communication.NetManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数,默认数据网络被激活返回true。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| httpProxy | [HttpProxy](#httpproxy) | 是 | 网络全局Http代理配置信息 | +| callback | AsyncCallback\ | 是 | 回调函数。当成功设置网络全局Http代理配置信息时,err为undefined,否则为错误对象| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -connection.hasDefaultNet(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) +let ExclusionList="" +let array = ExclusionList.split(','); +let httpProxy = { + host: "host", + port: 1, + parsedExclusionList: array +} +connection.setGlobalHttpProxy(httpProxy, (error, data) => { + console.info(JSON.stringify(error)); + console.info(JSON.stringify(data)); +}); +``` + +## connection.setGlobalHttpProxy10+ + +setGlobalHttpProxy(httpProxy: HttpProxy): Promise\; + +设置网络全局Http代理配置信息,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| httpProxy | [HttpProxy](#httpproxy) | 是 | 网络全局Http代理配置信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------- | ----------------------------- | +| Promise\ | 无返回值的Promise对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let ExclusionList="" +let array = ExclusionList.split(','); +let httpProxy = { + host: "host", + port: 1, + parsedExclusionList: array +} +connection.setGlobalHttpProxy(httpProxy).then((error, data) => { + console.info(JSON.stringify(data)); +}).catch(error=>{ + console.info(JSON.stringify(error)); }) ``` -## connection.hasDefaultNet +## connection.getAppNet9+ -hasDefaultNet(): Promise\ +getAppNet(callback: AsyncCallback\): void -检查默认数据网络是否被激活,使用Promise方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。 +获取App绑定的网络信息,使用callback方式作为异步方法。 -**需要权限**:ohos.permission.GET_NETWORK_INFO +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是 | 回调函数。当成功获取App绑定的网络信息时,err为undefined,data为获取到App绑定的网络信息;否则为错误对象| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.getAppNet(function(error, data)) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +} +``` + +## connection.getAppNet9+ + +getAppNet(): Promise\; + +获取App绑定的网络信息,使用Promise方式作为异步方法。 **系统能力**:SystemCapability.Communication.NetManager.Core **返回值:** -| 类型 | 说明 | -| ----------------- | ----------------------------------------------- | -| Promise\ | 以Promise形式返回,默认数据网络被激活返回true。 | +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetHandle](#nethandle)> | 以Promise形式返回App绑定的网络信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -connection.hasDefaultNet().then(function (has) { - console.log('has: ' + has) +connection.getAppNet().then((data) => { + console.info(JSON.stringify(data)); +}).catch(error => { + console.info(JSON.stringify(error)); }) ``` +## connection.SetAppNet9+ + +setAppNet(netHandle: NetHandle, callback: AsyncCallback\): void + +绑定App到指定网络,绑定后的App只能通过指定网络访问外网,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 | +| callback | AsyncCallback\ | 是 | 回调函数。当成功绑定App到指定网络时,err为undefined,否则为错误对象| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.getDefaultNet(function (error, netHandle) { + connection.setAppNet(netHandle, (error, data) => { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) + }); +}) +``` + +## connection.SetAppNet9+ + +setAppNet(netHandle: NetHandle): Promise\; + +绑定App到指定网络,绑定后的App只能通过指定网络访问外网,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------------------ | ---- | ---------------- | +| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------- | ----------------------------- | +| Promise\ | 无返回值的Promise对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.getDefaultNet().then(function (netHandle) { + connection.setAppNet(netHandle).then((error, data) => { + console.log(JSON.stringify(data)) + }).catch(error => { + console.log(JSON.stringify(error)) + }) +}) +``` + +## connection.getDefaultNetSync9+ + +getDefaultNetSync(): NetHandle; + +使用同步方法获取默认激活的数据网络。可以使用[getNetCapabilities](#connectiongetnetcapabilities)去获取网络的类型、拥有的能力等信息。 + +**需要权限**:ohos.permission.GET_NETWORK_INFO + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| --------- | ---------------------------------- | +| NetHandle | 以同步方式返回默认激活的数据网络。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let netHandle = connection.getDefaultNetSync(); +``` + ## connection.getAllNets getAllNets(callback: AsyncCallback<Array<NetHandle>>): void @@ -146,14 +450,22 @@ getAllNets(callback: AsyncCallback<Array<NetHandle>>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | 是 | 回调函数。 | +| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | 是 | 回调函数。当成功获取所有处于连接状态的网络列表时,err为undefined,data为激活的数据网络列表;否则为错误对象 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -connection.getAllNets(function (error, nets) { +connection.getAllNets(function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(nets)) + console.log(JSON.stringify(data)) }); ``` @@ -173,11 +485,19 @@ getAllNets(): Promise<Array<NetHandle>> | -------- | -------- | | Promise<Array<[NetHandle](#nethandle)>> | 以Promise形式返回激活的数据网络列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js -connection.getAllNets().then(function (nets) { - console.log(JSON.stringify(nets)) +connection.getAllNets().then(function (data) { + console.log(JSON.stringify(data)) }); ``` @@ -196,15 +516,25 @@ getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\ | 是 | 回调函数。 | +| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | 是 | 回调函数。当成功获取netHandle对应的网络的连接信息时,err为undefined,data为获取的网络连接信息;否则为错误对象| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle, function (error, info) { + connection.getConnectionProperties(netHandle, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(info)) + console.log(JSON.stringify(data)) }) }) ``` @@ -231,12 +561,22 @@ getConnectionProperties(netHandle: NetHandle): Promise\ | ------------------------------------------------------- | --------------------------------- | | Promise\<[ConnectionProperties](#connectionproperties)> | 以Promise形式返回网络的连接信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getConnectionProperties(netHandle).then(function (info) { - console.log(JSON.stringify(info)) + connection.getConnectionProperties(netHandle).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -256,15 +596,25 @@ getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\ | 是 | 回调函数。 | +| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | 是 | 回调函数。当成功获取netHandle对应的网络的能力信息时,err为undefined,data为获取到的网络能力信息;否则为错误对象 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle, function (error, info) { + connection.getNetCapabilities(netHandle, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(info)) + console.log(JSON.stringify(data)) }) }) ``` @@ -291,12 +641,22 @@ getNetCapabilities(netHandle: NetHandle): Promise\ | --------------------------------------------- | --------------------------------- | | Promise\<[NetCapabilities](#netcapabilities)> | 以Promise形式返回网络的能力信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js connection.getDefaultNet().then(function (netHandle) { - connection.getNetCapabilities(netHandle).then(function (info) { - console.log(JSON.stringify(info)) + connection.getNetCapabilities(netHandle).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -315,14 +675,22 @@ isDefaultNetMetered(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数,当前网络上的数据流量使用被计量返回true。 | +| callback | AsyncCallback\ | 是 | 回调函数。当前网络上的数据流量使用被计量返回true。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -connection.isDefaultNetMetered(function (error, has) { +connection.isDefaultNetMetered(function (error, data) { console.log(JSON.stringify(error)) - console.log('has: ' + has) + console.log('data: ' + data) }) ``` @@ -342,11 +710,208 @@ isDefaultNetMetered(): Promise\ | ----------------- | ----------------------------------------------- | | Promise\ | 以Promise形式返回,当前网络上的数据流量使用被计量true。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.isDefaultNetMetered().then(function (data) { + console.log('data: ' + data) +}) +``` + +## connection.hasDefaultNet + +hasDefaultNet(callback: AsyncCallback\): void + +检查默认数据网络是否被激活,使用callback方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。 + +**需要权限**:ohos.permission.GET_NETWORK_INFO + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | 是 | 回调函数。默认数据网络被激活返回true。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.hasDefaultNet(function (error, data) { + console.log(JSON.stringify(error)) + console.log('data: ' + data) +}) +``` + +## connection.hasDefaultNet + +hasDefaultNet(): Promise\ + +检查默认数据网络是否被激活,使用Promise方式作为异步方法。如果有默认数据网路,可以使用[getDefaultNet](#connectiongetdefaultnet)去获取。 + +**需要权限**:ohos.permission.GET_NETWORK_INFO + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ----------------------------------------------- | +| Promise\ | 以Promise形式返回,默认数据网络被激活返回true。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.hasDefaultNet().then(function (data) { + console.log('data: ' + data) +}) +``` + +## connection.enableAirplaneMode + +enableAirplaneMode(callback: AsyncCallback\): void + +开启飞行模式,使用callback方式作为异步方法。 + +**系统接口**:此接口为系统接口。 + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | 是 | 回调函数。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js -connection.isDefaultNetMetered().then(function (has) { - console.log('has: ' + has) +connection.enableAirplaneMode(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.enableAirplaneMode + +enableAirplaneMode(): Promise\ + +开启飞行模式,使用Promise方式作为异步方法。 + +**系统接口**:此接口为系统接口。 + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------- | ----------------------------- | +| Promise\ | 无返回值的Promise对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.enableAirplaneMode().then(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.disableAirplaneMode + +disableAirplaneMode(callback: AsyncCallback\): void + +关闭飞行模式,使用callback方式作为异步方法。 + +**系统接口**:此接口为系统接口。 + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | 是 | 回调函数。当关闭飞行模式成功,err为undefined,否则为错误对象。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.disableAirplaneMode(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.disableAirplaneMode + +disableAirplaneMode(): Promise\ + +关闭飞行模式,使用Promise方式作为异步方法。 + +**系统接口**:此接口为系统接口。 + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------- | ----------------------------- | +| Promise\ | 无返回值的Promise对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +connection.disableAirplaneMode().then(function (error) { + console.log(JSON.stringify(error)) }) ``` @@ -366,7 +931,17 @@ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当向网络管理报告网络处于可用状态成功,err为undefined,否则为错误对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** @@ -400,6 +975,16 @@ reportNetConnected(netHandle: NetHandle): Promise<void> | -------- | -------- | | Promise<void> | 无返回值的Promise对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js @@ -426,7 +1011,17 @@ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>) | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当向网络管理报告网络处于不可用状态成功,err为undefined,否则为错误对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** @@ -460,6 +1055,16 @@ reportNetDisconnected(netHandle: NetHandle): Promise<void> | -------- | -------- | | Promise<void> | 无返回值的Promise对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js @@ -485,15 +1090,25 @@ getAddressesByName(host: string, callback: AsyncCallback\>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------- | ---- | ------------------ | | host | string | 是 | 需要解析的主机名。 | -| callback | AsyncCallback\> | 是 | 回调函数。 | +| callback | AsyncCallback\> | 是 | 回调函数。当使用默认网络解析主机名成功获取所有IP地址,err为undefined,data为获取到的所有IP地址;否则为错误对象。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js let host = "xxxx"; -connection.getAddressesByName(host, function (error, addresses) { +connection.getAddressesByName(host, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(addresses)) + console.log(JSON.stringify(data)) }) ``` @@ -519,156 +1134,102 @@ getAddressesByName(host: string): Promise\> | ------------------------------------------- | ----------------------------- | | Promise\> | 以Promise形式返回所有IP地址。 | -**示例:** - -```js -let host = "xxxx"; -connection.getAddressesByName(host).then(function (addresses) { - console.log(JSON.stringify(addresses)) -}) -``` - -## connection.enableAirplaneMode - -enableAirplaneMode(callback: AsyncCallback\): void - -开启飞行模式,使用callback方式作为异步方法。 - -**系统接口**:此接口为系统接口。 - -**系统能力**:SystemCapability.Communication.NetManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | 是 | 回调函数。 | - -**示例:** - -```js -connection.enableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) -}) -``` - -## connection.enableAirplaneMode - -enableAirplaneMode(): Promise\ - -开启飞行模式,使用Promise方式作为异步方法。 - -**系统接口**:此接口为系统接口。 - -**系统能力**:SystemCapability.Communication.NetManager.Core - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------- | ----------------------------- | -| Promise\ | 无返回值的Promise对象。 | - -**示例:** - -```js -connection.enableAirplaneMode().then(function (error) { - console.log(JSON.stringify(error)) -}) -``` - -## connection.disableAirplaneMode - -disableAirplaneMode(callback: AsyncCallback\): void - -关闭飞行模式,使用callback方式作为异步方法。 - -**系统接口**:此接口为系统接口。 - -**系统能力**:SystemCapability.Communication.NetManager.Core - -**参数:** +**错误码:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js -connection.disableAirplaneMode(function (error) { - console.log(JSON.stringify(error)) +let host = "xxxx"; +connection.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) ``` -## connection.disableAirplaneMode +## NetConnection -disableAirplaneMode(): Promise\ +网络连接的句柄。 -关闭飞行模式,使用Promise方式作为异步方法。 +### register -**系统接口**:此接口为系统接口。 +register(callback: AsyncCallback\): void + +订阅指定网络状态变化的通知。 + +**需要权限**:ohos.permission.GET_NETWORK_INFO **系统能力**:SystemCapability.Communication.NetManager.Core -**返回值:** +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | 是 | 回调函数。当订阅指定网络状态变化的通知成功,err为undefined,否则为错误对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | +| 2101008 | The callback is not exists. | +| 2101022 | The number of requests exceeded the maximum. | -| 类型 | 说明 | -| ------------------------------------------- | ----------------------------- | -| Promise\ | 无返回值的Promise对象。 | **示例:** ```js -connection.disableAirplaneMode().then(function (error) { +netConnection.register(function (error) { console.log(JSON.stringify(error)) }) ``` -## connection.createNetConnection +### unregister -createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection +unregister(callback: AsyncCallback\): void -返回一个NetConnection对象,netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络。 +取消订阅默认网络状态变化的通知。 **系统能力**:SystemCapability.Communication.NetManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | -| netSpecifier | [NetSpecifier](#netspecifier) | 否 | 指定网络的各项特征,不指定则关注默认网络。 | -| timeout | number | 否 | 获取netSpecifier指定的网络时的超时时间,仅netSpecifier存在时生效。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------- | +| callback | AsyncCallback\ | 是 | 回调函数。当取消订阅指定网络状态变化的通知成功,err为undefined,否则为错误对象。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| ------------------------------- | -------------------- | -| [NetConnection](#netconnection) | 所关注的网络的句柄。 | +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | +| 2101007 | The same callback exists. | **示例:** ```js -// 关注默认网络 -let netConnection = connection.createNetConnection() - -// 关注蜂窝网络 -let netConnectionCellular = connection.createNetConnection({ - netCapabilities: { - bearerTypes: [connection.NetBearType.BEARER_CELLULAR] - } +netConnection.unregister(function (error) { + console.log(JSON.stringify(error)) }) ``` -## NetConnection - -网络连接的句柄。 - ### on('netAvailable') on(type: 'netAvailable', callback: Callback\): void 订阅网络可用事件。 +**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。 + **系统能力**:SystemCapability.Communication.NetManager.Core **参数:** @@ -676,21 +1237,37 @@ on(type: 'netAvailable', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件,固定为'netAvailable'。
netAvailable:数据网络可用事件。 | -| callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数。 | +| callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数,返回数据网络句柄。| **示例:** ```js -netConnection.on('netAvailable', function (data) { +// 创建NetConnection对象 +let netCon = connection.createNetConnection() + +// 先使用register接口注册订阅事件 +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// 订阅网络可用事件。调用register后,才能接收到此事件通知 +netCon.on('netAvailable', function (data) { console.log(JSON.stringify(data)) }) + +// 使用unregister接口取消订阅 +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netCapabilitiesChange') +### on('netBlockStatusChange') -on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void +on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void -订阅网络能力变化事件。 +订阅网络阻塞状态事件,使用callback方式作为异步方法。 + +**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。 **系统能力**:SystemCapability.Communication.NetManager.Core @@ -698,22 +1275,38 @@ on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, net | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 订阅事件,固定为'netCapabilitiesChange'。
netCapabilitiesChange:网络能力变化事件。 | -| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | 是 | 回调函数。 | +| type | string | 是 | 订阅事件,固定为'netBlockStatusChange'。
netBlockStatusChange:网络阻塞状态事件。 | +| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | 是 | 回调函数,返回数据网络句柄(netHandle),及网络堵塞状态(blocked)。| **示例:** ```js -netConnection.on('netCapabilitiesChange', function (data) { +// 创建NetConnection对象 +let netCon = connection.createNetConnection() + +// 先使用register接口注册订阅事件 +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// 订阅网络阻塞状态事件。调用register后,才能接收到此事件通知 +netCon.on('netBlockStatusChange', function (data) { console.log(JSON.stringify(data)) }) + +// 使用unregister接口取消订阅 +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netConnectionPropertiesChange') +### on('netCapabilitiesChange') -on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void +on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void -订阅网络连接信息变化事件。 +订阅网络能力变化事件。 + +**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。 **系统能力**:SystemCapability.Communication.NetManager.Core @@ -721,22 +1314,38 @@ on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHan | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 订阅事件,固定为'netConnectionPropertiesChange'。
netConnectionPropertiesChange:网络连接信息变化事件。 | -| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | 是 | 回调函数。 | +| type | string | 是 | 订阅事件,固定为'netCapabilitiesChange'。
netCapabilitiesChange:网络能力变化事件。 | +| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | 是 | 回调函数,返回数据网络句柄(netHandle)和网络的能力信息(netCap)。| **示例:** ```js -netConnection.on('netConnectionPropertiesChange', function (data) { +// 创建NetConnection对象 +let netCon = connection.createNetConnection() + +// 先使用register接口注册订阅事件 +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// 订阅网络能力变化事件。调用register后,才能接收到此事件通知 +netCon.on('netCapabilitiesChange', function (data) { console.log(JSON.stringify(data)) }) + +// 使用unregister接口取消订阅 +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` -### on('netBlockStatusChange') +### on('netConnectionPropertiesChange') -on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void +on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void -订阅网络阻塞状态事件,使用callback方式作为异步方法。 +订阅网络连接信息变化事件。 + +**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。 **系统能力**:SystemCapability.Communication.NetManager.Core @@ -744,15 +1353,29 @@ on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, b | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 订阅事件,固定为'netBlockStatusChange'。
netBlockStatusChange:网络阻塞状态事件。 | -| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | 是 | 回调函数。 | +| type | string | 是 | 订阅事件,固定为'netConnectionPropertiesChange'。
netConnectionPropertiesChange:网络连接信息变化事件。 | +| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | 是 | 回调函数,返回数据网络句柄(netHandle)和网络的连接信息(connectionProperties)| **示例:** ```js -netConnection.on('netBlockStatusChange', function (data) { +// 创建NetConnection对象 +let netCon = connection.createNetConnection() + +// 先使用register接口注册订阅事件 +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// 订阅网络连接信息变化事件。调用register后,才能接收到此事件通知 +netCon.on('netConnectionPropertiesChange', function (data) { console.log(JSON.stringify(data)) }) + +// 使用unregister接口取消订阅 +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` ### on('netLost') @@ -761,6 +1384,8 @@ on(type: 'netLost', callback: Callback\): void 订阅网络丢失事件。 +**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。 + **系统能力**:SystemCapability.Communication.NetManager.Core **参数:** @@ -768,15 +1393,28 @@ on(type: 'netLost', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件,固定为'netLost'。
netLost:网络严重中断或正常断开事件。 | -| callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数。 | +| callback | Callback\<[NetHandle](#nethandle)> | 是 | 回调函数,数据网络句柄(netHandle)| **示例:** ```js -let netConnection1 = connection.createNetConnection() -netConnection1.on('netLost', function (data) { +// 创建NetConnection对象 +let netCon = connection.createNetConnection() + +// 先使用register接口注册订阅事件 +netCon.register(function (error) { + console.log(JSON.stringify(error)) +}) + +// 订阅网络丢失事件。调用register后,才能接收到此事件通知 +netCon.on('netLost', function (data) { console.log(JSON.stringify(data)) }) + +// 使用unregister接口取消订阅 +netCon.unregister(function (error) { + console.log(JSON.stringify(error)) +}) ``` ### on('netUnavailable') @@ -785,6 +1423,8 @@ on(type: 'netUnavailable', callback: Callback\): void 订阅网络不可用事件。 +**模型约束**:此接口调用之前需要先调用register接口,使用unregister取消订阅默认网络状态变化的通知。 + **系统能力**:SystemCapability.Communication.NetManager.Core **参数:** @@ -792,58 +1432,26 @@ on(type: 'netUnavailable', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 订阅事件,固定为'netUnavailable'。
netUnavailable:网络不可用事件。 | -| callback | Callback\ | 是 | 回调函数。 | +| callback | Callback\ | 是 | 回调函数,无返回结果。| **示例:** ```js -netConnection.on('netUnavailable', function (data) { - console.log(JSON.stringify(data)) -}) -``` - -### register - -register(callback: AsyncCallback\): void - -订阅指定网络状态变化的通知。 - -**需要权限**:ohos.permission.GET_NETWORK_INFO - -**系统能力**:SystemCapability.Communication.NetManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数。 | +// 创建NetConnection对象 +let netCon = connection.createNetConnection() -**示例:** - -```js -netConnection.register(function (error) { +// 先使用register接口注册订阅事件 +netCon.register(function (error) { console.log(JSON.stringify(error)) }) -``` - -### unregister - -unregister(callback: AsyncCallback\): void - -取消订阅默认网络状态变化的通知。 - -**系统能力**:SystemCapability.Communication.NetManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +// 订阅网络不可用事件。调用register后,才能接收到此事件通知 +netCon.on('netUnavailable', function (data) { + console.log(JSON.stringify(data)) +}) -```js -netConnection.unregister(function (error) { +// 使用unregister接口取消订阅 +netCon.unregister(function (error) { console.log(JSON.stringify(error)) }) ``` @@ -864,7 +1472,7 @@ netConnection.unregister(function (error) { ### bindSocket9+ -bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; +bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void 将TCPSocket或UDPSocket绑定到当前网络,使用callback方式作为异步方法。 @@ -875,7 +1483,16 @@ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------------ | ---- | -------------------------------| | socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是 | 待绑定的TCPSocket或UDPSocket对象。| -| callback | AsyncCallback\ | 是 | 回调函数 | +| callback | AsyncCallback\ | 是 | 回调函数。当TCPSocket或UDPSocket成功绑定到当前网络,err为undefined,否则为错误对象。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** @@ -946,6 +1563,15 @@ bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\; | -------------- | ---------------------- | | Promise\ | 无返回值的Promise对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js @@ -1010,16 +1636,26 @@ getAddressesByName(host: string, callback: AsyncCallback\>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------- | ---- | ------------------ | | host | string | 是 | 需要解析的主机名。 | -| callback | AsyncCallback\> | 是 | 回调函数 | +| callback | AsyncCallback\> | 是 | 回调函数。当使用对应网络解析主机名成功获取所有IP地址,err为undefined,data为获取到的所有IP地址;否则为错误对象。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressesByName(host, function (error, addresses) { + netHandle.getAddressesByName(host, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(addresses)) + console.log(JSON.stringify(data)) }) }) ``` @@ -1046,13 +1682,23 @@ getAddressesByName(host: string): Promise\> | ------------------------------------------- | ----------------------------- | | Promise\> | 以Promise形式返回所有IP地址。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressesByName(host).then(function (addresses) { - console.log(JSON.stringify(addresses)) + netHandle.getAddressesByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` @@ -1072,16 +1718,26 @@ getAddressByName(host: string, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------- | ---- | ------------------ | | host | string | 是 | 需要解析的主机名。 | -| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。 | +| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是 | 回调函数。当使用对应网络解析主机名获取第一个IP地址成功,err为undefined,data为获取的第一个IP地址;否则为错误对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | **示例:** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressByName(host, function (error, address) { + netHandle.getAddressByName(host, function (error, data) { console.log(JSON.stringify(error)) - console.log(JSON.stringify(address)) + console.log(JSON.stringify(data)) }) }) ``` @@ -1108,41 +1764,27 @@ getAddressByName(host: string): Promise\ | ----------------------------------- | ------------------------------- | | Promise\<[NetAddress](#netaddress)> | 以Promise形式返回第一个IP地址。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + **示例:** ```js connection.getDefaultNet().then(function (netHandle) { let host = "xxxx"; - netHandle.getAddressByName(host).then(function (address) { - console.log(JSON.stringify(address)) + netHandle.getAddressByName(host).then(function (data) { + console.log(JSON.stringify(data)) }) }) ``` -## NetSpecifier - -提供承载数据网络能力的实例。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 - -| 名称 | 类型 | 必填 | 说明 | -| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| netCapabilities | [NetCapabilities](#netcapabilities) | 是 | 存储数据网络的传输能力和承载类型。 | -| bearerPrivateIdentifier | string | 否 | 网络标识符,Wi-Fi网络的标识符是"wifi",蜂窝网络的标识符是"slot0"(对应SIM卡1)。 | - -## NetCapabilities - -网络的能力集。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 - -| 名称 | 类型 | 必填 | 说明 | -| --------------------- | ---------------------------------- | --- | ------------------------ | -| linkUpBandwidthKbps | number | 否 | 上行(设备到网络)带宽。 | -| linkDownBandwidthKbps | number | 否 | 下行(网络到设备)带宽。 | -| networkCap | Array\<[NetCap](#netcap)> | 否 | 网络具体能力。 | -| bearerTypes | Array\<[NetBearType](#netbeartype)> | 是 | 网络类型。 | - ## NetCap 网络具体能力。 @@ -1169,6 +1811,42 @@ connection.getDefaultNet().then(function (netHandle) { | BEARER_WIFI | 1 | Wi-Fi网络。 | | BEARER_ETHERNET | 3 | 以太网网络。 | +## HttpProxy + +网络全局代理配置信息 + +**系统能力**:SystemCapability.Communication.NetManager.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ------ | --- |------------------------- | +| host | string | 否 | 代理服务器主机名。 | +| port | number | 否 | 主机端口。 | +| parsedExclusionList | Array | 否 | 不使用代理服务器的屏蔽列表。 | + +## NetSpecifier + +提供承载数据网络能力的实例。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 名称 | 类型 | 必填 | 说明 | +| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| netCapabilities | [NetCapabilities](#netcapabilities) | 是 | 存储数据网络的传输能力和承载类型。 | +| bearerPrivateIdentifier | string | 否 | 网络标识符,Wi-Fi网络的标识符是"wifi",蜂窝网络的标识符是"slot0"(对应SIM卡1)。 | + +## NetCapabilities + +网络的能力集。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 名称 | 类型 | 必填 | 说明 | +| --------------------- | ---------------------------------- | --- | ------------------------ | +| linkUpBandwidthKbps | number | 否 | 上行(设备到网络)带宽。 | +| linkDownBandwidthKbps | number | 否 | 下行(网络到设备)带宽。 | +| networkCap | Array\<[NetCap](#netcap)> | 否 | 网络具体能力。 | +| bearerTypes | Array\<[NetBearType](#netbeartype)> | 是 | 网络类型。 | + ## ConnectionProperties 网络连接信息。 @@ -1181,20 +1859,9 @@ connection.getDefaultNet().then(function (netHandle) { | domains | string | 是 |所属域,默认""。 | | linkAddresses | Array\<[LinkAddress](#linkaddress)> | 是 |链路信息。 | | routes | Array\<[RouteInfo](#routeinfo)> | 是 |路由信息。 | -| dnses | Array\<[NetAddress](#netaddress)>; | 是 |网络地址,参考[NetAddress](#netaddress)。 | +| dnses | Array\<[NetAddress](#netaddress)> | 是 |网络地址,参考[NetAddress](#netaddress)。 | | mtu | number | 是 |最大传输单元。 | -## LinkAddress - -网络链路信息。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 - -| 名称 | 类型 | 必填 |说明 | -| ------------ | ----------------------- |---- |-------------------- | -| address | [NetAddress](#netaddress) | 是 | 链路地址。 | -| prefixLength | number | 是 |链路地址前缀的长度。 | - ## RouteInfo 网络路由信息。 @@ -1209,6 +1876,17 @@ connection.getDefaultNet().then(function (netHandle) { | hasGateway | boolean | 是 |是否有网关。 | | isDefaultRoute | boolean | 是 |是否为默认路由。 | +## LinkAddress + +网络链路信息。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 名称 | 类型 | 必填 |说明 | +| ------------ | ----------------------- |---- |-------------------- | +| address | [NetAddress](#netaddress) | 是 | 链路地址。 | +| prefixLength | number | 是 |链路地址前缀的长度。 | + ## NetAddress 网络地址。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md index a451b5cf79e0c7ee25f77d7432e110173799442c..5da7dff74112a8ff98958a17b4599911292263da 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @@ -3,7 +3,6 @@ 以太网连接管理主要提供有线网络能力,提供设置有线网络的IP地址,子网掩码,网关,DNS等信息 > **说明:** -> > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -32,11 +31,24 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac | ic | [InterfaceConfiguration](#interfaceconfiguration) | 是 | 要设置的网络接口配置信息 | | callback | AsyncCallback\ | 是 | 回调函数,成功无返回,失败返回对应错误码。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | +| 2201006 | Device disconnected. | +| 2201007 | Failed to write the user configuration. | + **示例:** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", + gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"}, (error) => { if (error) { console.log("setIfaceConfig callback error = " + error); @@ -71,11 +83,24 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ | ------------------- | ----------------------------------------------------------- | | Promise\ | 以Promise形式返回执行结果。成功无返回,失败返回对应错误码。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | +| 2201006 | Device disconnected. | +| 2201007 | Failed to write the user configuration. | + **示例:** ```js -ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", - gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", + gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"}).then(() => { console.log("setIfaceConfig promiss ok "); }).catch((error) => { console.log("setIfaceConfig promiss error = " + error); @@ -101,6 +126,17 @@ getIfaceConfig(iface: string, callback: AsyncCallback\): | iface | string | 是 | 指定网络接口 | | callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | 是 | 回调函数,返回指定网络接口信息 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **示例:** ```js @@ -143,6 +179,17 @@ getIfaceConfig(iface: string): Promise\ | --------------------------------- | ---------------------------------- | | Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | 以Promise形式返回接口信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **示例:** ```js @@ -178,6 +225,17 @@ isIfaceActive(iface: string, callback: AsyncCallback\): void | iface | string | 是 | 接口名。为空时代表查询是否存在激活接口 | | callback | AsyncCallback\ | 是 | 回调函数,已激活:1,未激活:0,其他为获取失败错误码。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **示例:** ```js @@ -214,6 +272,17 @@ isIfaceActive(iface: string): Promise\ | ----------------| ------------------------------------------------------------------ | | Promise\ | 以Promise形式返回获取结果。已激活:1,未激活:0,其他为获取失败错误码。| +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | +| 2201005 | The device information does not exist. | + **示例:** ```js @@ -242,6 +311,14 @@ getAllActiveIfaces(callback: AsyncCallback\>): void | -------- | ------------------------------------ | ---- | ------------------------------ | | callback | AsyncCallback\> | 是 | 回调函数,返回值为对应接口名。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | + **示例:** ```js @@ -275,6 +352,14 @@ getAllActiveIfaces(): Promise\> | ------------------------------ | ----------------------------------------------- | | Promise\> | 以Promise形式返回获取结果。返回值为对应接口名。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------| +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service.| +| 2200003 | System internal error. | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-policy.md b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..0d2eef9ee6be3b6fd5d807b954367ba4fed1ba88 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1558 @@ +# @ohos.net.policy (网络策略管理) + +网络策略管理通过对用户使用数据流量进行控制管理,采用防火墙技术实现网络策略的管理。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import policy from '@ohos.net.policy' +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void + +设置后台网络策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | 是 | 是否允许应用后台使用数据 | +| callback | AsyncCallback\ | 是 | 回调函数,成功返回设置后台网络策略的结果,失败返回错误码错误信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => { + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean): Promise\ + +设置后台网络策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | 是 | 是否允许应用后台使用数据 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果,失败返回错误码错误信息。 | + +**示例:** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.isBackgroundAllowed + +isBackgroundAllowed(callback: AsyncCallback\): void + +获取后台网络策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | 是 | 回调函数,返回true代表后台策略为允许。失败返回错误码错误信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.isBackgroundAllowed((error, data) => { + this.callBack(error, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.isBackgroundAllowed + +isBackgroundAllowed(): Promise\; + +获取后台网络策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 返回true代表后台策略为允许。失败返回错误码错误信息。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.isBackgroundAllowed().then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void + +设置对应uid应用的访问计量网络的策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | 应用的唯一标识符 | +| policy | [NetUidPolicy](#netuidpolicy) | 是 | 应用对应的策略 | +| callback | AsyncCallback\ | 是 | 回调函数,成功返回设定结果。失败返回错误码错误信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; + +设置对应uid应用的访问计量网络的策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | 应用的唯一标识符 | +| policy | [NetUidPolicy](#netuidpolicy) | 是 | 应用对应的策略 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。失败返回错误码错误信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number, callback: AsyncCallback\): void + +通过应用uid获取策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | 是 | 回调函数,成功返回获取策略结果,失败返回错误码错误信息。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number): Promise\; + +通过应用uid获取策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetUidPolicy](#netuidpolicy)> | 以Promise形式返回获取策略结果。失败返回错误码错误信息。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getUidsByPolicy + +getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void + +通过策略获取设置这一策略的应用uid数组,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | 是 | 应用对应的计量网络下的策略 | +| callback | AsyncCallback\> | 是 | 回调函数,成功返回应用的uid数组,失败返回错误码错误信息。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getUidsByPolicy + +function getUidsByPolicy(policy: NetUidPolicy): Promise\>; + +通过策略获取设置这一策略的应用uid数组,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | 是 | app对应的计量网络下的策略 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\> | 以Promise形式返回应用的uid数组,失败返回错误码错误信息。| + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(callback: AsyncCallback\>): void + +获取计量网络策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | 是 | 回调函数,返回获取结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getNetQuotaPolicies((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(): Promise\>; + +获取计量网络策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\> | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getNetQuotaPolicies().then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void + +设置计量网络策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | 是 | 计量网络策略 | +| callback | AsyncCallback\ | 是 | 回调函数,返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\): Promise\; + +设置计量网络策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | 是 | 计量网络策略 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**示例:** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string, callback: AsyncCallback\): void + +重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | 是 | SIM卡ID| +| callback | AsyncCallback\ | 是 | 回调函数,返回重置结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string): Promise\; + +重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | 是 | SIM卡ID| + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam).then((error, data){ + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void + +获取对应uid能否访问计量或非计量网络,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| isMetered | boolean | 是 | 是否为计量网络 | +| callback | AsyncCallback\ | 是 | 回调函数,返回true表示这个uid可以访问对应的计量网络。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean): Promise\; + +获取对应uid能否访问计量或非计量网络,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| isMetered | boolean | 是 | 是否为计量网络 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void + +获取对应uid能否访问指定的iface的网络,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| iface | string | 是 | 网络对应的名称 | +| callback | AsyncCallback\ | 是 | 回调函数,返回true表示这个uid可以访问对应iface的网络。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string): Promise\; + +获取对应uid能否访问指定的iface的网络,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| iface | string | 是 | 网络对应的名称 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setDeviceIdleAllowList + +setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void + +设置指定uid应用是否在休眠防火墙的白名单,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| isAllowed | boolean | 是 | 是否加入白名单 | +| callback | callback: AsyncCallback\ | 是 | 回调函数,返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setDeviceIdleAllowList + +setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; + +设置指定uid应用是否在休眠防火墙的白名单,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| isAllowed | boolean | 是 | 是否加入白名单 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getDeviceIdleAllowList + +getDeviceIdleAllowList(callback: AsyncCallback\>): void + +获取休眠模式白名单所包含的uid数组,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | 是 | 回调函数,返回获取结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getDeviceIdleAllowList((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getDeviceIdleAllowList + +getDeviceIdleAllowList(): Promise\>; + +获取休眠模式白名单所包含的uid数组,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\> | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getDeviceIdleAllowList().then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void + +获取指定uid能否访问后台网络,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | 是 | 回调函数,返回获取结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number): Promise\; + +获取指定uid能否访问后台网络,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.resetPolicies + +resetPolicies(iccid: string, callback: AsyncCallback\): void + +重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | 是 | SIM卡ID| +| callback | AsyncCallback\ | 是 | 回调函数,返回重置结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +this.firstParam = iccid +policy.resetPolicies(this.firstParam, (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.resetPolicies + +resetPolicies(iccid: string): Promise\; + +重置对应sim卡id的蜂窝网络、后台网络策略、防火墙策略、应用对应的策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | 是 | SIM卡ID| + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((error, data) { + +}) +this.firstParam = iccid +policy.resetPolicies(this.firstParam).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void + +更新提醒策略,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 是 | 网络类型 | +| iccid | string | 是 | SIM卡ID| +| remindType | [RemindType](#remindtype) | 是 | 提醒类型 | +| callback | AsyncCallback\ | 是 | 回调函数,返回更新结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; + +更新提醒策略,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 是 | 网络类型 | +| iccid | string | 是 | SIM卡ID| +| remindType | [RemindType](#remindtype) | 是 | 提醒类型 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPowerSaveAllowList + +setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void + +设置指定uid应用是否在省电防火墙的白名单,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| isAllowed | boolean | 是 | 是否加入白名单 | +| callback | callback: AsyncCallback\ | 是 | 回调函数,返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { + this.callBack(error, data); +}); +``` + +## policy.setPowerSaveAllowList + +setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\; + +设置指定uid应用是否在省电防火墙的白名单,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | 是 | app唯一标识符 | +| isAllowed | boolean | 是 | 是否加入白名单 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\ | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2100001 | Invalid parameter value. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPowerSaveAllowList + +getPowerSaveAllowList(callback: AsyncCallback\>): void + +获取省电模式白名单所包含的uid数组,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | 是 | 回调函数,返回获取结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getPowerSaveAllowList((error, data) => { + this.callBack(error, data); +}); +``` + +## policy.getPowerSaveAllowList + +getPowerSaveAllowList(): Promise\>; + +获取休眠模式白名单所包含的uid数组,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------------------- | ------------------------------------- | +| Promise\> | 以Promise形式返回设定结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2100002 | Operation failed. Cannot connect to service.| +| 2100003 | System internal error. | + +**示例:** + +```js +policy.getPowerSaveAllowList().then((error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.on + +网络策略的句柄。 + +### on('netUidPolicyChange') + +on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void + +注册policy发生改变时的回调,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidPolicyChange | 是 | policy发生改变的类型 | +| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | 是 | 回调函数。注册policy发生改变时调用。 | + +**示例:** + +```js +policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange:' + JSON.stringify(data)); +}) +``` + +### on('netUidRuleChange') + +on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void + +注册rule发生改变时的回调,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidRuleChange | 是 | rule发生改变的类型 | +| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | 是 | 回调函数。注册rule发生改变时的调用。 | + +**示例:** + +```js +policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange:' + JSON.stringify(data)); +}) +``` + +### on('netMeteredIfacesChange') + +on(type: "netMeteredIfacesChange", callback: Callback\>): void + +注册计量iface发生改变时的回调,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netMeteredIfacesChange | 是 | 计量iface发生改变的类型 | +| callback | Callback\> | 是 | 回调函数。注册计量iface发生改变时调用。 | + +**示例:** + +```js +policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange:' + JSON.stringify(data)); +}) +``` + +### on('netQuotaPolicyChange') + +on(type: "netQuotaPolicyChange", callback: Callback\>): void + +注册计量网络策略发生改变时的回调,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netQuotaPolicyChange | 是 | 计量网络策略发生改变的类型 | +| callback | Callback\> | 是 | 回调函数。注册计量网络策略发生改变时调用。 | + +**示例:** + +```js +policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange:' + JSON.stringify(data)); +}) +``` + +### on('netBackgroundPolicyChange') + +on(type: "netBackgroundPolicyChange", callback: Callback\): void + +注册后台网络策略发生改变时的回调,使用callback方式作为异步方法。 + +**需要权限**:ohos.permission.CONNECTIVITY_INTERNAL + +**系统能力**:SystemCapability.Communication.NetManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netBackgroundPolicyChange | 是 | 后台网络策略发生改变的类型 | +| callback | Callback\ | 是 | 回调函数。注册后台网络策略发生改变时调用。 | + +**示例:** + +```js +policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange:' + JSON.stringify(data)); +}) +``` + +## NetBackgroundPolicy + +后台网络策略。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 参数名 | 值 | 说明 | +| ------------------------ | ---- | ---------------------- | +| NET_BACKGROUND_POLICY_NONE | 0 | 默认值。 | +| NET_BACKGROUND_POLICY_ENABLE | 1 | 应用在后台可以使用计量网路。 | +| NET_BACKGROUND_POLICY_DISABLE | 2 | 应用在后台不可以使用计量网路。 | +| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | 只有应用指定的列表在后台可以使用计量网络。 | + +## NetQuotaPolicy + +计量网络策略。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 参数名 | 类型 | 说明 | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | 网络类型。 | +| iccid | string | 计量蜂窝网络的SIM卡的标识值。以太网,wifi网络不会用到 | +| ident | string | 计量蜂窝网络中配合iccid联合使用。以太网,wifi网络单独使用。用于标记类型。 | +| periodDuration | string | 计量开始时间。 | +| warningBytes | number | 发出警告的流量阈值。 | +| limitBytes | number | 流量设置的配额。 | +| lastWarningRemind | string | 最新一次发出警告的时间。 | +| lastLimitRemind | string | 最新一次配额耗尽的时间。 | +| metered | string | 是否为计量网络。 | +| limitAction | [LimitAction](#limitaction) | 到达流量限制后的动作。 | + +## LimitAction + +限制动作。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 参数名 | 值 | 说明 | +| ---------------------- | ----- | ------------ | +| LIMIT_ACTION_NONE | -1 | 默认值。 | +| LIMIT_ACTION_DISABLE | 0 | 当配额策略达到限制时,访问被禁用。 | +| LIMIT_ACTION_AUTO_BILL| 1 | 当配额策略达到限制时,用户将自动计费。 | + +## NetUidRule + +计量网络规则。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 参数名 | 值 | 说明 | +| ---------------------- | ----- | ------------ | +| NET_RULE_NONE | 0 | 默认规则 | +| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | 允许前台访问计量网络 | +| NET_RULE_ALLOW_METERED | 2 | 允许访问计量网络 | +| NET_RULE_REJECT_METERED | 4 | 拒绝访问计量网络 | +| NET_RULE_ALLOW_ALL | 32 | 允许访问所有网络 | +| NET_RULE_REJECT_ALL | 64 | 拒绝访问所有网络 | + +## RemindType + +提醒类型。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 参数名 | 值 | 说明 | +| ---------------------- | - | ------- | +| REMIND_TYPE_WARNING | 1 | 警告提醒 | +| REMIND_TYPE_LIMIT | 2 | 限制提醒 | + +## NetUidPolicy + +应用对应的网络策略。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。 + +| 参数名 | 值 | 说明 | +| ---------------------- | ----- | ------------ | +| NET_POLICY_NONE | 0 | 默认网络策略 | +| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | 允许应用在后台访问计量网络 | +| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | 拒绝应用在后台访问计量网络 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md b/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md index cefbc4d648d85cb95de3f56f8bfd010f3384d366..3d7bb956500d79e1a26dde36e867cc55af3c3073 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,6 +1,6 @@ # @ohos.net.sharing (网络共享管理) -网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享和蓝牙共享,同时提供网络共享状态、共享流量查询功能。 +网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。 > **说明:** > @@ -30,6 +30,15 @@ isSharingSupported(callback: AsyncCallback\): void | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 是 | 回调函数,返回true代表支持网络共享。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | + **示例:** ```js @@ -57,6 +66,15 @@ isSharingSupported(): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回是否支持共享结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202011 | Cannot get network sharing configuration. | + **示例:** ```js @@ -85,6 +103,14 @@ isSharing(callback: AsyncCallback\): void | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 是 | 回调函数,返回true代表网络共享中。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -112,6 +138,14 @@ isSharing(): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回网络共享状态结果,返回true代表网络共享中。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -141,6 +175,21 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\): void | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | callback | AsyncCallback\ | 是 | 回调函数,返回开启网络共享结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202009 | Network share enable forwarding error. | +| 2202011 | Cannot get network sharing configuration. | + **示例:** ```js @@ -174,6 +223,21 @@ startSharing(type: SharingIfaceType): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回开启共享执行结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202004 | Try to share an unavailable iface. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202009 | Network share enable forwarding error. | +| 2202011 | Cannot get network sharing configuration. | + **示例:** ```js @@ -204,6 +268,19 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | | callback | AsyncCallback\ | 是 | 回调函数,返回停止网络共享结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202011 | Cannot get network sharing configuration. | + **示例:** ```js @@ -237,6 +314,19 @@ stopSharing(type: SharingIfaceType): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回关闭共享执行结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | +| 2202005 | WiFi sharing failed. | +| 2202006 | Bluetooth sharing failed. | +| 2202011 | Cannot get network sharing configuration. | + **示例:** ```js @@ -266,6 +356,14 @@ getStatsRxBytes(callback: AsyncCallback\): void | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 是 | 回调函数,number代表数据量,单位:KB。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -293,6 +391,14 @@ getStatsRxBytes(): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回共享网络接收数据量,单位:KB。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -321,6 +427,14 @@ getStatsTxBytes(callback: AsyncCallback\): void | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 是 | 回调函数,number代表数据量,单位:KB。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -348,6 +462,14 @@ getStatsTxBytes(): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回共享网络发送数据量,单位:KB。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -376,6 +498,14 @@ getStatsTotalBytes(callback: AsyncCallback\): void | -------- | --------------------------------------- | ---- | ---------- | | callback | AsyncCallback\ | 是 | 回调函数,number代表数据量,单位:KB。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -403,6 +533,14 @@ getStatsTotalBytes(): Promise\ | --------------------------------- | ------------------------------------- | | Promise\ | 以Promise形式返回共享网络总数据量,单位:KB。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -432,6 +570,16 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\> | 是 | 回调函数,返回指定状态的网卡名称列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -466,6 +614,16 @@ getSharingIfaces(state: SharingIfaceState): Promise\> | --------------------------------- | ------------------------------------- | | Promise\> | 以Promise形式返回指定状态网卡名称列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -496,6 +654,16 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\ | 是 | 回调函数,返回指定类型网络共享状态。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -524,6 +692,16 @@ getSharingState(type: SharingIfaceType): Promise\ | -------- | --------------------------------------- | ---- | ---------- | | type | [SharingIfaceType](#sharingifacetype) | 是 | 共享类型,0:Wi-Fi 1:USB 2:BLUETOOTH。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **返回值:** | 类型 | 说明 | @@ -560,6 +738,16 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\> | 是 | 回调函数,返回指定类型网卡名称正则表达式列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -594,6 +782,16 @@ getSharableRegexes(type: SharingIfaceType): Promise\> | --------------------------------- | ------------------------------------- | | Promise\> | 以Promise形式返回正则表达式列表。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | +| 2200001 | Invalid parameter value. | +| 2200002 | Operation failed. Cannot connect to service. | +| 2200003 | System internal error. | + **示例:** ```js @@ -624,6 +822,13 @@ on(type: 'sharingStateChange', callback: Callback\): void | type | string | 是 | 事件名称。 | | callback | AsyncCallback\ | 是 | 回调函数,返回网络共享状态。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **示例:** ```js @@ -652,6 +857,13 @@ off(type: 'sharingStateChange', callback?: Callback\): void | type | string | 是 | 事件名称。 | | callback | AsyncCallback\ | 否 | 回调函数,返回网络共享状态。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **示例:** ```js @@ -680,6 +892,13 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface | type | string | 是 | 事件名称。 | | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 是 | 回调函数,指定网卡共享状态变化时调用。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **示例:** ```js @@ -708,6 +927,13 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa | type | string | 是 | 事件名称。 | | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | 否 | 回调函数,注销指定网卡共享状态变化通知。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **示例:** ```js @@ -736,6 +962,13 @@ on(type: 'sharingUpstreamChange', callback: Callback\): void | type | string | 是 | 事件名称。 | | callback | AsyncCallback\ | 是 | 回调函数,上行网络变化时调用。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **示例:** ```js @@ -764,6 +997,13 @@ off(type: 'sharingUpstreamChange', callback?: Callback\): void | type | string | 是 | 事件名称。 | | callback | AsyncCallback\ | 否 | 回调函数,注销上行网络变化事件。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. | + **示例:** ```js @@ -789,7 +1029,7 @@ sharing.off('sharingUpstreamChange', (error, data) => { ## SharingIfaceType -网络共享类型(暂不支持USB共享)。 +网络共享类型。 **系统接口**:此接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md index 166c69fb6594c350cb943a03ff2db8ef4e732e79..04918ca06f0759a4033d73afcfb769861dcbecc5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -120,9 +120,9 @@ try { } ``` -## privacyManager.getPermissionUsedRecords +## privacyManager.getPermissionUsedRecord -getPermissionUsedRecords(request: PermissionUsedRequest): Promise<PermissionUsedResponse> +getPermissionUsedRecord(request: PermissionUsedRequest): Promise<PermissionUsedResponse> 获取历史权限使用记录。使用Promise异步回调。 @@ -170,19 +170,19 @@ let request = { "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { - privacyManager.getPermissionUsedRecords(request).then((data) => { - console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + privacyManager.getPermissionUsedRecord(request).then((data) => { + console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`); }).catch((err) => { - console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`); }); } catch(err) { console.log(`catch err->${JSON.stringify(err)}`); } ``` -## privacyManager.getPermissionUsedRecords +## privacyManager.getPermissionUsedRecord -getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void +getPermissionUsedRecord(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void 获取历史权限使用记录。使用callback异步回调。 @@ -225,11 +225,11 @@ let request = { "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; try { - privacyManager.getPermissionUsedRecords(request, (err, data) => { + privacyManager.getPermissionUsedRecord(request, (err, data) => { if (err) { - console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`); } else { - console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`); } }); } catch(err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index dd2d559e57d2008eafdf4e1d9e8982746fb67429..901b010bad01b1ee88840792cb06777ed9c76bc7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -35,8 +35,12 @@ isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void 判断指定bundleName的应用当前是否是空闲状态,三方应用只能查询自身的空闲状态,使用Callback形式返回。 +**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO + **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**系统API**:此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -53,8 +57,8 @@ isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | **示例**: ```js @@ -77,8 +81,12 @@ isIdleState(bundleName: string): Promise<boolean> 判断指定bundleName的应用当前是否是空闲状态,三方应用只能查询自身的空闲状态,使用Promise形式返回。 +**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO + **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**系统API**:此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -100,8 +108,8 @@ isIdleState(bundleName: string): Promise<boolean> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | **示例**: @@ -140,10 +148,10 @@ queryAppGroup(): Promise<number> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000004 | IPC failed. | +| 10000005 | Application is not installed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **示例**: @@ -182,10 +190,10 @@ queryAppGroup(callback: AsyncCallback<number>): void | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000004 | IPC failed. | +| 10000005 | Application is not installed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **示例**: @@ -232,9 +240,9 @@ queryBundleStatsInfos(begin: number, end: number, callback: AsyncCallback<Bun | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -292,9 +300,9 @@ queryBundleStatsInfos(begin: number, end: number): Promise<BundleStatsMap> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -346,9 +354,9 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -405,9 +413,9 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -456,9 +464,9 @@ queryBundleEvents(begin: number, end: number, callback: AsyncCallback<Array&l | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -514,9 +522,9 @@ queryBundleEvents(begin: number, end: number): Promise<Array<BundleEvents& | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -561,9 +569,9 @@ queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback< | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -615,9 +623,9 @@ queryCurrentBundleEvents(begin: number, end: number): Promise<Array<Bundle | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -664,9 +672,9 @@ queryModuleUsageRecords(): Promise<Array<HapModuleInfo>> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -714,9 +722,9 @@ queryModuleUsageRecords(callback: AsyncCallback<Array<HapModuleInfo>> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -771,9 +779,9 @@ queryModuleUsageRecords(maxNum: number): Promise<Array<HapModuleInfo>&g | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -821,9 +829,9 @@ queryModuleUsageRecords(maxNum: number, callback: AsyncCallback<Array<HapM | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -878,10 +886,10 @@ queryAppGroup(bundleName : string): Promise<number> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | +| 10000004 | IPC failed. | | 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **示例**: @@ -927,10 +935,10 @@ queryAppGroup(bundleName : string, callback: AsyncCallback<number>): void | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | +| 10000004 | IPC failed. | | 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **示例**: @@ -977,9 +985,9 @@ setAppGroup(bundleName: string, newGroup: GroupType): Promise<void> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10100001 | Repeated operation on the application group. | **返回值**: @@ -1033,9 +1041,9 @@ setAppGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback< | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10100001 | Repeated operation on the application group. | **示例**: @@ -1083,8 +1091,8 @@ registerAppGroupCallBack(groupCallback: Callback<AppGroupCallbackInfo>): P | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **返回值**: @@ -1142,13 +1150,14 @@ registerAppGroupCallBack(groupCallback: Callback<AppGroupCallbackInfo>, ca | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **示例**: ```javascript + // @ts-nocheck let onBundleGroupChanged = (err, res) =>{ console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appOldGroup is : ' + res.appOldGroup); @@ -1197,8 +1206,8 @@ unregisterAppGroupCallBack(): Promise<void> | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **示例**: @@ -1241,8 +1250,8 @@ unregisterAppGroupCallBack(callback: AsyncCallback<void>): void; | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **示例**: @@ -1294,9 +1303,9 @@ queryDeviceEventStats(begin: number, end: number): Promise<Array<DeviceEve | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -1342,9 +1351,9 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback<Arr | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -1397,9 +1406,9 @@ queryNotificationEventStats(begin: number, end: number): Promise<Array<Dev | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: @@ -1445,9 +1454,9 @@ queryNotificationEventStats(begin: number, end: number, callback: AsyncCallback& | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-screen.md b/zh-cn/application-dev/reference/apis/js-apis-screen.md index 7c37de05cb8fe9303392531982b4af0bfc8f8a57..d2c888e1f4b312e1a9338b2344853be23dd78a52 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-screen.md +++ b/zh-cn/application-dev/reference/apis/js-apis-screen.md @@ -735,6 +735,8 @@ try { 下列API示例中都需先使用[getAllScreens()](#screengetallscreens)、[createVirtualScreen()](#screencreatevirtualscreen)中的任一方法获取到Screen实例,再通过此实例调用对应方法。 +### 属性 + **系统能力:** SystemCapability.WindowManager.WindowManager.Core | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -744,6 +746,7 @@ try { | supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | 是 | 否 | 屏幕支持的模式集合。 | | activeModeIndex | number | 是 | 否 | 当前屏幕所处模式索引。 | | orientation | [Orientation](#orientation) | 是 | 否 | 屏幕方向。 | +| sourceMode10+ | [ScreenSourceMode](#screensourcemode10) | 是 | 否 | 屏幕来源模式。 | ### setOrientation @@ -997,6 +1000,19 @@ try { | REVERSE_VERTICAL | 3 | 表示指定屏幕为反向垂直方向。 | | REVERSE_HORIZONTAL | 4 | 表示指定屏幕为反向水平方向。 | +## ScreenSourceMode10+ + +屏幕显示内容来源模式枚举。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +| 名称 | 值 | 说明 | +| ------------------ | ---- | -------------------------------- | +| SCREEN_MAIN | 0 | 表示屏幕为默认主屏。 | +| SCREEN_MIRROR | 1 | 表示屏幕内容来自镜像。 | +| SCREEN_EXTEND | 2 | 表示屏幕内容来自扩展。 | +| SCREEN_ALONE | 3 | 表示屏幕为未指定来源。 | + ## ScreenModeInfo 屏幕显示模式信息。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-settings.md b/zh-cn/application-dev/reference/apis/js-apis-settings.md index 1fd15c0f09c8801a2b822ac7778643cb117f5ff4..3c92903dd4b91ad78982c2693358ac314e7338dd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-settings.md +++ b/zh-cn/application-dev/reference/apis/js-apis-settings.md @@ -328,6 +328,8 @@ import featureAbility from '@ohos.ability.featureAbility'; //更新数据项亮度的值(该数据项在数据库中已存在,故setValue方法将更新该数据项的值) let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); +//@ts-ignore +//此处数据项值的类型为string settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => { console.log('Callback return whether value is set.'); }); @@ -365,6 +367,8 @@ import featureAbility from '@ohos.ability.featureAbility'; //更新数据项亮度的值(该数据项在数据库中已存在,故setValue方法将更新该数据项的值) let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); let helper = featureAbility.acquireDataAbilityHelper(uri); +//@ts-ignore +//此处数据项值的类型为string settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => { console.log('Callback return whether value is set.'); }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-socket.md b/zh-cn/application-dev/reference/apis/js-apis-socket.md index 1659644ba57a226828422a0d1576acda37a64000..9c5f0e008d8bc2240473582bb95af720f979670c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-socket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-socket.md @@ -667,6 +667,12 @@ Socket的连接信息。 | port | number | 是 | 端口号,范围0~65535。 | | size | number | 是 | 服务器响应信息的字节长度。 | +## UDP 错误码说明 + +UDP 错误码映射形式为:2301000 + 内核错误码。 + +错误码的详细介绍参见[Socket错误码](../errorcodes/errorcode-socket.md) + ## socket.constructTCPSocketInstance constructTCPSocketInstance\(\): TCPSocket @@ -1453,6 +1459,12 @@ TCPSocket连接的其他属性。 | reuseAddress | boolean | 否 | 是否重用地址。默认为false。 | | socketTimeout | number | 否 | 套接字超时时间,单位毫秒(ms)。 | +## TCP 错误码说明 + +TCP 错误码映射形式为:2301000 + 内核错误码。 + +错误码的详细介绍参见[Socket错误码](../errorcodes/errorcode-socket.md) + ## socket.constructTLSSocketInstance9+ constructTLSSocketInstance(): TLSSocket diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-app.md b/zh-cn/application-dev/reference/apis/js-apis-system-app.md index 105134736b233c4b9cd2fd5860e8757feed4b478..8a03bfb8c5842b16ec77570d4a577400b3073893 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-app.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-app.md @@ -1,6 +1,7 @@ # @system.app (应用上下文) > **说明:** +> > - 从API Version 7 开始,该接口不再维护,推荐使用新接口。 > > - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -20,7 +21,7 @@ getInfo(): AppResponse 获取当前应用配置文件中声明的信息。 -> **说明:** 从API Version 7开始,推荐使用[`@ohos.bundle`](js-apis-Bundle.md)。 +从API Version 7开始,推荐使用[`@ohos.bundle`](js-apis-Bundle.md)。 **系统能力:** SystemCapability.ArkUI.ArkUI.Lite @@ -32,14 +33,14 @@ getInfo(): AppResponse **示例:** - ```ts +```ts export default { getInfo() { let info = app.getInfo() console.log(JSON.stringify(info)) } } - ``` +``` ## app.terminate @@ -47,37 +48,38 @@ terminate(): void 退出当前Ability。 -> **说明:** 从API Version 7开始,推荐使用[`@ohos.ability.featureAbility`](js-apis-ability-featureAbility.md)。 +从API Version 7开始,推荐使用[`@ohos.ability.featureAbility`](js-apis-ability-featureAbility.md)。 **系统能力:** SystemCapability.ArkUI.ArkUI.Lite **示例:** - ```ts +```ts export default { terminate() { app.terminate() } } - ``` +``` ## app.requestFullWindow requestFullWindow(options?: RequestFullWindowOptions): void 请求应用以全窗口运行,FA在某些场景下(如半模态FA)会以非全窗口运行,调用该接口会从非全窗口切换为全窗口运行,如果已经以全窗口运行则该接口调用无效。 -> **说明:** 从API Version 7开始,推荐使用[`@ohos.window`](js-apis-window.md)。 +从API Version 7开始,推荐使用[`@ohos.window`](js-apis-window.md)。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | options | [RequestFullWindowOptions](#requestfullwindowoptions) | 否 | 请求全屏时,设定非全屏到全屏的过渡时间,单位为毫秒,默认时间与非全屏到全屏的距离成正比。 | **示例:** - ```ts +```ts export default { requestFullWindow() { app.requestFullWindow({ @@ -85,7 +87,7 @@ export default { }) } } - ``` +``` ## app.setImageCacheCount7+ @@ -96,13 +98,14 @@ setImageCacheCount(value: number): void **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | number | 是 | 内存中解码后图片的缓存数量。 | **示例:** - ```ts +```ts // app.ets import app from '@system.app' @@ -115,7 +118,7 @@ export default { console.info('Application onDestroy') }, } - ``` +``` ## app.setImageRawDataCacheSize7+ @@ -126,13 +129,14 @@ setImageRawDataCacheSize(value: number): void **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | number | 是 | 内存中解码前图片数据的缓存大小,单位为字节。 | **示例:** - ```ts +```ts // app.ets import app from '@system.app' @@ -146,7 +150,7 @@ export default { console.info('Application onDestroy') }, } - ``` +``` ## app.setImageFileCacheSize7+ @@ -157,13 +161,14 @@ setImageFileCacheSize(value: number): void **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | number | 是 | 图片文件的缓存大小,单位为字节。 | **示例:** - ```ts +```ts // app.ets import app from '@system.app' @@ -177,7 +182,7 @@ export default { console.info('Application onDestroy') }, } - ``` +``` ## AppResponse @@ -198,7 +203,7 @@ screenOnVisible(options?: ScreenOnVisibleOptions) 定义屏幕唤醒时是否保持应用可见。 -**说明:** 该接口从API Version 8 开始废弃。 +该接口从API Version 8 开始废弃。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md index e05aec4775026b954accbc578e073a4cb8ef97cc..eb8d83f1e094027bfa33fc45f11041eb30d4566b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treemap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -1,8 +1,5 @@ # @ohos.util.TreeMap (非线性容器TreeMap) -> **说明:** -> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - TreeMap可用于存储具有关联关系的key-value键值对集合,存储元素中key值唯一,每个key对应一个value。 TreeMap底层使用红黑树实现,可以利用二叉树特性快速查找键值对。key值有序存储,可以实现快速的插入和删除。 @@ -11,10 +8,16 @@ TreeMap和[HashMap](js-apis-treemap.md)相比,HashMap依据键的hashCode存 **推荐使用场景:** 一般需要存储有序键值对的场景,可以使用TreeMap。 -文档中存在泛型的使用,涉及以下泛型标记符:
-- K: Key, 键
+文档中存在泛型的使用,涉及以下泛型标记符: + +- K: Key, 键 + - V: Value, 值 +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + ## 导入模块 ```ts @@ -563,7 +566,7 @@ while(temp != undefined) { values(): IterableIterator<V> -返回包含此映射中包含的键值的新迭代器对象。 +返回包含此映射中键值对的新迭代器对象。 **系统能力:** SystemCapability.Utils.Lang @@ -609,9 +612,9 @@ forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callbackFn | function | 是 | 回调函数。 | -| thisArg | Object | 否 | callbackfn被调用时用作this值。 | +| thisArg | Object | 否 | callbackFn被调用时用作this值。 | -callbackfn的参数说明: +callbackFn的参数说明: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | V | 否 | 当前遍历到的元素键值对的值。 | @@ -642,7 +645,7 @@ treeMap.forEach((value, key) => { entries(): IterableIterator<[K, V]> -返回包含此映射中包含的键值对的新迭代器对象。 +返回包含此映射中键值对的新迭代器对象。 **系统能力:** SystemCapability.Utils.Lang @@ -680,7 +683,7 @@ while(temp != undefined) { [Symbol.iterator]\(): IterableIterator<[K, V]> -返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 +返回一个迭代器,迭代器的每一项都是一个JavaScript对象,并返回该对象。 **系统能力:** SystemCapability.Utils.Lang diff --git a/zh-cn/application-dev/reference/apis/js-apis-treeset.md b/zh-cn/application-dev/reference/apis/js-apis-treeset.md index 402ea10225fcdc632960f1fb35c4845b267f408b..5452620b579d1ae02e0ff9f695b72c0d1662b6dd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treeset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treeset.md @@ -1,17 +1,19 @@ # @ohos.util.TreeSet (非线性容器TreeSet) -> **说明:** -> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - TreeSet基于[TreeMap](js-apis-treemap.md)实现,在TreeSet中,只对value对象进行处理。TreeSet可用于存储一系列值的集合,元素中value唯一且有序。 TreeSet和[HashSet](js-apis-hashset.md)相比,HashSet中的数据无序存放,而TreeSet是有序存放。它们集合中的元素都不允许重复,但HashSet允许放入null值,TreeSet不允许。 **推荐使用场景:** 一般需要存储有序集合的场景,可以使用TreeSet。 -文档中存在泛型的使用,涉及以下泛型标记符:
+文档中存在泛型的使用,涉及以下泛型标记符: + - T: Type, 类 +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + ## 导入模块 ```ts @@ -436,7 +438,7 @@ treeSet.clear(); values(): IterableIterator<T> -返回包含此映射中包含的键值的新迭代器对象。 +返回包含此映射中键值对的新迭代器对象。 **系统能力:** SystemCapability.Utils.Lang @@ -482,13 +484,13 @@ forEach(callbackFn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisAr | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callbackFn | function | 是 | 回调函数。 | -| thisArg | Object | 否 | callbackfn被调用时用作this值。 | +| thisArg | Object | 否 | callbackFn被调用时用作this值。 | -callbackfn的参数说明: +callbackFn的参数说明: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | T | 否 | 当前遍历到的元素。 | -| key | T | 否 | 当前遍历到的元素(和value相同)。 | +| value | T | 否 | 当前遍历到的value元素。 | +| key | T | 否 | 当前遍历到的key元素。 | | set | TreeSet<T> | 否 | 当前调用forEach方法的实例对象。 | **错误码:** @@ -515,7 +517,7 @@ treeSet.forEach((value, key) => { entries(): IterableIterator<[T, T]> -返回包含此映射中包含的键值对的新迭代器对象。 +返回包含此映射中键值对的新迭代器对象。 **系统能力:** SystemCapability.Utils.Lang @@ -553,7 +555,7 @@ while(temp != undefined) { [Symbol.iterator]\(): IterableIterator<T> -返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 +返回一个迭代器,迭代器的每一项都是一个JavaScript对象,并返回该对象。 **系统能力:** SystemCapability.Utils.Lang @@ -561,7 +563,7 @@ while(temp != undefined) { | 类型 | 说明 | | -------- | -------- | -| IterableIterator<T> | 返回一个迭代器 | +| IterableIterator<T> | 返回一个迭代器。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md index 59173bfab8fb9dbe015fb04db725511890d83bf1..a3fa457f690aef1252e5e9b51ff3499f00e80244 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @@ -82,10 +82,10 @@ async function example() { console.info('fetchResult success'); let fileAsset = await fetchResult.getFirstObject(); if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); + console.info("fileAsset.displayName : " + fileAsset.displayName); } } else { - console.info('fetchResult fail' + err); + console.error('fetchResult fail' + err); } }); } @@ -136,7 +136,7 @@ async function example() { } } } catch (err) { - console.info('getPhotoAssets failed, message = ', err); + console.error('getPhotoAssets failed, message = ', err); } } ``` @@ -177,7 +177,7 @@ async function example() { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } else { - console.info('createPhotoAsset failed, message = ', err); + console.error('createPhotoAsset failed, message = ', err); } }); } @@ -211,7 +211,7 @@ async function example() { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } else { - console.info('createPhotoAsset failed, message = ', err); + console.error('createPhotoAsset failed, message = ', err); } }); } @@ -251,7 +251,7 @@ async function example() { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } catch (err) { - console.info('createPhotoAsset failed, message = ', err); + console.error('createPhotoAsset failed, message = ', err); } } ``` @@ -293,11 +293,11 @@ async function example() { if (album != undefined) { console.info('first album.albumName = ' + album.albumName); } else { - console.info('album is undefined, err = ', err); + console.error('album is undefined, err = ', err); } }); } else { - console.info('getPhotoAlbums fail, message = ', err); + console.error('getPhotoAlbums fail, message = ', err); } }); } @@ -342,7 +342,7 @@ async function example() { const album = await fetchResult.getFirstObject(); console.info('first album.albumName = ' + album.albumName); } catch (err) { - console.info('getPhotoAlbums fail, message = ' + err); + console.error('getPhotoAlbums fail, message = ' + err); } } ``` @@ -375,7 +375,7 @@ async function example() { let trashAlbum = await fetchResult.getFirstObject(); console.info('first album.albumName = ' + trashAlbum.albumName); } else { - console.info('getPrivateAlbum failed. message = ', err); + console.error('getPrivateAlbum failed. message = ', err); } }); } @@ -414,7 +414,7 @@ async function example() { let trashAlbum = await fetchResult.getFirstObject(); console.info('first album.albumName = ' + trashAlbum.albumName); } catch (err) { - console.info('getPrivateAlbum failed. message = ', err); + console.error('getPrivateAlbum failed. message = ', err); } } ``` @@ -458,7 +458,7 @@ async function example() { console.info("fileAsset.displayName :" + fileAsset.displayName); } } else { - console.info('fetchFileResult fail' + err); + console.error('fetchFileResult fail' + err); } }); } @@ -502,7 +502,7 @@ async function example() { try { var fetchResult = await mgr.getAudioAssets(fetchOptions); } catch (err) { - console.info('getAudioAssets failed, message = ', err); + console.error('getAudioAssets failed, message = ', err); } if (fetchResult != undefined) { @@ -558,7 +558,7 @@ async function example() { if (err == undefined) { console.info("delete successfully"); } else { - console.info("delete failed with error:" + err); + console.error("delete failed with error: " + err); } }); } @@ -612,7 +612,7 @@ async function example() { await mgr.delete(asset.uri); console.info("delete successfully"); } catch (err) { - console.info("delete failed with error:" + err); + console.error("delete failed with error: " + err); } } ``` @@ -648,13 +648,13 @@ async function example() { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } catch (err) { - console.info('createPhotoAsset failed, message = ' + err); + console.error('createPhotoAsset failed, message = ' + err); } //sleep 1s if (count > 0) { console.info("onDemo success"); } else { - console.info("onDemo fail"); + console.error("onDemo fail"); } mgr.off('imageChange', () => { // stop listening success @@ -698,13 +698,13 @@ async function example() { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } catch (err) { - console.info('createPhotoAsset failed, message = ' + err); + console.error('createPhotoAsset failed, message = ' + err); } //sleep 1s if (count == 0) { console.info("offDemo success"); } else { - console.info("offDemo fail"); + console.error("offDemo fail"); } } ``` @@ -735,7 +735,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('getActivePeers failed. message = ', err); + console.error('getActivePeers failed. message = ', err); } }); } @@ -763,7 +763,7 @@ async function example() { try { var devicesInfo = await mgr.getActivePeers(); } catch (err) { - console.info('getActivePeers failed. message = ', err); + console.error('getActivePeers failed. message = ', err); } if (devicesInfo != undefined) { console.log('getActivePeers succeed.'); @@ -771,7 +771,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail'); + console.error('get distributed fail'); } } ``` @@ -802,7 +802,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('getAllPeers failed. message = ', err); + console.error('getAllPeers failed. message = ', err); } }); } @@ -830,7 +830,7 @@ async function example() { try { var devicesInfo = await mgr.getAllPeers(); } catch (err) { - console.info('getAllPeers failed. message = ', err); + console.error('getAllPeers failed. message = ', err); } if (devicesInfo != undefined) { console.log('getAllPeers succeed.'); @@ -838,7 +838,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail'); + console.error('get distributed fail'); } } ``` @@ -865,7 +865,7 @@ async function example() { console.info('releaseDemo'); mgr.release((err) => { if (err != undefined) { - console.info('release failed. message = ', err); + console.error('release failed. message = ', err); } else { console.info('release ok.'); } @@ -897,7 +897,7 @@ async function example() { await mgr.release(); console.info('release ok.'); } catch (err) { - console.info('release failed. message = ', err); + console.error('release failed. message = ', err); } } ``` @@ -950,7 +950,7 @@ async function example() { let fileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); } catch (err) { - console.info('release failed. message = ', err); + console.error('release failed. message = ', err); } } ``` @@ -988,7 +988,7 @@ async function example() { let title = userFileManager.ImageVideoKey.TITLE; fileAsset.set(title.toString(), "newTitle"); } catch (err) { - console.info('release failed. message = ', err); + console.error('release failed. message = ', err); } } ``` @@ -1032,7 +1032,7 @@ async function example() { let newFileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); } else { - console.info('commitModify failed, message =', err); + console.error('commitModify failed, message =', err); } }); } @@ -1077,7 +1077,7 @@ async function example() { let newFileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); } catch (err) { - console.info('release failed. message = ', err); + console.error('release failed. message = ', err); } } ``` @@ -1114,7 +1114,7 @@ async function example() { console.info('File fd' + fd); fileAsset.close(fd); } else { - console.info('File err' + err); + console.error('File err' + err); } }); } @@ -1157,10 +1157,10 @@ async function example() { console.info('File fd' + fd); fileAsset.close(fd); } else { - console.info(' open File fail'); + console.error(' open File fail'); } } catch (err) { - console.info('open Demo err' + err); + console.error('open Demo err' + err); } } ``` @@ -1201,11 +1201,11 @@ async function example() { if (err == undefined) { console.info('asset close succeed.'); } else { - console.info('close failed, message = ' + err); + console.error('close failed, message = ' + err); } }); } catch (err) { - console.info('close failed, message = ' + err); + console.error('close failed, message = ' + err); } } ``` @@ -1250,7 +1250,7 @@ async function example() { await asset.close(fd); console.info('asset close succeed.'); } catch (err) { - console.info('close failed, message = ' + err); + console.error('close failed, message = ' + err); } } ``` @@ -1290,7 +1290,7 @@ async function example() { if (err == undefined) { console.info('getThumbnail successful ' + pixelMap); } else { - console.info('getThumbnail fail', err); + console.error('getThumbnail fail', err); } }); } @@ -1333,7 +1333,7 @@ async function example() { if (err == undefined) { console.info('getThumbnail successful ' + pixelMap); } else { - console.info('getThumbnail fail', err); + console.error('getThumbnail fail', err); } }); } @@ -1380,7 +1380,7 @@ async function example() { asset.getThumbnail(size).then((pixelMap) => { console.info('getThumbnail successful ' + pixelMap); }).catch((err) => { - console.info('getThumbnail fail' + err); + console.error('getThumbnail fail' + err); }); } ``` @@ -1420,7 +1420,7 @@ async function example() { if (err == undefined) { console.info("favorite successfully"); } else { - console.info("favorite failed with error:" + err); + console.error("favorite failed with error:" + err); } }); } @@ -1465,7 +1465,7 @@ async function example() { asset.favorite(true).then(function () { console.info("favorite successfully"); }).catch(function (err) { - console.info("favorite failed with error:" + err); + console.error("favorite failed with error:" + err); }); } ``` @@ -1568,7 +1568,7 @@ async function example() { await fetchResult.close(); console.info('close succeed.'); } catch (err) { - console.info('close fail. message = ' + err); + console.error('close fail. message = ' + err); } } ``` @@ -1604,7 +1604,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.info("fileAsset failed with err:" + err); + console.error("fileAsset failed with err:" + err); } }); } @@ -1675,7 +1675,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.info("fileAsset failed with err:" + err); + console.error("fileAsset failed with err: " + err); } }); } @@ -1748,7 +1748,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.info("fileAsset failed with err:" + err); + console.error("fileAsset failed with err: " + err); } }); } @@ -1818,7 +1818,7 @@ async function example() { if (fileAsset != undefined) { console.info('fileAsset displayName: ', fileAsset.displayName); } else { - console.info("fileAsset failed with err:" + err); + console.error("fileAsset failed with err: " + err); } }); } @@ -1915,9 +1915,9 @@ async function example() { const album = await albumList.getFirstObject(); album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { if (albumFetchResult != undefined) { - console.info("album getPhotoAssets successfully, getCount:" + albumFetchResult.getCount()); + console.info("album getPhotoAssets successfully, getCount: " + albumFetchResult.getCount()); } else { - console.info("album getPhotoAssets failed with error:" + err); + console.error("album getPhotoAssets failed with error: " + err); } }); } @@ -1958,9 +1958,9 @@ async function example() { const albumList = await mgr.getPhotoAlbums(albumFetchOptions); const album = await albumList.getFirstObject(); album.getPhotoAssets(fetchOption).then((albumFetchResult) => { - console.info("album getFileAssets successfully, getCount:" + albumFetchResult.getCount()); + console.info("album getFileAssets successfully, getCount: " + albumFetchResult.getCount()); }).catch((err) => { - console.info("album getFileAssets failed with error:" + err); + console.error("album getFileAssets failed with error: " + err); }); } ``` @@ -1997,7 +1997,7 @@ async function example() { album.albumName = 'hello'; album.commitModify((err) => { if (err != undefined) { - console.info("commitModify failed with error:" + err); + console.error("commitModify failed with error: " + err); } else { console.info("commitModify successfully"); } @@ -2035,14 +2035,14 @@ async function example() { try { var albumList = await mgr.getPhotoAlbums(albumFetchOptions); } catch (err) { - console.info('getPhotoAlbums failed. message = ', err); + console.error('getPhotoAlbums failed. message = ', err); } const album = await albumList.getFirstObject(); album.albumName = 'hello'; album.commitModify().then(() => { console.info("commitModify successfully"); }).catch((err) => { - console.info("commitModify failed with error:" + err); + console.error("commitModify failed with error: " + err); }); } ``` @@ -2099,7 +2099,7 @@ async function example() { let count = fetchResult.getCount(); console.info('fetchResult.count = ', count); } else { - console.info('getFileAssets failed, message = ', err); + console.error('getFileAssets failed, message = ', err); } }); } @@ -2182,7 +2182,7 @@ async function example() { let deleteFileUri = fileAsset.uri; trashAlbum.delete(deleteFileUri, (err) => { if (err != undefined) { - console.info('trashAlbum.delete failed, message = ', err); + console.error('trashAlbum.delete failed, message = ', err); } else { console.info('trashAlbum.delete successfully'); } @@ -2231,7 +2231,7 @@ async function example() { trashAlbum.delete(deleteFileUri).then(() => { console.info('trashAlbum.delete successfully'); }).catch((err) => { - console.info('trashAlbum.delete failed, message = ', err); + console.error('trashAlbum.delete failed, message = ', err); }); } ``` @@ -2272,7 +2272,7 @@ async function example() { let recoverFileUri = fileAsset.uri; trashAlbum.recover(recoverFileUri, (err) => { if (err != undefined) { - console.info('trashAlbum.recover failed, message = ', err); + console.error('trashAlbum.recover failed, message = ', err); } else { console.info('trashAlbum.recover successfully'); } @@ -2321,7 +2321,7 @@ async function example() { trashAlbum.recover(recoverFileUri).then(() => { console.info('trashAlbum.recover successfully'); }).catch((err) => { - console.info('trashAlbum.recover failed, message = ', err); + console.error('trashAlbum.recover failed, message = ', err); }); } ``` @@ -2402,7 +2402,7 @@ async function example() { | URI | uri | 文件uri | | DISPLAY_NAME | display_name | 显示名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | | TITLE | title | 文件标题 | | ARTIST | artist | 作者 | | AUDIOALBUM | audio_album | 专辑 | @@ -2421,7 +2421,7 @@ async function example() { | FILE_TYPE | file_type | 媒体文件类型 | | DISPLAY_NAME | display_name | 显示名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | | TITLE | title | 文件标题 | | DURATION | duration | 持续时间(单位:毫秒) | | WIDTH | width | 图片宽度(单位:像素) | @@ -2442,7 +2442,7 @@ async function example() { | FILE_TYPE | file_type | 媒体文件类型 | | ALBUM_NAME | album_name | 相册名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) | ## FetchOptions diff --git a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md index 5eb5d8ab5f6f3d8c65e074f2be1a519492a5a249..1c1bc09e3075ac28d21de64433dca8c4abbc0384 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webSocket.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webSocket.md @@ -104,6 +104,11 @@ connect\(url: string, callback: AsyncCallback\): void | url | string | 是 | 建立WebSocket连接的URL地址。 | | callback | AsyncCallback\ | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | **示例:** @@ -138,6 +143,11 @@ connect\(url: string, options: WebSocketRequestOptions, callback: AsyncCallback< | options | WebSocketRequestOptions | 是 | 参考[WebSocketRequestOptions](#websocketrequestoptions)。 | | callback | AsyncCallback\ | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | **示例:** @@ -182,6 +192,12 @@ connect\(url: string, options?: WebSocketRequestOptions\): Promise | :----------------- | :-------------------------------- | | Promise\ | 以Promise形式返回建立连接的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -213,6 +229,12 @@ send\(data: string | ArrayBuffer, callback: AsyncCallback\): void | data | string \| ArrayBuffer 8+ | 是 | 发送的数据。 | | callback | AsyncCallback\ | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -252,6 +274,12 @@ send\(data: string | ArrayBuffer\): Promise | :----------------- | :-------------------------------- | | Promise\ | 以Promise形式返回发送数据的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +|--------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -284,6 +312,12 @@ close\(callback: AsyncCallback\): void | -------- | ------------------------ | ---- | ---------- | | callback | AsyncCallback\ | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -316,6 +350,12 @@ close\(options: WebSocketCloseOptions, callback: AsyncCallback\): void | options | WebSocketCloseOptions | 是 | 参考[WebSocketCloseOptions](#websocketcloseoptions)。 | | callback | AsyncCallback\ | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|--------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -356,6 +396,12 @@ close\(options?: WebSocketCloseOptions\): Promise | :----------------- | :-------------------------------- | | Promise\ | 以Promise形式返回关闭连接的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +|--------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -388,6 +434,11 @@ on\(type: 'open', callback: AsyncCallback\): void | type | string | 是 | 'open':WebSocket的打开事件。 | | callback | AsyncCallback\ | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | **示例:** @@ -417,6 +468,12 @@ off\(type: 'open', callback?: AsyncCallback\): void | type | string | 是 | 'open':WebSocket的打开事件。 | | callback | AsyncCallback\ | 否 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -448,6 +505,11 @@ on\(type: 'message', callback: AsyncCallback\): void | type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 | | callback | AsyncCallback\8+
\> | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|--------|---------------------------| +| 401 | Parameter error. | **示例:** @@ -478,6 +540,12 @@ off\(type: 'message', callback?: AsyncCallback\): void | type | string | 是 | 'message':WebSocket的接收到服务器消息事件。 | | callback | AsyncCallback\8+
\> | 否 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js @@ -529,6 +597,11 @@ off\(type: 'close', callback?: AsyncCallback<\{ code: number, reason: string \}\ | type | string | 是 | 'close':WebSocket的关闭事件。 | | callback | AsyncCallback<{ code: number, reason: string }> | 否 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | **示例:** @@ -553,6 +626,11 @@ on\(type: 'error', callback: ErrorCallback\): void | type | string | 是 | 'error':WebSocket的Error事件。 | | callback | ErrorCallback | 是 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|-------|---------------------------| +| 401 | Parameter error. | **示例:** @@ -582,6 +660,12 @@ off\(type: 'error', callback?: ErrorCallback\): void | type | string | 是 | 'error':WebSocket的Error事件。 | | callback | ErrorCallback | 否 | 回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +|--------|---------------------------| +| 401 | Parameter error. | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-webgl.md b/zh-cn/application-dev/reference/apis/js-apis-webgl.md index 79e437f53cc4dc3b21ca70dd232eef7cf0e4d662..95a00191c78e971c6b2b49dd116096e9145ad5f7 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-webgl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webgl.md @@ -9,6 +9,8 @@ WebGL标准图形API,对应OpenGL ES 2.0特性集。更多信息请参考[WebG > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > > WebGL遵循OpenGL协议,不支持多线程调用。 +> +> 目前该功能仅支持使用兼容JS的类Web开发范式开发。 ## 调用方式 diff --git a/zh-cn/application-dev/reference/apis/js-apis-webgl2.md b/zh-cn/application-dev/reference/apis/js-apis-webgl2.md index ab16b8697067334c78e85057dfe185f02ecd33dd..c3e4cf4e3828b119796c9513e46246ce887c7592 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-webgl2.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webgl2.md @@ -9,6 +9,8 @@ WebGL标准图形API,对应OpenGL ES 3.0特性集。更多信息请参考[WebG > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > > WebGL2遵循OpenGL协议,不支持多线程调用。 +> +> 目前该功能仅支持使用兼容JS的类Web开发范式开发。 ## 调用方式 diff --git a/zh-cn/application-dev/reference/apis/js-apis-webview.md b/zh-cn/application-dev/reference/apis/js-apis-webview.md index 45b88eae96a856c63c6fd27abcf28b7ca3e651af..780887ebfd6aca0d4b003d97161855321cfaadea 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webview.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webview.md @@ -115,7 +115,7 @@ postMessageEvent(message: WebMessage): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------- | @@ -167,7 +167,7 @@ onMessageEvent(callback: (result: WebMessage) => void): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ----------------------------------------------- | @@ -278,6 +278,8 @@ static setWebDebuggingAccess(webDebuggingAccess: boolean): void | ------------------ | ------- | ---- | ------------- | | webDebuggingAccess | boolean | 是 | 设置是否启用网页调试功能。| +**示例:** + ```ts // xxx.ets import web_webview from '@ohos.web.webview'; @@ -320,7 +322,7 @@ loadUrl(url: string | Resource, headers?: Array\): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -344,6 +346,7 @@ struct WebComponent { Button('loadUrl') .onClick(() => { try { + //需要加载的URL是string类型 this.controller.loadUrl('www.example.com'); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); @@ -355,6 +358,69 @@ struct WebComponent { } ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + //带参数headers + this.controller.loadUrl('www.example.com', [{headerKey: "headerKey", headerValue: "headerValue"}]); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + .webDebuggingAccess(true) + } + } +} +``` + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + //需要加载的URL是Resource类型 + this.controller.loadUrl($rawfile('xxx.html')); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + +

Hello World

+ + +``` + ### loadData loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void @@ -375,7 +441,7 @@ loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, his **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -429,7 +495,7 @@ accessForward(): boolean **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -473,7 +539,7 @@ forward(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -522,7 +588,7 @@ accessBackward(): boolean **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -566,7 +632,7 @@ backward(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -609,7 +675,7 @@ onActive(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -652,7 +718,7 @@ onInactive(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -694,7 +760,7 @@ refresh(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -749,7 +815,7 @@ accessStep(step: number): boolean **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -794,7 +860,7 @@ clearHistory(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -843,7 +909,7 @@ getHitTest(): WebHitTestType **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -895,7 +961,7 @@ registerJavaScriptProxy(object: object, name: string, methodList: Array\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -962,7 +1028,7 @@ runJavaScript(script: string, callback : AsyncCallback\): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1030,7 +1096,7 @@ runJavaScript(script: string): Promise\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1088,7 +1154,7 @@ deleteJavaScriptRegister(name: string): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1139,7 +1205,7 @@ zoom(factor: number): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1190,7 +1256,7 @@ searchAllAsync(searchString: string): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1238,7 +1304,7 @@ clearMatches(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1287,7 +1353,7 @@ searchNext(forward: boolean): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1330,7 +1396,7 @@ clearSslCache(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1373,7 +1439,7 @@ clearClientAuthenticationCache(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1422,7 +1488,7 @@ struct WebComponent { **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1475,7 +1541,7 @@ postMessage(name: string, ports: Array\, uri: string): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1540,7 +1606,7 @@ struct WebComponent { .onClick(() => { try { if (this.ports && this.ports[1]) { - this.ports[1].postMessageEvent("post message from ets to HTML"); + this.ports[1].postMessageEvent("this.sendFromEts"); } else { console.error(`ports is null, Please initialize first`); } @@ -1626,7 +1692,7 @@ requestFocus(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1669,7 +1735,7 @@ zoomIn(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1713,7 +1779,7 @@ zoomOut(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1763,7 +1829,7 @@ getHitTestValue(): HitTestValue **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1814,7 +1880,7 @@ getWebId(): number **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1864,7 +1930,7 @@ getUserAgent(): string **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1914,7 +1980,7 @@ getTitle(): string **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -1964,7 +2030,7 @@ getPageHeight(): number **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2016,7 +2082,7 @@ storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2139,7 +2205,7 @@ getUrl(): string **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2183,7 +2249,7 @@ stop(): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2232,7 +2298,7 @@ backOrForward(step: number): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2283,7 +2349,7 @@ scrollTo(x:number, y:number): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2355,7 +2421,7 @@ scrollBy(deltaX:number, deltaY:number): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2427,7 +2493,7 @@ slideScroll(vx:number, vy:number): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2498,7 +2564,7 @@ getOriginalUrl(): string **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2548,7 +2614,7 @@ getFavicon(): image.PixelMap **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2598,7 +2664,7 @@ setNetworkAvailable(enable: boolean): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2647,7 +2713,7 @@ hasImage(callback: AsyncCallback\): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2702,7 +2768,7 @@ hasImage(): Promise\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2756,7 +2822,7 @@ removeCache(clearRom: boolean): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2805,7 +2871,7 @@ pageUp(top:boolean): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2854,7 +2920,7 @@ pageDown(bottom:boolean): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2903,7 +2969,7 @@ getBackForwardEntries(): BackForwardList **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -2952,7 +3018,7 @@ serializeWebState(): Uint8Array **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -3007,7 +3073,7 @@ restoreWebState(state: Uint8Array): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | @@ -3127,7 +3193,7 @@ static getCookie(url: string): string **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3178,7 +3244,7 @@ static setCookie(url: string, value: string): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3579,11 +3645,11 @@ static deleteOrigin(origin : string): void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------ | -| origin | string | 是 | 指定源的字符串索引. | +| origin | string | 是 | 指定源的字符串索引,来自于[getOrigins](#getorigins)。 | **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3635,7 +3701,7 @@ static getOrigins(callback: AsyncCallback\>) : void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3696,7 +3762,7 @@ static getOrigins() : Promise\> **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3758,7 +3824,7 @@ static getOriginQuota(origin : string, callback : AsyncCallback\) : void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3822,7 +3888,7 @@ static getOriginQuota(origin : string) : Promise\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3881,7 +3947,7 @@ static getOriginUsage(origin : string, callback : AsyncCallback\) : void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -3945,7 +4011,7 @@ static getOriginUsage(origin : string) : Promise\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ----------------------------------------------------- | @@ -4355,7 +4421,7 @@ static allowGeolocation(origin: string): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -4405,7 +4471,7 @@ static deleteGeolocation(origin: string): void **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | @@ -4456,7 +4522,7 @@ static getAccessibleGeolocation(origin: string, callback: AsyncCallback\ **错误码:** -以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) +以下错误码的详细介绍请参见[webview错误码](../errorcodes/errorcode-webview.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md index 4d45951c2c928a087981d6b34e096f8289356d41..31c3a192e7d0bc5449d9b4984546987f75b60a5e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md @@ -29,6 +29,14 @@ enableWifi(): void | -------- | -------- | | boolean | true:操作成功, false:操作失败。| +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| + ## wifi.disableWifi9+ @@ -48,6 +56,13 @@ disableWifi(): void | -------- | -------- | | boolean | true:操作成功, false:操作失败。| +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.isWifiActive9+ @@ -65,6 +80,13 @@ isWifiActive(): boolean | -------- | -------- | | boolean | true:已使能, false:未使能。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.scan9+ @@ -82,6 +104,13 @@ scan(): void | -------- | -------- | | boolean | true:扫描操作执行成功, false:扫描操作执行失败。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getScanResults9+ @@ -99,6 +128,13 @@ getScanResults(): Promise<Array<WifiScanInfo>> | -------- | -------- | | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise对象。返回扫描到的热点列表。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getScanResults9+ @@ -116,6 +152,14 @@ getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void | -------- | -------- | -------- | -------- | | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | 是 | 回调函数。当成功时,err为0,data为扫描到的热点;否则err为非0值,data为空。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| + **示例:** ```js import wifi from '@ohos.wifi'; @@ -249,6 +293,13 @@ getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> | -------- | -------- | |  Array<[WifiScanInfo](#wifiscaninfo)> | 扫描结果数组。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.addDeviceConfig9+ @@ -274,6 +325,14 @@ addDeviceConfig(config: WifiDeviceConfig): Promise<number> | -------- | -------- | | Promise<number> | Promise对象。返回添加的网络配置ID,如果值为-1表示添加失败。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| + ## WifiDeviceConfig9+ WLAN配置信息。 @@ -416,6 +475,13 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>) | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。当error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.addCandidateConfig9+ @@ -439,6 +505,13 @@ addCandidateConfig(config: WifiDeviceConfig): Promise<number> | -------- | -------- | | Promise<number> | Promise对象。表示网络配置ID。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.addCandidateConfig9+ @@ -457,6 +530,13 @@ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number&g | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。如果操作出现错误,err为非0值。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeCandidateConfig9+ @@ -480,6 +560,13 @@ removeCandidateConfig(networkId: number): Promise<void> | -------- | -------- | | Promise<void> | Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeCandidateConfig9+ @@ -498,6 +585,13 @@ removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): v | networkId | number | 是 | 网络配置ID。 | | callback | AsyncCallback<void> | 是 | 回调函数。当操作成功时,err为0。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getCandidateConfigs9+ @@ -515,6 +609,13 @@ getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> | -------- | -------- | |  Array<[WifiDeviceConfig](#wifideviceconfig)> | 候选网络配置数组。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.connectToCandidateConfig9+ @@ -532,6 +633,14 @@ connectToCandidateConfig(networkId: number): void | -------- | -------- | -------- | -------- | | networkId | number | 是 | 候选网络配置的ID。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.connectToNetwork9+ @@ -551,12 +660,14 @@ connectToNetwork(networkId: number): void | -------- | -------- | -------- | -------- | | networkId | number | 是 | 待连接的网络配置ID。 | -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.connectToDevice9+ @@ -577,12 +688,14 @@ connectToDevice(config: WifiDeviceConfig): void | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.disconnect9+ @@ -597,12 +710,13 @@ disconnect(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getSignalLevel9+ @@ -627,6 +741,13 @@ getSignalLevel(rssi: number, band: number): number | -------- | -------- | | number | 信号强度,取值范围为[0, 4]。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getLinkedInfo9+ @@ -644,6 +765,14 @@ getLinkedInfo(): Promise<WifiLinkedInfo> | -------- | -------- | | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise对象。表示WLAN连接信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.getLinkedInfo9+ @@ -661,6 +790,15 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| + **示例:** ```js import wifi from '@ohos.wifi'; @@ -765,6 +903,13 @@ isConnected(): boolean | -------- | -------- | | boolean | true:已连接, false:未连接。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getSupportedFeatures9+ @@ -799,6 +944,13 @@ getSupportedFeatures(): number | 0x10000000 | WPA3-Enterprise Suite-B | | 0x20000000 | 增强开放特性。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2401000 | Operation failed.| ## wifi.isFeatureSupported9+ @@ -823,6 +975,13 @@ isFeatureSupported(featureId: number): boolean | -------- | -------- | | boolean | true:支持, false:不支持。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2401000 | Operation failed.| ## wifi.getDeviceMacAddress9+ @@ -842,6 +1001,13 @@ getDeviceMacAddress(): string[] | -------- | -------- | | string[] | MAC地址。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getIpInfo9+ @@ -859,6 +1025,13 @@ getIpInfo(): IpInfo | -------- | -------- | | [IpInfo](#ipinfo9) | IP信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## IpInfo9+ @@ -893,6 +1066,13 @@ getCountryCode(): string | -------- | -------- | | string | 国家码。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2401000 | Operation failed.| ## wifi.reassociate9+ @@ -906,12 +1086,14 @@ reassociate(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.reconnect9+ @@ -925,12 +1107,14 @@ reconnect(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.getDeviceConfigs9+ @@ -950,6 +1134,13 @@ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> | -------- | -------- | |  Array<[WifiDeviceConfig](#wifideviceconfig)> | 网络配置信息的数组。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.updateNetwork9+ @@ -975,6 +1166,13 @@ updateNetwork(config: WifiDeviceConfig): number | -------- | -------- | | number | 返回更新的网络配置ID,如果值为-1表示更新失败。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.disableNetwork9+ @@ -994,12 +1192,13 @@ disableNetwork(netId: number): void | -------- | -------- | -------- | -------- | | netId | number | 是 | 网络配置ID。 | -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeAllNetwork9+ @@ -1013,12 +1212,13 @@ removeAllNetwork(): void **系统能力:** SystemCapability.Communication.WiFi.STA -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeDevice9+ @@ -1038,12 +1238,13 @@ removeDevice(id: number): void | -------- | -------- | -------- | -------- | | id | number | 是 | 网络配置ID。 | -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.enableHotspot9+ @@ -1057,12 +1258,13 @@ enableHotspot(): void **系统能力:** SystemCapability.Communication.WiFi.AP.Core -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。| +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.disableHotspot9+ @@ -1076,12 +1278,13 @@ disableHotspot(): void **系统能力:** SystemCapability.Communication.WiFi.AP.Core -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。| +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.isHotspotDualBandSupported9+ @@ -1099,8 +1302,15 @@ isHotspotDualBandSupported(): boolean | **类型** | **说明** | | -------- | -------- | - | boolean | true:支持, false:不支持。| + | boolean | true:支持, false:不支持.| +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.isHotspotActive9+ @@ -1118,8 +1328,15 @@ isHotspotActive(): boolean | **类型** | **说明** | | -------- | -------- | - | boolean | true:已使能, false:未使能。| + | boolean | true:已使能, false:未使能.| + +**错误码:** +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.setHotspotConfig9+ @@ -1139,12 +1356,13 @@ setHotspotConfig(config: HotspotConfig): void | -------- | -------- | -------- | -------- | | config | [HotspotConfig](#hotspotconfig9) | 是 | 热点配置信息。 | -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## HotspotConfig9+ @@ -1181,6 +1399,13 @@ getHotspotConfig(): HotspotConfig | -------- | -------- | | [HotspotConfig](#hotspotconfig9) | 热点的配置信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.getStations9+ @@ -1200,6 +1425,13 @@ getStations():  Array<[StationInfo](#stationinfo9)> | -------- | -------- | |  Array<[StationInfo](#stationinfo9)> | 连接的设备数组。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## StationInfo9+ @@ -1232,7 +1464,13 @@ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> | -------- | -------- | | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise对象。表示P2P连接信息。 | +**错误码:** +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2pLinkedInfo9+ @@ -1292,6 +1530,13 @@ getCurrentGroup(): Promise<WifiP2pGroupInfo> | -------- | -------- | | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise对象。表示当前组信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getCurrentGroup9+ @@ -1309,6 +1554,13 @@ getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pPeerDevices9+ @@ -1326,6 +1578,13 @@ getP2pPeerDevices(): Promise<WifiP2pDevice[]> | -------- | -------- | | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise对象。表示对端设备列表信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pPeerDevices9+ @@ -1343,6 +1602,13 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2pDevice9+ @@ -1390,6 +1656,13 @@ getP2pLocalDevice(): Promise<WifiP2pDevice> | -------- | -------- | | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise对象。表示本端设备信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pLocalDevice9+ @@ -1424,12 +1697,13 @@ createGroup(config: WifiP2PConfig): void | -------- | -------- | -------- | -------- | | config | [WifiP2PConfig](#wifip2pconfig9) | 是 | 群组配置信息。 | -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:创建群组操作执行成功, false:创建群组操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2PConfig9+ @@ -1469,12 +1743,13 @@ removeGroup(): void **系统能力:** SystemCapability.Communication.WiFi.P2P -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:操作执行成功, false:操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.p2pConnect9+ @@ -1493,12 +1768,13 @@ p2pConnect(config: WifiP2PConfig): void | -------- | -------- | -------- | -------- | | config | [WifiP2PConfig](#wifip2pconfig9) | 是 | 连接配置信息。 | -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:操作执行成功, false:操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| **示例:** ```js @@ -1577,12 +1853,13 @@ p2pCancelConnect(): void **系统能力:** SystemCapability.Communication.WiFi.P2P -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:操作执行成功, false:操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.startDiscoverDevices9+ @@ -1594,12 +1871,13 @@ startDiscoverDevices(): void **系统能力:** SystemCapability.Communication.WiFi.P2P -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:操作执行成功, false:操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.stopDiscoverDevices9+ @@ -1611,12 +1889,13 @@ stopDiscoverDevices(): void **系统能力:** SystemCapability.Communication.WiFi.P2P -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:操作执行成功,操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.deletePersistentGroup9+ @@ -1637,12 +1916,13 @@ deletePersistentGroup(netId: number): void | -------- | -------- | -------- | -------- | | netId | number | 是 | 组的ID。 | -**返回值:** +**错误码:** - | 类型 | 说明 | - | -------- | -------- | - | boolean | true:操作执行成功,操作执行失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pGroups9+ @@ -1662,6 +1942,13 @@ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> | -------- | -------- | | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise对象。表示所有群组信息。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2pGroupInfo9+ @@ -1700,6 +1987,13 @@ getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void | -------- | -------- | -------- | -------- | | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | 是 | 回调函数。当操作成功时,err为0,data表示所有群组信息。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.setDeviceName9+ @@ -1719,12 +2013,13 @@ setDeviceName(devName: string): void | -------- | -------- | -------- | -------- | | devName | string | 是 | 设备名称。 | -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | true:操作成功, false:操作失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('wifiStateChange')9+ @@ -1743,6 +2038,14 @@ on(type: "wifiStateChange", callback: Callback<number>): void | type | string | 是 | 固定填"wifiStateChange"字符串。 | | callback | Callback<number> | 是 | 状态改变回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| + **状态改变事件的枚举:** | **枚举值** | **说明** | @@ -1770,6 +2073,14 @@ off(type: "wifiStateChange", callback?: Callback<number>): void | type | string | 是 | 固定填"wifiStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| + **示例:** ```js import wifi from '@ohos.wifi'; @@ -1810,6 +2121,13 @@ on(type: "wifiConnectionChange", callback: Callback<number>): void | 0 | 已断开。 | | 1 | 已连接。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.off('wifiConnectionChange')9+ @@ -1828,6 +2146,13 @@ off(type: "wifiConnectionChange", callback?: Callback<number>): void | type | string | 是 | 固定填"wifiConnectionChange"字符串。 | | callback | Callback<number> | 否 | 连接状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.on('wifiScanStateChange')9+ @@ -1853,6 +2178,13 @@ on(type: "wifiScanStateChange", callback: Callback<number>): void | 0 | 扫描失败。 | | 1 | 扫描成功。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.off('wifiScanStateChange')9+ @@ -1871,6 +2203,13 @@ off(type: "wifiScanStateChange", callback?: Callback<number>): void | type | string | 是 | 固定填"wifiScanStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.on('wifiRssiChange')9+ @@ -1889,6 +2228,13 @@ on(type: "wifiRssiChange", callback: Callback<number>): void | type | string | 是 | 固定填"wifiRssiChange"字符串。 | | callback | Callback<number> | 是 | 状态改变回调函数,返回以dBm为单位的RSSI值。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.off('wifiRssiChange')9+ @@ -1907,6 +2253,13 @@ off(type: "wifiRssiChange", callback?: Callback<number>): void | type | string | 是 | 固定填"wifiRssiChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.on('hotspotStateChange')9+ @@ -1934,6 +2287,13 @@ on(type: "hotspotStateChange", callback: Callback<number>): void | 2 | 激活中。 | | 3 | 去激活中。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.off('hotspotStateChange')9+ @@ -1952,6 +2312,13 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void | type | string | 是 | 固定填"hotspotStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.on('p2pStateChange')9+ @@ -1980,6 +2347,14 @@ on(type: "p2pStateChange", callback: Callback<number>): void | 4 | 关闭中。 | | 5 | 已关闭。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| + ## wifi.off('p2pStateChange')9+ off(type: "p2pStateChange", callback?: Callback<number>): void @@ -1997,6 +2372,13 @@ off(type: "p2pStateChange", callback?: Callback<number>): void | type | string | 是 | 固定填"p2pStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pConnectionChange')9+ @@ -2015,6 +2397,13 @@ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): vo | type | string | 是 | 固定填"p2pConnectionChange"字符串。 | | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | 是 | 状态改变回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pConnectionChange')9+ @@ -2033,6 +2422,13 @@ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): | type | string | 是 | 固定填"p2pConnectionChange"字符串。 | | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pDeviceChange')9+ @@ -2051,6 +2447,13 @@ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void | type | string | 是 | 固定填"p2pDeviceChange"字符串。 | | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | 是 | 状态改变回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pDeviceChange')9+ @@ -2069,6 +2472,13 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void | type | string | 是 | 固定填"p2pDeviceChange"字符串。 | | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pPeerDeviceChange')9+ @@ -2087,6 +2497,13 @@ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void | type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | 是 | 状态改变回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pPeerDeviceChange')9+ @@ -2105,6 +2522,13 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo | type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pPersistentGroupChange')9+ @@ -2123,6 +2547,13 @@ on(type: "p2pPersistentGroupChange", callback: Callback<void>): void | type | string | 是 | 固定填"p2pPersistentGroupChange"字符串。 | | callback | Callback<void> | 是 | 状态改变回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pPersistentGroupChange')9+ @@ -2141,6 +2572,13 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void | type | string | 是 | 固定填"p2pPersistentGroupChange"字符串。 | | callback | Callback<void> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pDiscoveryChange')9+ @@ -2166,6 +2604,13 @@ on(type: "p2pDiscoveryChange", callback: Callback<number>): void | 0 | 初始状态。 | | 1 | 发现成功。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pDiscoveryChange')9+ @@ -2184,3 +2629,10 @@ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void | type | string | 是 | 固定填"p2pDiscoveryChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2801000 | Operation failed.| diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md index 637f78a84d484b85fe27b31c49750b5d3eaab35a..6b973ac78d449daa3d32e2a7c28da46a5115202e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -22,12 +22,13 @@ enableHotspot(): boolean; **系统能力:** SystemCapability.Communication.WiFi.AP.Extension -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | 操作结果, true: 成功, false: 失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.disableHotspot @@ -39,12 +40,13 @@ disableHotspot(): boolean; **系统能力:** SystemCapability.Communication.WiFi.AP.Extension -**返回值:** +**错误码:** - | **类型** | **说明** | - | -------- | -------- | - | boolean | 操作结果, true: 成功, false: 失败。 | +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 +| **类型** | **说明** | + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.getSupportedPowerModel @@ -62,6 +64,13 @@ getSupportedPowerModel(): Promise<Array<PowerModel>> | -------- | -------- | | Promise<Array<[PowerModel](#powermodel)>> | Promise对象。表示功率模式。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2701000 | Operation failed.| ## PowerModel @@ -92,6 +101,13 @@ getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | 是 | 回调函数。当操作成功时,err为0,data表示支持的功率模式。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.getPowerModel @@ -109,6 +125,13 @@ getPowerModel(): Promise<PowerModel> | -------- | -------- | | Promise<[PowerModel](#powermodel)> | Promise对象。表示功率模式。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.getPowerModel @@ -126,6 +149,13 @@ getPowerModel(callback: AsyncCallback<PowerModel>): void | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[PowerModel](#powermodel)> | 是 | 回调函数。当操作成功时,err为0,data表示功率模式。如果error为非0,表示处理出现错误。 | +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **类型** | **说明** | + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.setPowerModel @@ -143,8 +173,10 @@ setPowerModel(model: PowerModel) : boolean; | -------- | -------- | -------- | -------- | | model | [PowerModel](#powermodel) | 是 | 功率模式。 | -**返回值:** +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 - | **类型** | **说明** | +| **类型** | **说明** | | -------- | -------- | - | boolean | 操作结果, true: 成功, false: 失败。 | +| 2701000 | Operation failed.| diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index ba74712186d850dfa65d80583c2cad657e5a4a4b..e80202ae57e2d9f1059041bc6888c02ca9a9245a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -839,7 +839,7 @@ create(id: string, type: WindowType, callback: AsyncCallback<Window>): voi 创建子窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[createWindow()](#windowcreatewindow9)。 **模型约束:** 此接口仅可在FA模型下使用。 @@ -875,7 +875,7 @@ create(id: string, type: WindowType): Promise<Window> 创建子窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[createWindow()](#windowcreatewindow9-1)。 **模型约束:** 此接口仅可在FA模型下使用。 @@ -915,7 +915,7 @@ create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback&l 创建系统窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[createWindow()](#windowcreatewindow9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -951,7 +951,7 @@ create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> 创建系统窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[createWindow()](#windowcreatewindow9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -990,7 +990,7 @@ find(id: string, callback: AsyncCallback<Window>): void 查找id所对应的窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[findWindow()](#windowfindwindow9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -1023,7 +1023,7 @@ find(id: string): Promise<Window> 查找id所对应的窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[findWindow()](#windowfindwindow9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -1060,7 +1060,7 @@ getTopWindow(callback: AsyncCallback<Window>): void 获取当前应用内最后显示的窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[getLastWindow()](#windowgetlastwindow9)。 **模型约束:** 此接口仅可在FA模型下使用。 @@ -1094,7 +1094,7 @@ getTopWindow(): Promise<Window> 获取当前应用内最后显示的窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[getLastWindow()](#windowgetlastwindow9-1)。 **模型约束:** 此接口仅可在FA模型下使用。 @@ -1127,7 +1127,7 @@ getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void 获取当前应用内最后显示的窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[getLastWindow()](#windowgetlastwindow9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -1160,7 +1160,7 @@ getTopWindow(ctx: BaseContext): Promise<Window> 获取当前应用内最后显示的窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[getLastWindow()](#windowgetlastwindow9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2998,6 +2998,154 @@ try { } ``` +### bindDialogTarget9+ + +bindDialogTarget(requestInfo: dialogRequest.RequestInfo, deathCallback: Callback<void>, callback: AsyncCallback<void>): void + +绑定模态窗口与目标窗口并添加模态窗口销毁监听,使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------------------------- | ---- | -------------------- | +| requestInfo | [dialogRequest.RequestInfo](js-apis-app-ability-dialogRequest.md#requestinfo) | 是 | 目标窗口RequestInfo值。 | +| deathCallback | Callback<void> | 是 | 模态窗口销毁监听。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**示例:** + +```js +import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; +import rpc from '@ohos.rpc'; +import dialogRequest from '@ohos.app.ability.dialogRequest'; +import window from '@ohos.window'; + +export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info('onCreate'); + } + + onRequest(want, startId) { + console.info('onRequest'); + try { + let requestInfo = dialogRequest.getRequestInfo(want) + windowClass.bindDialogTarget(requestInfo, () => { + console.info('Dialog Window Need Destroy.'); + }, (err) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target.'); + }); + } catch(err) { + console.error('getRequestInfo err = ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info('onConnect'); + } + + onDisconnect(want) { + console.info('onDisconnect'); + } + + onDestroy() { + console.info('onDestroy'); + } +} +``` + +### bindDialogTarget9+ + +bindDialogTarget(requestInfo: dialogRequest.RequestInfo, deathCallback: Callback<void>): Promise<void> + +绑定模态窗口与目标窗口并添加模态窗口销毁监听,使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------------------------- | ---- | -------------------- | +| requestInfo | [dialogRequest.RequestInfo](js-apis-app-ability-dialogRequest.md#requestinfo) | 是 | 目标窗口RequestInfo值。 | +| deathCallback | Callback<void> | 是 | 模态窗口销毁监听。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**示例:** + +```js +import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; +import rpc from '@ohos.rpc'; +import dialogRequest from '@ohos.app.ability.dialogRequest'; +import window from '@ohos.window'; + +export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info('onCreate'); + } + + onRequest(want, startId) { + console.info('onRequest'); + try { + let requestInfo = dialogRequest.getRequestInfo(want) + let promise = windowClass.bindDialogTarget(requestInfo, () => { + console.info('Dialog Window Need Destroy.'); + }); + promise.then(()=> { + console.info('Succeeded in binding dialog target.'); + }).catch((err)=>{ + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + }); + } catch(err) { + console.error('getRequestInfo err = ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info('onConnect'); + } + + onDisconnect(want) { + console.info('onDisconnect'); + } + + onDestroy() { + console.info('onDestroy'); + } +} +``` + ### isWindowSupportWideGamut9+ isWindowSupportWideGamut(callback: AsyncCallback<boolean>): void @@ -4065,7 +4213,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { playMode: PlayMode.Normal, // 动画模式 onFinish: ()=> { context.completeTransition(true) - } + } }, () => { let obj : window.TranslateOptions = { x : 100.0, @@ -4265,6 +4413,253 @@ try { } ``` +### raiseToAppTop10+ + +raiseToAppTop(callback: AsyncCallback<void>): void + +提升应用子窗口到应用顶层。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | +| 1300009 | The parent window is invalid. | + +**示例:** + +```js +windowClass.raiseToAppTop((err) => { + if (err.code) { + console.error('Failed to raise the window to app top. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in raising the window to app top.'); +}); +``` + +### raiseToAppTop10+ + +raiseToAppTop(): Promise<void> + +提升应用子窗口到应用顶层。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | +| 1300009 | The parent window is invalid. | + +**示例:** + +```js +let promise = windowClass.raiseToAppTop(); +promise.then(()=> { + console.info('Succeeded in raising the window to app top.'); +}).catch((err)=>{ + console.error('Failed to raise the window to app top. Cause: ' + JSON.stringify(err)); +}); +``` +### setAspectRatio10+ + +setAspectRatio(ratio: number): Promise<void> + +设置窗口内容布局的比例,使用Promise异步回调。 + +仅应用主窗口支持此接口功能,比例参数将持久化保存,关闭应用或重启设备设置的比例仍然生效。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| ratio | number | 是 | 除边框装饰之外的窗口内容布局的宽高比,取值范围为大于0。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**示例:** + +```js +try { + let ratio = 1.0; + let promise = windowClass.setAspectRatio(ratio); + promise.then(()=> { + console.info('Succeeded in setting aspect ratio of window.'); + }).catch((err)=>{ + console.error('Failed to set the aspect ratio of window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} +``` + +### setAspectRatio10+ + +setAspectRatio(ratio: number, callback: AsyncCallback<void>): void + +设置窗口内容布局的比例,使用callback异步回调。 + +仅应用主窗口支持此接口功能,比例参数将持久化保存,关闭应用或重启设备设置的比例仍然生效。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| ratio | number | 是 | 除边框装饰之外的窗口内容布局的宽高比,取值范围为大于0。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**示例:** + +```js +try { + let ratio = 1.0; + windowClass.setAspectRatio(ratio, (err) => { + if (err.code) { + console.error('Failed to set the aspect ratio of window. Cause:' + JSON.stringify(err)); + return; + } + console.error('Failed to set the aspect ratio of window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} +``` + +### resetAspectRatio10+ + +resetAspectRatio(): Promise<void> + +取消设置窗口内容布局的比例,使用Promise异步回调。 + +仅应用主窗口支持此接口功能,调用后将清除持久化储存的比例信息。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**示例:** + +```js +try { + let promise = windowClass.resetAspectRatio(); + promise.then(()=> { + console.info('Succeeded in resetting aspect ratio of window.'); + }).catch((err)=>{ + console.error('Failed to reset the aspect ratio of window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to reset the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} +``` + +### resetAspectRatio10+ + +resetAspectRatio(callback: AsyncCallback<void>): void + +取消设置窗口内容布局的比例,使用callback异步回调。 + +仅应用主窗口支持此接口功能,调用后将清除持久化储存的比例信息。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------------ | ------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**示例:** + +```js +try { + windowClass.resetAspectRatio((err) => { + if (err.code) { + console.error('Failed to reset the aspect ratio of window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in resetting aspect ratio of window.'); + }); +} catch (exception) { + console.error('Failed to reset the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} +``` + ### show(deprecated) show(callback: AsyncCallback<void>): void @@ -4272,7 +4667,7 @@ show(callback: AsyncCallback<void>): void 显示当前窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[showWindow()](#showwindow9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4302,7 +4697,7 @@ show(): Promise<void> 显示当前窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[showWindow()](#showwindow9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4331,7 +4726,7 @@ destroy(callback: AsyncCallback<void>): void 销毁当前窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[destroyWindow()](#destroywindow9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4361,7 +4756,7 @@ destroy(): Promise<void> 销毁当前窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[destroyWindow()](#destroywindow9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4392,7 +4787,7 @@ moveTo(x: number, y: number, callback: AsyncCallback<void>): void 全屏模式窗口不支持该操作。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[moveWindowTo()](#movewindowto9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4426,7 +4821,7 @@ moveTo(x: number, y: number): Promise<void> 全屏模式窗口不支持该操作。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[moveWindowTo()](#movewindowto9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4470,7 +4865,7 @@ resetSize(width: number, height: number, callback: AsyncCallback<void>): v 全屏模式窗口不支持该操作。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[resize()](#resize9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4510,7 +4905,7 @@ resetSize(width: number, height: number): Promise<void> 全屏模式窗口不支持该操作。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[resize()](#resize9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4548,7 +4943,7 @@ setWindowType(type: WindowType, callback: AsyncCallback<void>): void **系统接口:** 此接口为系统接口。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4582,7 +4977,7 @@ setWindowType(type: WindowType): Promise<void> **系统接口:** 此接口为系统接口。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4618,7 +5013,7 @@ getProperties(callback: AsyncCallback<WindowProperties>): void 获取当前窗口的属性,使用callback异步回调,返回WindowProperties。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[getWindowProperties()](#getwindowproperties9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4648,7 +5043,7 @@ getProperties(): Promise<WindowProperties> 获取当前窗口的属性,使用Promise异步回调,返回WindowProperties。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[getWindowProperties()](#getwindowproperties9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4677,7 +5072,7 @@ getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback< 获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[getWindowAvoidArea()](#getwindowavoidarea9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4709,7 +5104,7 @@ getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#av 获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[getWindowAvoidArea()](#getwindowavoidarea9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4745,7 +5140,7 @@ setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void 设置是否为全屏状态,使用callback异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowSystemBarEnable()](#setwindowsystembarenable9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4777,7 +5172,7 @@ setFullScreen(isFullScreen: boolean): Promise<void> 设置是否为全屏状态,使用Promise异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowSystemBarEnable()](#setwindowsystembarenable9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4813,7 +5208,7 @@ setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void 设置窗口的布局是否为全屏显示状态,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowLayoutFullScreen()](#setwindowlayoutfullscreen9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4845,7 +5240,7 @@ setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> 设置窗口的布局是否为全屏显示状态,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowLayoutFullScreen()](#setwindowlayoutfullscreen9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4881,7 +5276,7 @@ setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallbac 设置导航栏、状态栏的可见模式,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowSystemBarEnable()](#setwindowsystembarenable9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4914,7 +5309,7 @@ setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> 设置导航栏、状态栏的可见模式,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowSystemBarEnable()](#setwindowsystembarenable9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4951,7 +5346,7 @@ setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: Async 设置窗口内导航栏、状态栏的属性,使用callback异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowSystemBarProperties()](#setwindowsystembarproperties9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4989,7 +5384,7 @@ setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<voi 设置窗口内导航栏、状态栏的属性,使用Promise异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowSystemBarProperties()](#setwindowsystembarproperties9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5031,7 +5426,7 @@ loadContent(path: string, callback: AsyncCallback<void>): void 为当前窗口加载具体页面内容,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setUIContent()](#setuicontent9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5062,7 +5457,7 @@ loadContent(path: string): Promise<void> 为当前窗口加载具体页面内容,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setUIContent()](#setuicontent9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5097,7 +5492,7 @@ isShowing(callback: AsyncCallback<boolean>): void 判断当前窗口是否已显示,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[isWindowShowing()](#iswindowshowing9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5127,7 +5522,7 @@ isShowing(): Promise<boolean> 判断当前窗口是否已显示,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[isWindowShowing()](#iswindowshowing9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5156,7 +5551,7 @@ on(type: 'systemAvoidAreaChange', callback: Callback<AvoidArea>): void 开启系统规避区变化的监听。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[on('avoidAreaChange')](#onavoidareachange9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5183,7 +5578,7 @@ off(type: 'systemAvoidAreaChange', callback?: Callback<AvoidArea>): void 关闭系统规避区变化的监听。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[off('avoidAreaChange')](#offavoidareachange9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5208,7 +5603,7 @@ isSupportWideGamut(callback: AsyncCallback<boolean>): void 判断当前窗口是否支持广色域模式,使用callback异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[isWindowSupportWideGamut()](#iswindowsupportwidegamut9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5238,7 +5633,7 @@ isSupportWideGamut(): Promise<boolean> 判断当前窗口是否支持广色域模式,使用Promise异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[isWindowSupportWideGamut()](#iswindowsupportwidegamut9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5267,7 +5662,7 @@ setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void 设置当前窗口为广色域模式或默认色域模式,使用callback异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[setWindowColorSpace()](#setwindowcolorspace9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5298,7 +5693,7 @@ setColorSpace(colorSpace:ColorSpace): Promise<void> 设置当前窗口为广色域模式或默认色域模式,使用Promise异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[setWindowColorSpace()](#setwindowcolorspace9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5333,7 +5728,7 @@ getColorSpace(callback: AsyncCallback<ColorSpace>): void 获取当前窗口色域模式,使用callback异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[getWindowColorSpace()](#getwindowcolorspace9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5363,7 +5758,7 @@ getColorSpace(): Promise<ColorSpace> 获取当前窗口色域模式,使用Promise异步回调。 > **说明:** -> +> > 从 API version 8开始支持,从API version 9开始废弃,推荐使用[getWindowColorSpace()](#getwindowcolorspace9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5392,7 +5787,7 @@ setBackgroundColor(color: string, callback: AsyncCallback<void>): void 设置窗口的背景色,使用callback异步回调。Stage模型下,该接口需要在[loadContent](#loadcontent9)或[setUIContent()](#setuicontent9)之后使用。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowBackgroundColor()](#setwindowbackgroundcolor9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5424,7 +5819,7 @@ setBackgroundColor(color: string): Promise<void> 设置窗口的背景色,使用Promise异步回调。Stage模型下,该接口需要在[loadContent](#loadcontent9)或[setUIContent()](#setuicontent9)之后使用。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowBackgroundColor()](#setwindowbackgroundcolor9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5460,7 +5855,7 @@ setBrightness(brightness: number, callback: AsyncCallback<void>): void 设置屏幕亮度值,使用callback异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowBrightness()](#setwindowbrightness9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5492,7 +5887,7 @@ setBrightness(brightness: number): Promise<void> 设置屏幕亮度值,使用Promise异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowBrightness()](#setwindowbrightness9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5528,7 +5923,7 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void 窗口叠加时,设备有子窗口的情况下设置靠后的窗口的暗度值,使用callback异步回调。 > **说明:** -> +> > 该接口不支持使用。从 API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5559,7 +5954,7 @@ setDimBehind(dimBehindValue: number): Promise<void> 窗口叠加时,设备有子窗口的情况下设置靠后的窗口的暗度值,使用Promise异步回调。 > **说明:** -> +> > 该接口不支持使用。从 API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5594,7 +5989,7 @@ setFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void 设置点击时是否支持切换焦点窗口,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowFocusable()](#setwindowfocusable9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5626,7 +6021,7 @@ setFocusable(isFocusable: boolean): Promise<void> 设置点击时是否支持切换焦点窗口,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowFocusable()](#setwindowfocusable9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5662,7 +6057,7 @@ setKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): v 设置屏幕是否为常亮状态,使用callback异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowKeepScreenOn()](#setwindowkeepscreenon9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5694,7 +6089,7 @@ setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> 设置屏幕是否为常亮状态,使用Promise异步回调。 > **说明:** -> +> > 从 API version 6开始支持,从API version 9开始废弃,推荐使用[setWindowKeepScreenOn()](#setwindowkeepscreenon9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5730,7 +6125,7 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): vo 设置是否允许可点击子窗口之外的区域,使用callback异步回调。 > **说明:** -> +> > 该接口不支持使用。从 API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5761,7 +6156,7 @@ setOutsideTouchable(touchable: boolean): Promise<void> 设置是否允许可点击子窗口之外的区域,使用Promise异步回调。。 > **说明:** -> +> > 该接口不支持使用。从 API version 7开始支持,从API version 9开始废弃。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5796,7 +6191,7 @@ setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): voi 设置窗口是否为隐私模式,使用callback异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowPrivacyMode()](#setwindowprivacymode9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5828,7 +6223,7 @@ setPrivacyMode(isPrivacyMode: boolean): Promise<void> 设置窗口是否为隐私模式,使用Promise异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowPrivacyMode()](#setwindowprivacymode9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5864,7 +6259,7 @@ setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void 设置窗口是否为可触状态,使用callback异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowTouchable()](#setwindowtouchable9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5896,7 +6291,7 @@ setTouchable(isTouchable: boolean): Promise<void> 设置窗口是否为可触状态,使用Promise异步回调。 > **说明:** -> +> > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[setWindowTouchable()](#setwindowtouchable9-1)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -6724,7 +7119,7 @@ controller.animationForShown = (context : window.TransitionContext) => { playMode: PlayMode.Normal, // 动画模式 onFinish: ()=> { context.completeTransition(true) - } + } }, () => { let obj : window.TranslateOptions = { x : 100.0, @@ -6770,7 +7165,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { playMode: PlayMode.Normal, // 动画模式 onFinish: ()=> { context.completeTransition(true) - } + } }, () => { let obj : window.TranslateOptions = { x : 100.0, diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-common-mediaquery.md b/zh-cn/application-dev/reference/arkui-js/js-components-common-mediaquery.md index 7df435b4a48c3b2292055637a837acb7498ec269..874bda123dc414f535574fa14ea5b1fb1237a369 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-common-mediaquery.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-common-mediaquery.md @@ -109,9 +109,9 @@ | dark-mode6+ | 系统为深色模式时为true,否则为false。 | -## 示例代码 +## 通用媒体特征示例代码 -- 通用媒体特征示例代码(多个.container中的所写的属性个数以及类型需要相同,若不相同会导致显示异常): +多个.container中的所写的属性个数以及类型需要相同,若不相同会导致显示异常。 ```html diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index 74c48383609667735a7bd7a1ef1e9adf97f80a00..23ee9d666a1cb8a15ca1edb1db80957ed70c23f6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -19,6 +19,7 @@ DatePicker(options?: {start?: Date, end?: Date, selected?: Date}) 根据指定范围的Date创建可以选择日期的滑动选择器。 **参数:** + | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | ------------- | -------- | | start | Date | 否 | 指定选择器的起始日期。
默认值:Date('1970-1-1') | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index bc6a54e414a7fff721138d60240d8f28cdaf3335..2856ea7dd00b07f36b009b66db67ec7642084244 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -53,7 +53,7 @@ Image(src: string | PixelMap | Resource) > **说明:** > > 使用快捷组合键对Image组件复制的前提是,该组件必须处于获焦状态。将Image组件的属性focusable设置为true,即可使用TAB键将焦点切换到Image组件上,再将Image组件的focusOnTouch属性设置为true,即可实现点击获焦。 -> 图片设置svg图源时,支持的标签范围有限,目前支持的svg标签包括svg、rect、circle、ellipse、path、line、polyline、polygon、animate、animateMotion、animateTransform。 +> 图片设置svg图源时,支持的标签范围有限,目前支持的svg标签包括svg、rect、circle、ellipse、path、line、polyline、polygon、animate。 ### ImageInterpolation diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md index 52f18fce48e8bf6c8c2cd2db419771cb3af3996c..a378f85c11918c041547ec2067becc5f7e45c0b9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md @@ -19,11 +19,13 @@ RemoteWindow(target: WindowAnimationTarget) 通过窗口动画对象创建组件。 **参数:** + | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | --------------- | -------- | | target | [WindowAnimationTarget](#windowanimationtarget) | 是 | 需要控制的动画窗口的描述。 | ## WindowAnimationTarget + 目标窗口,用来远程控制实现动画。 | 参数 | 类型 | 描述 | @@ -34,6 +36,7 @@ RemoteWindow(target: WindowAnimationTarget) | missionId | number | 任务ID。| ## RRect + 圆角矩形。 | 参数 | 类型 | 描述 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md index b300a6a2ab18d2453b685c998e9059eb7466a8eb..fe680d987c2ac0dcea2deba8d22b63c0ba34f4bd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md @@ -25,6 +25,7 @@ ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: B | state | [BarState](ts-appendix-enums.md#barstate) | 否 | 滚动条状态。
默认值:BarState.Auto | > **说明:** +> > ScrollBar组件负责定义可滚动区域的行为样式,ScrollBar的子节点负责定义滚动条的行为样式。 > > 滚动条组件与可滚动组件通过Scroller进行绑定,且只有当两者方向相同时,才能联动,ScrollBar与可滚动组件仅支持一对一绑定。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md index 647260276e3dba7f7954b38e0fe5d3ca2d557875..c8d7d5482648345ceedf04c6b5036ed2b6655e6d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -24,7 +24,7 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty | min | number | 否 | 设置最小值。
默认值:0 | | max | number | 否 | 设置最大值。
默认值:100 | | step | number | 否 | 设置Slider滑动步长。
默认值:1
取值范围:[0.01, max] | -| style | SliderStyle | 否 | 设置Slider的滑块与滑轨显示样式。
默认值:SliderStyle.OutSet | +| style | [SliderStyle](#sliderstyle枚举说明) | 否 | 设置Slider的滑块与滑轨显示样式。
默认值:SliderStyle.OutSet | | direction8+ | [Axis](ts-appendix-enums.md#axis) | 否 | 设置滑动条滑动方向为水平或竖直方向。
默认值:Axis.Horizontal | | reverse8+ | boolean | 否 | 设置滑动条取值范围是否反向,横向Slider默认为从左往右滑动,竖向Slider默认为从上往下滑动。
默认值:false | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 8f9a28d3e5e49f695200372404fb9fdedcf40072..dda20d99a30be6965863aa882ef01c1a6fb41fb4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -92,7 +92,7 @@ TextInput组件的控制器。 ``` controller: TextInputController = new TextInputController() ``` -### caretPosition +### caretPosition8+ caretPosition(value: number): void diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index e00ea4bb7aeef7efb1f3b681563dcb37af8ef39a..e82389ae717ae5ca876dd07954276f49af52df95 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -30,9 +30,9 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) ## ToggleType枚举说明 | 名称 | 描述 | | -------- | ---------------- | -| Checkbox | 提供单选框样式。
> **说明:**
> [通用属性padding](ts-universal-attributes-size.md)的默认值为:
{
 top: 14 vp,
 right: 6 vp,
 bottom: 14 vp,
 left: 6 vp
} | +| Checkbox | 提供单选框样式。
**说明:**
[通用属性padding](ts-universal-attributes-size.md)的默认值为:
{
 top: 14 vp,
 right: 6 vp,
 bottom: 14 vp,
 left: 6 vp
} | | Button | 提供状态按钮样式,如果子组件有文本设置,则相应的文本内容会显示在按钮内部。 | -| Switch | 提供开关样式。
> **说明:**
> [通用属性padding](ts-universal-attributes-size.md)默认值为:
{
 top: 12 vp,
 right: 12 vp,
 bottom: 12 vp,
 left: 12 vp
} | +| Switch | 提供开关样式。
**说明:**
[通用属性padding](ts-universal-attributes-size.md)默认值为:
{
 top: 12 vp,
 right: 12 vp,
 bottom: 12 vp,
 left: 12 vp
} | ## 属性 @@ -40,7 +40,7 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) | 名称 | 参数 | 参数描述 | | ---------------- | --------------------------- | ---------------------- | | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件打开状态的背景颜色。 | -| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | 设置Switch类型的圆形滑块颜色。
> **说明:**
> 仅对type为ToggleType.Switch生效。 | +| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | 设置Switch类型的圆形滑块颜色。
**说明:**
仅对type为ToggleType.Switch生效。 | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index 32cd9333f37dd48ea86b81c0e4bdda6cbb2d34fe..ae246a09ee6db917abb138bbb6b9d4766b8cf6ad 100755 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -21,6 +21,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) > **说明:** > > 不支持转场动画。 +> 同一页面的多个web组件,必须绑定不同的WebController。 **参数:** @@ -1557,7 +1558,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void) -网页加载遇到错误时触发该回调。出于性能考虑,建议此回调中尽量执行简单逻辑。 +网页加载遇到错误时触发该回调。出于性能考虑,建议此回调中尽量执行简单逻辑。在无网络的情况下,触发此回调。 **参数:** @@ -1968,7 +1969,7 @@ onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void) onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) -当Web组件加载url之前触发该回调,用于是否阻止此次访问。 +当Web组件加载url之前触发该回调,用于判断是否阻止此次访问。默认允许加载。 **参数:** @@ -2344,8 +2345,8 @@ onScroll(callback: (event: {xOffset: number, yOffset: number}) => void) | 参数名 | 参数类型 | 参数描述 | | ------- | ------ | ------------ | -| xOffset | number | 水平滚动条滚动所在位置。 | -| yOffset | number | 竖直滚动条滚动所在位置。 | +| xOffset | number | 以网页最左端为基准,水平滚动条滚动所在位置。 | +| yOffset | number | 以网页最上端为基准,竖直滚动条滚动所在位置。 | **示例:** @@ -2686,7 +2687,7 @@ onPageVisible(callback: (event: {url: string}) => void) onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) -设置键盘事件的回调函数,该回调在被Webview消费前触发。 +设置键盘事件的回调函数,该回调在被Webview使用前触发。 **参数:** @@ -4270,7 +4271,7 @@ zoom(factor: number): void ### zoomIn9+ zoomIn(): boolean -调用此接口将当前网页进行放大,比列20%。 +调用此接口将当前网页进行放大,比例为20%。 **返回值:** @@ -4303,7 +4304,7 @@ zoomIn(): boolean ### zoomOut9+ zoomOut(): boolean -调用此接口将当前网页进行缩小,比列20%。 +调用此接口将当前网页进行缩小,比例为20%。 **返回值:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md b/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md index ec9d2e8021068ffde8cf932df2ca0fea5612f381..7c297ede50ec17263b9a6979cb34e9305941c351 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-combined-gestures.md @@ -6,18 +6,19 @@ > > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - ## 接口 GestureGroup(mode: GestureMode, ...gesture: GestureType[]) -- 参数 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | -------- | -------- | -------- | -------- | -------- | - | mode | [GestureMode](#gesturemode枚举说明) | 是 | - | 设置组合手势识别模式。 | - | gesture | [TapGesture](ts-basic-gestures-tapgesture.md)
\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)
\| [PanGesture](ts-basic-gestures-pangesture.md)
\| [PinchGesture](ts-basic-gestures-pinchgesture.md)
\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | 是 | - | 可变长参数,1个或者多个基础手势类型,这些手势会被组合识别。 | +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| mode | [GestureMode](#gesturemode枚举说明) | 是 | 设置组合手势识别模式。 | +| gesture | [TapGesture](ts-basic-gestures-tapgesture.md)
\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)
\| [PanGesture](ts-basic-gestures-pangesture.md)
\| [PinchGesture](ts-basic-gestures-pinchgesture.md)
\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | 是 | 可变长参数,1个或者多个基础手势类型,这些手势会被组合识别。 | ## GestureMode枚举说明 + | 名称 | 描述 | | -------- | -------- | | Sequence | 顺序识别,按照手势的注册顺序识别手势,直到所有手势识别成功。当有一个手势识别失败时,所有手势识别失败。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index e359c9adfa14fd1309eb46f4b7fa8a17f950490b..d26cadcd3f509f6438c97c71d345e5a65413ee64 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -19,6 +19,7 @@ 创建数字标记组件。 **参数:** + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | -------- | -------- | -------- | -------- | -------- | | count | number | 是 | - | 设置提醒消息数。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md index 0ba38047bab43cbe3a266697f64ad1aa783d35cc..e035856a4c9b0c71dfad2d881c2e8639061841b7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-columnsplit.md @@ -25,6 +25,7 @@ ColumnSplit() | resizeable | boolean | 分割线是否可拖拽,默认为false。 | > **说明:** +> > 与RowSplit相同,ColumnSplit的分割线最小能拖动到刚好包含子组件。 > > 在真机中查看拖动效果,预览器中不支持拖动。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md index b04c09c7804046cfdce174a35b9291371f34ffaa..e2d7be2c2b07b48fa4fafaf1d04eaf003a98fb8b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-flex.md @@ -3,15 +3,11 @@ 以弹性方式布局子组件的容器组件。 > **说明:** +> > - 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > - Flex组件在渲染时存在二次布局过程,因此在对性能有严格要求的场景下建议使用[Column](ts-container-column.md)、[Row](ts-container-row.md)代替。 -## 权限列表 - -无 - - ## 子组件 可以包含子组件。 @@ -23,14 +19,15 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle 标准Flex布局容器。 -- 参数 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- | - | direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | 否 | FlexDirection.Row | 子组件在Flex容器上排列的方向,即主轴的方向。 | - | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | 否 | FlexWrap.NoWrap | Flex容器是单行/列还是多行/列排列。 | - | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 子组件在Flex容器主轴上的对齐格式。 | - | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | 否 | ItemAlign.Start | 子组件在Flex容器交叉轴上的对齐格式。 | - | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。 | +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- | +| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | 否 | FlexDirection.Row | 子组件在Flex容器上排列的方向,即主轴的方向。 | +| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | 否 | FlexWrap.NoWrap | Flex容器是单行/列还是多行/列排列。 | +| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 子组件在Flex容器主轴上的对齐格式。 | +| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | 否 | ItemAlign.Start | 子组件在Flex容器交叉轴上的对齐格式。 | +| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md index 34342bef756369527367d85e11077db6fae4cf73..ef8f2337eab6c6962066120ba4f6af42c41c42d0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md @@ -17,6 +17,7 @@ Grid(scroller?: Scroller) **参数:** + | 参数名 | 参数类型 | 必填 | 参数描述 | | --------- | ---------------------------------------- | ---- | ----------------------- | | scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器。用于与可滚动组件进行绑定。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md index 75e927bf604194c4d19b99c2a291b8cd94c1876d..85e356b91ecdc865041301182ec39d1381029678 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md @@ -16,6 +16,7 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | GutterOption, breakpoints?: BreakPoints, direction?: GridRowDirection}) **参数:** + | 参数名 |类型|必填|说明| |-----|-----|----|----| |gutter|Length \| GutterOption| 否 |栅格布局间距,x代表水平方向。| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md index 3b3fcb3d9162b8de5d6075cf2e01dc120ad87d90..29d42b8de0840788b1f4fe13b94986ad3d337790 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitemgroup.md @@ -5,7 +5,9 @@ > **说明:** > > 该组件从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + ## 使用说明 + 当ListItemGroup的父组件List的listDirection属性为Axis.Vertical时,不允许设置ListItemGroup组件的height属性。ListItemGroup的高度为header高度、footer高度和所有ListItem布局后总高度之和。当父组件List的listDirection属性为Axis.Horizontal时,不允许设置ListItemGroup组件的width属性。ListItemGroup的宽度为header宽度、footer宽度和所有ListItem布局后总宽度之和。 当前ListItemGroup内部的ListItem组件不支持编辑、框选、拖拽功能,即ListItem组件的editable、selectable属性不生效。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md index 7dd5e6a524d1c5bb4b224647e8d08be1a2481424..da4043d3bf0612b044344ba91e947b2d52cb80f6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-rowsplit.md @@ -22,6 +22,7 @@ RowSplit() | resizeable | boolean | 分割线是否可拖拽,默认为false。 | > **说明:** +> > RowSplit的分割线最小能拖动到刚好包含子组件。 > > 在真机中查看拖动效果,预览器中不支持拖动。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index c11e5f70b08b5d9ff02c3e7dcaa69da5734fac70..c9550fbd7355c8f35bd790f7619793f73b1f1388 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -23,7 +23,7 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | autoCancel | boolean | 否 | 是否允许点击遮障层退出。
默认值:true | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | | offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | -| customStyle | boolean | 否 | 弹窗容器样式是否自定义。
默认值:false | +| customStyle | boolean | 否 | 弹窗容器样式是否自定义。
默认值:false,弹窗容器的宽度根据栅格系统自适应,不跟随子节点;高度自适应子节点,最大为窗口高度的90%;圆角为24vp。 | | gridCount8+ | number | 否 | 弹窗宽度占[栅格宽度](../../ui/ui-ts-layout-grid-container-new.md)的个数。
默认值为4,异常值按默认值处理,最大栅格数为系统最大栅格数。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 50d072a9a221958dc2a7b21aa4608c913bc004fd..f3bd25442f3d688aec59f9ed2c3fb3a445d8398b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -20,7 +20,7 @@ show(options?: DatePickerDialogOptions) | start | Date | 否 | Date('1970-1-1') | 设置选择器的起始日期。 | | end | Date | 否 | Date('2100-12-31') | 设置选择器的结束日期。 | | selected | Date | 否 | 当前系统日期 | 设置当前选中的日期。 | -| lunar | boolean | 否 | false | 日期是否显示为农历。 |确定 +| lunar | boolean | 否 | false | 日期是否显示为农历。 | | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 点击弹窗中的“确定”按钮时触发该回调。 | | onCancel | () => void | 否 | - | 点击弹窗中的“取消”按钮时触发该回调。 | | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index 82fd60584cbbf0dab54f234136342a5a760a8722..a30820399e7e66b72019e7a5a111b3157308a27f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -47,7 +47,8 @@ struct SharedTransitionExample { struct pageBExample { build() { Stack() { - Image($r('app.media.ic_health_heart')).width(150).height(150).sharedTransition('sharedImage') + Image($r('app.media.ic_health_heart')).width(150).height(150) + .sharedTransition('sharedImage', { duration: 800, curve: Curve.Linear, delay: 100 }) }.width('100%').height('100%') } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index 12c17eea62759530d4fa7881293319b9e91100b3..f56a0c97957064edf50c2f702a1a2f3bbea8c3a9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -39,7 +39,7 @@ getInspectorByKey(id: string): string ### getInspectorTree9+ -getInspectorTree(): string +getInspectorTree(): Object 获取组件树及组件属性。 @@ -49,7 +49,7 @@ getInspectorTree(): string | 类型 | 描述 | | ------ | --------------------------- | -| string | 组件树及组件属性列表的JSON字符串。 | +| Object | 组件树及组件属性列表的JSON对象。 | ### sendEventByKey9+ @@ -181,7 +181,7 @@ struct IdExample { }.margin({ top: 20 }) .onClick(() => { console.info(getInspectorByKey("click")) - console.info(getInspectorTree()) + console.info(JSON.stringify(getInspectorTree())) this.text = "Button 'click to start' is clicked" setTimeout(() => { sendEventByKey("longClick", 11, "") // 向id为"longClick"的组件发送长按事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md index 25f14ed9632f3e04803b7768a240e4c23a658d02..cc73b1303ddfd1b5592c5377165ea9461fdb569c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md @@ -38,6 +38,7 @@ requestFocus(value: string): boolean | boolean | 返回是否成功给目标组件申请到焦点。若参数指向的目标组件存在,且目标组件可获焦,则返回true,否则返回false。 | > **说明:** +> > 支持焦点控制的组件:Button、Text、Image、List、Grid。焦点事件当前仅支持在真机上显示运行效果。 ## 示例 @@ -47,6 +48,7 @@ requestFocus(value: string): boolean defaultFocus/groupDefaultFocus/focusOnTouch示例代码: defaultFocus可以使绑定的组件成为页面创建后首次获焦的焦点。groupDefaultFocus可以使绑定的组件成为tabIndex容器创建后首次获焦的焦点。focusOnTouch可以使绑定的组件点击后立即获焦。 + ```ts // focusTest.ets @Entry diff --git a/zh-cn/application-dev/reference/errorcodes/Readme-CN.md b/zh-cn/application-dev/reference/errorcodes/Readme-CN.md index ba66cd409a9e3ce26e184992ee410a1971fa9280..bf7667cdd065d8d4f03d3d938eeddcc5b7e5304d 100644 --- a/zh-cn/application-dev/reference/errorcodes/Readme-CN.md +++ b/zh-cn/application-dev/reference/errorcodes/Readme-CN.md @@ -47,6 +47,8 @@ - [文件管理子系统错误码](errorcode-filemanagement.md) - 网络管理 - [上传下载错误码](errorcode-request.md) + - [HTTP错误码](errorcode-http.md) + - [Socket错误码](errorcode-socket.md) - 通信与连接 - [NFC错误码](errorcode-nfc.md) - [RPC错误码](errorcode-rpc.md) diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md b/zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md index e7611c35ea75641a984219be39fd62dccba5d6f6..dda2607a4d9de5f979f26ca206313fad3dd84804 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md @@ -58,7 +58,7 @@ System service operation failed. **错误信息** -IPC communication failed. +IPC failed. **错误描述** @@ -94,7 +94,7 @@ The application is not installed. **错误信息** -Get application info failed. +Failed to get the application information. **错误描述** @@ -114,11 +114,11 @@ Get application info failed. **错误信息** -Get system or actual time operation failed. +Failed to get the system time. **错误描述** -系统服务获取系统事件或者实际事件操作失败。 +系统服务获取系统时间或者实际时间操作失败。 **可能原因** @@ -132,7 +132,7 @@ Get system or actual time operation failed. **错误信息** -Application group operation failed. The application group are the the same or do not need te be updated. +Repeated operation on the application group. **错误描述** @@ -150,7 +150,7 @@ Application group operation failed. The application group are the the same or do **错误信息** -Get application group info failed. The application group infomation cannot be found. +Failed to get the application group information. **错误描述** diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-http.md b/zh-cn/application-dev/reference/errorcodes/errorcode-http.md new file mode 100644 index 0000000000000000000000000000000000000000..342513e155c9b0c8ed5a79176527671f372bcb9f --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-http.md @@ -0,0 +1,523 @@ +# HTTP错误码 + +## 2300001 不支持的协议 + +**错误信息** + +Unsupported protocol. + +**错误描述** + +协议版本服务器不支持。 + +**可能原因** + +传入的协议版本,服务器不支持。 + +**处理步骤** + +请检查传入的协议版本是否合理,排查服务器实现。 + +## 2300003 URL格式错误 + +**错误信息** + +URL using bad/illegal format or missing URL. + +**错误描述** + +URL格式错误。 + +**可能原因** + +可能传入的url格式不正确。 + +**处理步骤** + +检查传入的url格式是否正确。 + +## 2300005 代理服务器域名解析失败 + +**错误信息** + +Couldn't resolve proxy name. + +**错误描述** + +代理服务器的域名无法解析。 + +**可能原因** + +服务器的URL不正确 + +**处理步骤** + +排查代理服务器的URL是否正确。 + +## 2300006 域名解析失败 + +**错误信息** + +Couldn't resolve host name. + +**错误描述** + +服务器的域名无法解析。 + +**可能原因** + +传入的服务器的URL不正确。 + +**处理步骤** + +请检查入的服务器的URL是否合理。 + +## 2300007 无法连接到服务器 + +**错误信息** + +Couldn't connect to server. + +**错误描述** + +服务器无法连接。 + +**可能原因** + +可能传入的url格式不正确。 + +**处理步骤** + +检查传入的url格式是否正确。 + +## 2300008 服务器返回非法数据 + +**错误信息** + +Weird server reply. + +**错误描述** + +服务器返回非法数据。 + +**可能原因** + +服务器出错,返回了非HTTP格式的数据。 + +**处理步骤** + +排查服务器实现。 + +## 2300009 拒绝对远程资源的访问 + +**错误信息** + +Access denied to remote resource. + +**错误描述** + +拒绝对远程资源的访问。 + +**可能原因** + +指定的内容被服务器拒绝访问。 + +**处理步骤** + +排查请求内容。 + +## 2300016 HTT2帧层错误 + +**错误信息** + +Error in the HTTP2 framing layer. + +**错误描述** + +HTTP2层级的错误。 + +**可能原因** + +服务器不支持HTTP2。 + +**处理步骤** + +抓包分析、排查服务器是否支持HTTP2。 + +## 2300018 服务器返回数据不完整 + +**错误信息** + +Transferred a partial file. + +**错误描述** + +服务器返回的数据不完整。 + +**可能原因** + +可能与服务器实现有关 + +**处理步骤** + +排查服务器实现。 + +## 2300023 向磁盘/应用程序写入接收数据失败 + +**错误信息** + +Failed writing received data to disk/application. + +**错误描述** + +向磁盘/应用程序写入接收数据失败。 + +**可能原因** + +应用没有写文件权限。 + +**处理步骤** + +排查应用权限。 + +## 2300025 上传失败 + +**错误信息** + +Upload failed. + +**错误描述** + +上传失败。 + +**可能原因** + +文件过大或者网络问题。对于FTP,服务器通常会拒绝STOR命令。错误缓冲区通常包含服务器的解释。 + +**处理步骤** + +排查文件大小及网络状况。 + +## 2300026 从文件/应用程序中打开/读取本地数据失败 + +**错误信息** + +Failed to open/read local data from file/application. + +**错误描述** + +从文件/应用程序中打开/读取本地数据失败。 + +**可能原因** + +应用没有读文件权限 + +**处理步骤** + +排查应用权限。 + +## 2300027 内存不足 + +**错误信息** + +Out of memory. + +**错误描述** + +内存不足。 + +**可能原因** + +内存不足。 + +**处理步骤** + +排查系统内存。 + +## 2300028 操作超时 + +**错误信息** + +Timeout was reached. + +**错误描述** + +操作超时。 + +**可能原因** + +TCP连接超时或读写超时。 + +**处理步骤** + +排查网络问题。 + +## 2300047 重定向次数达到最大值 + +**错误信息** + +Number of redirects hit maximum amount. + +**错误描述** + +重定向次数达到最大值。 + +**可能原因** + +重定向次数过多 + +**处理步骤** + +排查服务器实现。 + +## 2300052 服务器没有返回内容 + +**错误信息** + +Server returned nothing (no headers, no data). + +**错误描述** + +服务器没有返回内容。 + +**可能原因** + +可能与服务器实现有关。 + +**处理步骤** + +排查服务器实现。 + +## 2300055 发送网络数据失败 + +**错误信息** + +Failed sending data to the peer. + +**错误描述** + +无法往对端发送数据,发送网络数据失败。 + +**可能原因** + +网络问题。 + +**处理步骤** + +排查网络。 + +## 2300056 接收网络数据失败 + +**错误信息** + +Failure when receiving data from the peer. + +**错误描述** + +无法往从对端收到数据,接收网络数据失败。 + +**可能原因** + +网络问题 + +**处理步骤** + +排查网络问题。 + +## 2300058 本地SSL证书错误 + +**错误信息** + +Problem with the local SSL certificate. + +**错误描述** + +本地SSL证书错误。 + +**可能原因** + +SSL证书格式有错误。 + +**处理步骤** + +检查SSL证书格式。 + +## 2300059 无法使用指定的密码 + +**错误信息** + +Couldn't use specified SSL cipher. + +**错误描述** + +无法使用指定的密码。 + +**可能原因** + +client和sever协商的加密算法系统不支持。 + +**处理步骤** + +抓包分析协商的算法。 + +## 2300060 远程服务器SSL证书或SSH秘钥不正确 + +**错误信息** + +SSL peer certificate or SSH remote key was not OK. + +**错误描述** + +远程服务器SSL证书或SSH秘钥不正确。 + +**可能原因** + +无法校验服务器身份,有可能是证书过期了 + +**处理步骤** + +检查证书有效性。 + +## 2300061 无法识别或错误的HTTP编码格式 + +**错误信息** + +Unrecognized or bad HTTP Content or Transfer-Encoding. + +**错误描述** + +无法识别或错误的HTTP编码格式。 + +**可能原因** + +HTTP编码格式不正确。 + +**处理步骤** + +排查服务器实现,目前仅支持gzip编码。 + +## 2300063 超出最大文件大小 + +**错误信息** + +Maximum file size exceeded. + +**错误描述** + +超出最大文件大小。 + +**可能原因** + +下载的文件过大。 + +**处理步骤** + +排查服务器实现。 + +## 2300070 服务器磁盘空间不足 + +**错误信息** + +Remote disk full or allocation exceeded. + +**错误描述** + +服务器磁盘空间不足。 + +**可能原因** + +服务器磁盘已满 + +**处理步骤** + +检查服务器磁盘空间。 + +## 2300073 服务器返回文件已存在 + +**错误信息** + +Remote file already exists. + +**错误描述** + +服务器返回文件已存在。 + +**可能原因** + +上传文件的时候,服务器返回文件已经存在。 + +**处理步骤** + +排查服务器。 + +## 2300077 SSL CA证书不存在或没有访问权限 + +**错误信息** + +Problem with the SSL CA cert (path? access rights?). + +**错误描述** + +SSL CA证书不存在或没有访问权限。 + +**可能原因** + +证书不存在或者没有访问权限。 + +**处理步骤** + +检查证书是否存在或者有没有访问权限。 + +## 2300078 URL请求的文件不存在 + +**错误信息** + +Remote file not found. + +**错误描述** + +URL请求的文件不存在。 + +**可能原因** + +URL请求的文件不存在 + +**处理步骤** + +检查URL请求的文件是否存在。 + +## 2300094 身份校验失败 + +**错误信息** + +An authentication function returned an error. + +**错误描述** + +身份校验失败。 + +**可能原因** + +传入的校验身份的字段与服务器不匹配。 + +**处理步骤** + +排查传入的校验身份的字段是否与服务器匹配。 + +## 2300999 未知错误 + +**错误信息** + +Unknown Other Error. + +**错误描述** + +未知错误。 + +**可能原因** + +未知错误。 + +**处理步骤** + +未知错误。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-socket.md b/zh-cn/application-dev/reference/errorcodes/errorcode-socket.md new file mode 100644 index 0000000000000000000000000000000000000000..687ef15d7e9f836521de0db784bb7868c96a95ad --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-socket.md @@ -0,0 +1,77 @@ +# TCP/UDP 错误码 + +## 2301001 操作不允许 + +**错误信息** + +Operation not permitted. + +**错误描述** + +操作不允许。 + +**可能原因** + +非法操作。 + +**处理步骤** + +检查操作步骤。 + +## 2301002 文件不存在 + +**错误信息** + +No such file or directory. + +**错误描述** + +文件不存在。 + +**可能原因** + +文件不存在。 + +**处理步骤** + +检查文件名或文件路径。 + +## 2301003 进程不存在 + +**错误信息** + +No such process. + +**错误描述** + +进程不存在。 + +**可能原因** + +进程不存在 + +**处理步骤** + +排查进程信息。 + +## 2300004 Interrupted system call + +**错误信息** + +Couldn't resolve host name. + +**错误描述** + +系统调用中断。 + +**可能原因** + +系统调用中断。 + +**处理步骤** + +排查系统调用。 + +**TCP/UDP 错误码说明:** +> 其余错误码映射形式为:2301000 + 内核错误码,关键信息请参考内核错误码。 + diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-wifi.md b/zh-cn/application-dev/reference/errorcodes/errorcode-wifi.md new file mode 100644 index 0000000000000000000000000000000000000000..348a833f12c55cf709c9c22c8ec00e516421b27a --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-wifi.md @@ -0,0 +1,125 @@ +# WIFI错误码 + +## 2401000 STA内部异常 + +**错误信息** + +Operation failed. + +**错误描述** + +WIFI服务内部执行STA相关操作时出现未知错误。 + +**可能原因** + +1. 和WIFI服务建立通信异常。 +2. WIFI芯片通信异常。 +3. 其他未知错误。 + +**处理步骤** + +1. 重新执行关闭及打开WIFI开关的操作。 +2. 如果步骤1无效,请尝试重启设备。 + +## 2501000 STA内部异常 + +**错误信息** + +Operation failed. + +**错误描述** + +WIFI服务内部执行STA相关操作时出现未知错误。 + +**可能原因** + +1. 和WIFI服务建立通信异常。 +2. WIFI芯片通信异常。 +3. 其他未知错误。 + +**处理步骤** + +1. 重新执行关闭及打开WIFI开关的操作。 +2. 如果步骤1无效,请尝试重启设备。 + +## 2501001 STA功能未打开 + +**错误信息** + +Wifi is closed. + +**错误描述** + +WIFI STA功能被关闭。 + +**可能原因** + +WIFI功能被关闭。 + +**处理步骤** + +打开WIFI功能。 + +## 2601000 Hotspot模块异常 + +**错误信息** + +Operation failed. + +**错误描述** + +WIFI服务内部执行Hotspot相关操作时出现未知错误。 + +**可能原因** + +1. 和WIFI服务建立通信异常。 +2. WIFI芯片通信异常。 +3. 其他未知错误。 + +**处理步骤** + +1. 重新执行关闭及打开Hotspot开关的操作。 +2. 如果步骤1无效,请尝试重启设备。 + +## 2701000 AP扩展模块异常 + +**错误信息** + +Operation failed. + +**错误描述** + +WIFI服务内部执行Hotspot相关操作时出现未知错误。 + +**可能原因** + +1. 和WIFI服务建立通信异常。 +2. WIFI芯片通信异常。 +3. 其他未知错误。 + +**处理步骤** + +1. 重新执行关闭及打开Hotspot开关的操作。 +2. 如果步骤1无效,请尝试重启设备。 + +## 2801000 P2P模块异常 + +**错误信息** + +Operation failed. + +**错误描述** + +WIFI服务内部执行P2P相关操作时出现未知错误。 + +**可能原因** + +1. 和WIFI服务建立通信异常。 +2. WIFI芯片通信异常。 +3. 其他未知错误。 + +**处理步骤** + +1. 重新执行关闭及打开WIFI开关的操作。 +2. 如果步骤1无效,请尝试重启设备。 + diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-window.md b/zh-cn/application-dev/reference/errorcodes/errorcode-window.md index 257e3b7355a8cda3dd91db05cd16e9fef94f0a54..ece08787c2d65a1a7b120e6447196d26c8419c86 100755 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-window.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-window.md @@ -77,3 +77,58 @@ This window context is abnormal. **处理步骤**
在对窗口上下文进行操作前,检查该窗口上下文是否存在,确保其未被销毁,再进行相关操作。 + +## 1300007 WindowExtension拉起应用失败 + +**错误信息**
+Start ability failed. + +**错误描述**
+WindowExtension拉起应用失败。 + +**可能原因**
+WindowExtension拉起应用的参数异常。 + +**处理步骤**
+检查WindowExtension参数是否被异常修改,确保其参数合法,再进行相关操作。 + +## 1300008 显示设备异常 + +**错误信息**
The operation is on invalid display. + +**错误描述**
显示设备异常。 + +**可能原因**
+1. 显示设备没有准备好。
+2. 显示设备被移除。
+3. 显示设备被损坏。 + +**处理步骤**
确保显示设备正常,再进行相关开发。 + +## 1300009 父窗口无效 + +**错误信息**
The parent window is invalid. + +**错误描述**
父窗口无效。 + +**可能原因**
+1. 子窗口没有绑定父窗口。
+2. 子窗口绑定的父窗口异常,如父窗口已被销毁等。 + +**处理步骤**
+1. 检查确保子窗口成功绑定父窗口。
+2. 检查子窗口绑定的父窗口状态,确保父窗口状态正常。 + +## 1300010 全屏窗口的无效操作 + +**错误信息**
This operation is not support in fullscreen. + +**错误描述**
全屏窗口下的无效操作。 + +**可能原因**
+1. 对全屏窗口进行move操作。
+2. 对全屏窗口进行resize操作。 + +**处理步骤**
+1. 不要对全屏窗口进行move操作。
+2. 不要对全屏窗口进行resize操作。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md index fffd2abf32ac3f80dfc1dd808b2933a1a91ac345..2fd63c654e3cc00bde0dda042aa198597ba633d7 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component.md @@ -69,8 +69,8 @@ | [OH_XCOMPONENT_ID_LEN_MAX](#oh_xcomponent_id_len_max) = 128 | ArkUI XComponent的id最大长度。 | | [OH_MAX_TOUCH_POINTS_NUMBER](#oh_max_touch_points_number) = 10 | 触摸事件中的可识别的触摸点个数最大值。 | | [OH_NativeXComponent_TouchPoint::id](#id-12) = 0 | 手指的唯一标识符。 | -| [OH_NativeXComponent_TouchPoint::screenX](#screenx-13) = 0.0 | 触摸点相对于屏幕左边缘的x坐标。 | -| [OH_NativeXComponent_TouchPoint::screenY](#screeny-13) = 0.0 | 触摸点相对于屏幕上边缘的y坐标。 | +| [OH_NativeXComponent_TouchPoint::screenX](#screenx-13) = 0.0 | 触摸点相对于应用窗口左上角的x坐标。 | +| [OH_NativeXComponent_TouchPoint::screenY](#screeny-13) = 0.0 | 触摸点相对于应用窗口左上角的y坐标。 | | [OH_NativeXComponent_TouchPoint::x](#x-13) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | | [OH_NativeXComponent_TouchPoint::y](#y-13) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | | [OH_NativeXComponent_TouchPoint::type](#type-12) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | @@ -79,8 +79,8 @@ | [OH_NativeXComponent_TouchPoint::timeStamp](#timestamp-12) = 0 | 当前触摸事件的时间戳。 | | [OH_NativeXComponent_TouchPoint::isPressed](#ispressed) = false | 当前点是否被按下。 | | [OH_NativeXComponent_TouchEvent::id](#id-22) = 0 | 手指的唯一标识符。 | -| [OH_NativeXComponent_TouchEvent::screenX](#screenx-23) = 0.0 | 触摸点相对于屏幕左边缘的x坐标。 | -| [OH_NativeXComponent_TouchEvent::screenY](#screeny-23) = 0.0 | 触摸点相对于屏幕上边缘的y坐标。 | +| [OH_NativeXComponent_TouchEvent::screenX](#screenx-23) = 0.0 | 触摸点相对于应用窗口左上角的x坐标。 | +| [OH_NativeXComponent_TouchEvent::screenY](#screeny-23) = 0.0 | 触摸点相对于应用窗口左上角的y坐标。 | | [OH_NativeXComponent_TouchEvent::x](#x-23) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | | [OH_NativeXComponent_TouchEvent::y](#y-23) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | | [OH_NativeXComponent_TouchEvent::type](#type-22) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | @@ -92,8 +92,8 @@ | [OH_NativeXComponent_TouchEvent::numPoints](#numpoints) = 0 | 当前接触点的数量。 | | [OH_NativeXComponent_MouseEvent::x](#x-33) = 0.0 | 点击触点相对于当前组件左上角的x轴坐标。 | | [OH_NativeXComponent_MouseEvent::y](#y-33) = 0.0 | 点击触点相对于当前组件左上角的y轴坐标。 | -| [OH_NativeXComponent_MouseEvent::screenX](#screenx-33) = 0.0 | 点击触点相对于屏幕左上角的x轴坐标。 | -| [OH_NativeXComponent_MouseEvent::screenY](#screeny-33) = 0.0 | 点击触点相对于屏幕左上角的y轴坐标。 | +| [OH_NativeXComponent_MouseEvent::screenX](#screenx-33) = 0.0 | 点击触点相对于应用窗口左上角的x轴坐标。 | +| [OH_NativeXComponent_MouseEvent::screenY](#screeny-33) = 0.0 | 点击触点相对于应用窗口左上角的y轴坐标。 | | [OH_NativeXComponent_MouseEvent::timestamp](#timestamp) = 0 | 当前鼠标事件的时间戳。 | | [OH_NativeXComponent_MouseEvent::action](#action) = [OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE](#oh_nativexcomponent_mouseeventaction) | 当前鼠标事件动作。 | | [OH_NativeXComponent_MouseEvent::button](#button) = [OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON](#oh_nativexcomponent_mouseeventbutton) | 鼠标事件按键。 | @@ -739,7 +739,7 @@ float OH_NativeXComponent_TouchPoint::screenX = 0.0 **描述:** -触摸点相对于屏幕左边缘的x坐标。 +触摸点相对于应用窗口左上角的x坐标。 **起始版本:** @@ -755,7 +755,7 @@ float OH_NativeXComponent_TouchEvent::screenX = 0.0 **描述:** -触摸点相对于屏幕左边缘的x坐标。 +触摸点相对于应用窗口左上角的x坐标。 **起始版本:** @@ -771,7 +771,7 @@ float OH_NativeXComponent_MouseEvent::screenX **描述:** -点击触点相对于屏幕左上角的x轴坐标。 +点击触点相对于应用窗口左上角的x轴坐标。 **起始版本:** @@ -787,7 +787,7 @@ float OH_NativeXComponent_TouchPoint::screenY = 0.0 **描述:** -触摸点相对于屏幕上边缘的y坐标。 +触摸点相对于应用窗口左上角的y坐标。 **起始版本:** @@ -803,7 +803,7 @@ float OH_NativeXComponent_TouchEvent::screenY = 0.0 **描述:** -触摸点相对于屏幕上边缘的y坐标。 +触摸点相对于应用窗口左上角的y坐标。 **起始版本:** @@ -819,7 +819,7 @@ float OH_NativeXComponent_MouseEvent::screenY **描述:** -点击触点相对于屏幕左上角的y轴坐标。 +点击触点相对于应用窗口左上角的y轴坐标。 **起始版本:** diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event.md index b046d76de2c0c98161fb5795dca4d2a4e1e2a46b..0ac4572128b94269ff1bdf393717b72a3c3020f1 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___mouse_event.md @@ -23,8 +23,8 @@ | -------- | -------- | | [x = 0.0](_o_h___native_x_component.md#x-33) | 点击触点相对于当前组件左上角的x轴坐标。 | | [y = 0.0](_o_h___native_x_component.md#y-33) | 点击触点相对于当前组件左上角的y轴坐标。 | -| [screenX = 0.0](_o_h___native_x_component.md#screenx-33) | 点击触点相对于屏幕左上角的x轴坐标。 | -| [screenY = 0.0](_o_h___native_x_component.md#screeny-33) | 点击触点相对于屏幕左上角的y轴坐标。 | +| [screenX = 0.0](_o_h___native_x_component.md#screenx-33) | 点击触点相对于应用窗口左上角的x轴坐标。 | +| [screenY = 0.0](_o_h___native_x_component.md#screeny-33) | 点击触点相对于应用窗口左上角的y轴坐标。 | | [timestamp = 0](_o_h___native_x_component.md#timestamp) | 当前鼠标事件的时间戳。 | | [action = OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE](_o_h___native_x_component.md#action) | 当前鼠标事件动作。 | | [button = OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON](_o_h___native_x_component.md#button) | 鼠标事件按键。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_event.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_event.md index 2907636f13dee69f0a85ff8d6135af9eb3c429f9..1002313b4f2a5d42a4f0b044114c1a8e04768f7c 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_event.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_event.md @@ -22,8 +22,8 @@ | 成员变量名称 | 描述 | | -------- | -------- | | [id](_o_h___native_x_component.md#id-22) = 0 | 手指的唯一标识符。 | -| [screenX](_o_h___native_x_component.md#screenx-23) = 0.0 | 触摸点相对于屏幕左边缘的x坐标。 | -| [screenY](_o_h___native_x_component.md#screeny-23) = 0.0 | 触摸点相对于屏幕上边缘的y坐标。 | +| [screenX](_o_h___native_x_component.md#screenx-23) = 0.0 | 触摸点相对于应用窗口左上角的x坐标。 | +| [screenY](_o_h___native_x_component.md#screeny-23) = 0.0 | 触摸点相对于应用窗口左上角的y坐标。 | | [x](_o_h___native_x_component.md#x-23) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | | [y](_o_h___native_x_component.md#y-23) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | | [type](_o_h___native_x_component.md#type-22) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | diff --git a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_point.md b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_point.md index 462f272c615f148d40a8caa59638abef3e123a8a..14176aeec7b69522675e9c387240812b1fcfaafb 100644 --- a/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_point.md +++ b/zh-cn/application-dev/reference/native-apis/_o_h___native_x_component___touch_point.md @@ -22,8 +22,8 @@ | 成员变量名称 | 描述 | | -------- | -------- | | [id](_o_h___native_x_component.md#id-12) = 0 | 手指的唯一标识符。 | -| [screenX](_o_h___native_x_component.md#screenx-13) = 0.0 | 触摸点相对于屏幕左边缘的x坐标。 | -| [screenY](_o_h___native_x_component.md#screeny-13) = 0.0 | 触摸点相对于屏幕上边缘的y坐标。 | +| [screenX](_o_h___native_x_component.md#screenx-13) = 0.0 | 触摸点相对于应用窗口左上角的x坐标。 | +| [screenY](_o_h___native_x_component.md#screeny-13) = 0.0 | 触摸点相对于应用窗口左上角的y坐标。 | | [x](_o_h___native_x_component.md#x-13) = 0.0 | 触摸点相对于XComponent组件左边缘的x坐标。 | | [y](_o_h___native_x_component.md#y-13) = 0.0 | 触摸点相对于XComponent组件上边缘的y坐标。 | | [type](_o_h___native_x_component.md#type-12) = OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UNKNOWN | 触摸事件的触摸类型。 | diff --git a/zh-cn/application-dev/reference/syscap.md b/zh-cn/application-dev/reference/syscap.md index cc3ecda8615c8c3b536a8de554c2e02daececae7..5ab69bbb18a97b2645a1300ea7a258741fb19bad 100644 --- a/zh-cn/application-dev/reference/syscap.md +++ b/zh-cn/application-dev/reference/syscap.md @@ -8,7 +8,7 @@ SysCap,全称SystemCapability,即系统能力,指操作系统中每一个 ![image-20220326064841782](figures/image-20220326064841782.png) -开发者可以在[SysCap列表](../reference/syscap-list.md)中查询OpenHarmony的能力集。 +开发者可以在[SysCap列表](syscap-list.md)中查询OpenHarmony的能力集。 ### 支持能力集,联想能力集与要求能力集 @@ -93,19 +93,19 @@ DevEco Studio会根据创建的工程所支持的设置自动配置联想能力 ### 判断 API 是否可以使用 -- 方法1:OpenHarmony定义了API canIUse帮助开发者来判断该工程是否支持某个特定的syscap。 +- 方法1:OpenHarmony定义了API canIUse帮助开发者来判断该设备是否支持某个特定的syscap。 ```ts if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) { - console.log("该应用支持SystemCapability.ArkUI.ArkUI.Full"); + console.log("该设备支持SystemCapability.ArkUI.ArkUI.Full"); } else { - console.log("该应用不支持SystemCapability.ArkUI.ArkUI.Full"); + console.log("该设备不支持SystemCapability.ArkUI.ArkUI.Full"); } ``` -- 方法2:开发者可通过 import 的方式将模块导入,若当前设备不支持该模块,import 的结果为 undefined,开发者在使用其 API 时,需要判断其是否存在。 +- 方法2:开发者可通过import的方式将模块导入,若当前设备不支持该模块,import的结果为undefined,开发者在使用其API时,需要判断其是否存在。 - ``` + ```ts import geolocation from '@ohos.geolocation'; if (geolocation) { @@ -148,16 +148,16 @@ authenticator.execute('FACE_ONLY', 'S1', (err, result) => { 1. 一套 OpenHarmony 源码由可选和必选部件集组成,不同的部件为对外体现的系统能力不同,即部件与 SysCap 之间映射关系。 -2. 发布归一化的 SDK,API 与 SysCap 之间存在映射关系。 +2. 发布归一化的SDK,API与SysCap之间存在映射关系。 3. 产品解决方案厂商按硬件能力和产品诉求,可按需拼装部件。 -4. 产品配置的部件可以是 OpenHarmony 的部件,也可以是三方开发的私有部件,由于部件与SysCap间存在映射,所有拼装后即可得到该产品的SysCap集合。 +4. 产品配置的部件可以是OpenHarmony的部件,也可以是三方开发的私有部件,由于部件与SysCap间存在映射,所有拼装后即可得到该产品的SysCap集合。 -5. SysCap集编码生成 PCID (Product Compatibility ID, 产品兼容性标识),应用开发者可将 PCID 导入 IDE解码成SysCap ,开发时对设备的SysCap差异做兼容性处理。 +5. SysCap集编码生成 PCID (Product Compatibility ID, 产品兼容性标识),应用开发者可将PCID导入IDE解码成SysCap,开发时对设备的SysCap差异做兼容性处理。 -6. 部署到设备上的系统参数中包含了 SysCap 集,系统提供了native的接口和应用接口,可供系统内的部件和应用查询某个 SysCap 是否存在。 +6. 部署到设备上的系统参数中包含了SysCap集,系统提供了native的接口和应用接口,可供系统内的部件和应用查询某个SysCap是否存在。 -7. 应用开发过程中,应用必要的 SysCap 将被编码成 RPCID(Required Product Compatibility ID),并写入应用安装包中。应用安装时,包管理器将解码 RPCID 得到应用需要的 SysCap,与设备当前具备的 SysCap 比较,若应用要求的 SysCap 都被满足,则安装成功。 +7. 应用开发过程中,应用必要的SysCap将被编码成RPCID(Required Product Compatibility ID),并写入应用安装包中。应用安装时,包管理器将解码RPCID得到应用需要的 SysCap,与设备当前具备的SysCap比较,若应用要求的SysCap都被满足,则安装成功。 -8. 应用运行时,可通过 canIUse 接口查询设备的 SysCap,保证在不同设备上的兼容性。 +8. 应用运行时,可通过canIUse接口查询设备的SysCap,保证在不同设备上的兼容性。 diff --git a/zh-cn/application-dev/security/cryptoFramework-guidelines.md b/zh-cn/application-dev/security/cryptoFramework-guidelines.md index 562bef2ff66b8f961190f2bd1027496ffa4fa793..0c697abe1d3eef3718759ba8107e2e2e68a12ebc 100644 --- a/zh-cn/application-dev/security/cryptoFramework-guidelines.md +++ b/zh-cn/application-dev/security/cryptoFramework-guidelines.md @@ -249,7 +249,7 @@ function genGcmParamsSpec() { arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes let dataTag = new Uint8Array(arr); let tagBlob = {data : dataTag}; - let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algoName : "GcmParamsSpec"}; + let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algName : "GcmParamsSpec"}; return gcmParamsSpec; } @@ -296,8 +296,8 @@ function testAesGcm() { }, 10) }).then(() => { // 生成对称密钥生成器 - let symAlgoName = 'AES128'; - let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); + let symAlgName = 'AES128'; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); if (symKeyGenerator == null) { console.error('createSymKeyGenerator failed'); return; @@ -309,9 +309,9 @@ function testAesGcm() { globalGcmParams = genGcmParamsSpec(); // 生成加解密生成器 - let cipherAlgoName = 'AES128|GCM|PKCS7'; + let cipherAlgName = 'AES128|GCM|PKCS7'; try { - globalCipher = cryptoFramework.createCipher(cipherAlgoName); + globalCipher = cryptoFramework.createCipher(cipherAlgName); console.info(`cipher algName: ${globalCipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); @@ -409,8 +409,8 @@ function genKeyMaterialBlob() { // 3DES ECB模式示例,采用已有数据生成密钥(callback写法) function test3DesEcb() { // 生成对称密钥生成器 - let symAlgoName = '3DES192'; - let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); + let symAlgName = '3DES192'; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); if (symKeyGenerator == null) { console.error('createSymKeyGenerator failed'); return; @@ -418,9 +418,9 @@ function test3DesEcb() { console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); // 生成加解密生成器 - let cipherAlgoName = '3DES192|ECB|PKCS7'; + let cipherAlgName = '3DES192|ECB|PKCS7'; try { - globalCipher = cryptoFramework.createCipher(cipherAlgoName); + globalCipher = cryptoFramework.createCipher(cipherAlgName); console.info(`cipher algName: ${globalCipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); diff --git a/zh-cn/application-dev/telephony/Readme-CN.md b/zh-cn/application-dev/telephony/Readme-CN.md index 7361624ade0d235beb6e00ad87ce6b84c67a09df..f7892bf92c07bfcee484c9fdac765fcf487d9f90 100644 --- a/zh-cn/application-dev/telephony/Readme-CN.md +++ b/zh-cn/application-dev/telephony/Readme-CN.md @@ -1,5 +1,5 @@ # 电话服务 - [电话服务开发概述](telephony-overview.md) -- [跳转拨号界面](jumping-to-the-dial-screen.md) -- [获取当前蜂窝网络信号信息](cellular-network-signal-info.md) +- [拨打电话](telephony-call.md) +- [短信服务](telephony-sms.md) diff --git a/zh-cn/application-dev/telephony/cellular-network-signal-info.md b/zh-cn/application-dev/telephony/cellular-network-signal-info.md deleted file mode 100644 index 2e37ff8134208b978720953229ee445d8cd922e6..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/telephony/cellular-network-signal-info.md +++ /dev/null @@ -1,56 +0,0 @@ -# 获取当前蜂窝网络信号信息 - - -## 场景介绍 - -应用通常需要获取用户所在蜂窝网络下信号信息,以便获取当前驻网质量。开发者可以通过本业务,获取到用户指定SIM卡当前所在网络下的信号信息。 - - -## 接口说明 - -radio模块提供了获取当前网络信号信息的方法。observer模块为开发者提供蜂窝网络状态订阅和取消订阅功能。具体接口说明如下表。 - -| 功能分类 | 接口名 | 描述 | 所需权限 | -| -------- | -------- | -------- | -------- | -| 信号强度信息 | radio.getSignalInformation​​() | 获取当前注册蜂窝网络信号强度信息 | 无 | -| 订阅蜂窝网络信号变化 | observer.on('signalInfoChange') | 订阅蜂窝网络信号变化 | 无 | -| 取消订阅蜂窝网络信号变化 | observer.off('signalInfoChange') | 取消订阅蜂窝网络信号变化 | 无 | - - -## 开发步骤 - -1. import需要的模块。 - -2. 调用getSignalInformation()方法,返回所有SignalInformation列表。 - -3. 遍历SignalInformation数组,并分别根据不同的signalType得到不同制式的信号强度。 - -4. 订阅蜂窝网络信号变化(可选)。 - - ```js - import radio from '@ohos.telephony.radio' - import observer from '@ohos.telephony.observer'; - - // 以获取卡1的信号强度为例 - let slotId = 0; - radio.getSignalInformation(slotId, (err, data) => { - if (!err) { - console.log("get signal information success."); - // 遍历数组,输出不同网络制式下的信号强度 - for (let j = 0; j < data.length; j++) { - console.log("type:" + data[j].signalType + ", level:" + data[j].signalLevel); - } - } else { - console.log("get signal information fail, err is:" + JSON.stringify(err)); - } - }); - // 订阅蜂窝网络信号变化(可选) - observer.on("signalInfoChange", (data) => { - console.log("signal info change, data is:" + JSON.stringify(data)); - }); - ``` - -## 相关实例 - -针对蜂窝网络数据开发,有以下相关实例可供参考: -- [`MobileNetwork`:蜂窝数据(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/MobileNetwork) \ No newline at end of file diff --git a/zh-cn/application-dev/telephony/jumping-to-the-dial-screen.md b/zh-cn/application-dev/telephony/jumping-to-the-dial-screen.md deleted file mode 100644 index 6cdca64e2e8d47d6dbc6e1557c166f0c18394243..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/telephony/jumping-to-the-dial-screen.md +++ /dev/null @@ -1,51 +0,0 @@ -# 跳转拨号界面 - -当应用需要跳转到拨号界面,并显示拨号的号码时,使用本业务。当开发者调用makeCall接口时,设备会自动跳转到拨号界面。和正常拨打电话一样,用户可以选择音频或视频呼叫,卡1或卡2拨出。 - - -## 接口说明 - -call模块为开发者提供呼叫管理功能。observer模块为开发者提供订阅和取消订阅通话业务状态的功能。具体接口说明如下表。 - -| 功能分类 | 接口名 | 描述 | 所需权限 | -| -------- | -------- | -------- | -------- | -| 能力获取 | call.hasVoiceCapability() | 是否具有语音功能 | 无 | -| 跳转拨号界面 | call.makeCall() | 跳转到拨号界面,并显示拨号的号码 | 无 | -| 订阅通话业务状态变化 | observer.on('callStateChange') | 订阅通话业务状态变化 | ohos.permission.READ_CALL_LOG (获取通话号码需要该权限) | -| 取消订阅通话业务状态变化 | observer.off('callStateChange') | 取消订阅通话业务状态变化 | 无 | - - -## 开发步骤 - -1. import需要的模块。 - -2. 调用hasVoiceCapability()接口获取当前设备呼叫能力,如果支持继续下一步;如果不支持则无法发起呼叫。 - -3. 跳转到拨号界面,并显示拨号的号码。 - -4. (可选)订阅通话业务状态变化。 - - ```js - // import需要的模块 - import call from '@ohos.telephony.call'; - import observer from '@ohos.telephony.observer'; - - // 调用查询能力接口 - let isSupport = call.hasVoiceCapability(); - if (!isSupport) { - console.log("not support voice capability, return."); - return; - } - // 如果设备支持呼叫能力,则继续跳转到拨号界面,并显示拨号的号码 - call.makeCall("13xxxx", (err)=> { - if (!err) { - console.log("make call success."); - } else { - console.log("make call fail, err is:" + JSON.stringify(err)); - } - }); - // 订阅通话业务状态变化(可选) - observer.on("callStateChange", (data) => { - console.log("call state change, data is:" + JSON.stringify(data)); - }); - ``` diff --git a/zh-cn/application-dev/telephony/telephony-call.md b/zh-cn/application-dev/telephony/telephony-call.md new file mode 100644 index 0000000000000000000000000000000000000000..0426b1df602827beb3e6b163ecd893241b475545 --- /dev/null +++ b/zh-cn/application-dev/telephony/telephony-call.md @@ -0,0 +1,116 @@ +# 拨打电话 + +## 场景介绍 + +开发者可以通过两种不同的方式实现拨打电话的功能: +- 对于系统应用,开发者可以使用dial接口,直接进行音频/视频呼叫,在应用界面显示对应的通话。 +- 对于三方应用,开发者可以使用makecall接口,拉起系统电话应用,用户可以自行呼出通话。 + +## 基本概念 + +- 通话状态码 + 将当前的通话状态上报给app,可以根据当前的通话状态去做一些逻辑处理。例如在当前没有正在进行呼叫的时候,可以正常拨打新的一通电话。 + + | 名称 | 值 | 说明 | + | ------------------ | ---- | ------------------------------------------------------------ | + | CALL_STATE_UNKNOWN | -1 | 无效状态,当获取呼叫状态失败时返回。 | + | CALL_STATE_IDLE | 0 | 表示没有正在进行的呼叫。 | + | CALL_STATE_RINGING | 1 | 表示来电正在振铃或等待。 | + | CALL_STATE_OFFHOOK | 2 | 表示至少有一个呼叫处于拨号、通话中或呼叫保持状态,并且没有新的来电振铃或等待。 | + +## 约束与限制 + +1. 仅支持在标准系统上运行。 +2. 设备需插入可用的SIM卡。 + + +## 接口说明 + +> **说明:** +> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-call.md)。 + +| 接口名 | 描述 | +| ----------------------------------------------------------------------------------- | ------------------------------------------------------------ | +| hasVoiceCapability(): boolean; | 判断是否具有语音功能。 | +| dial(phoneNumber: string, callback: AsyncCallback): void | 拨号。该接口为系统接口。 | +| makeCall(phoneNumber: string, callback: AsyncCallback): void | 转到拨号屏幕,显示被叫号码。 | + +observer模块为开发者提供订阅和取消订阅通话业务状态的功能。具体API说明详见[接口文档](../reference/apis/js-apis-observer.md)。 + +| 接口名 | 描述 | +| ------------------------------------------------------------ | ------------------ | +| on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ state: CallState, number: string }>): void | 监听通话状态变化。 | + +## 开发步骤 + +### 使用dial拨打电话(仅供系统应用使用) + +1. 声明接口调用所需要的权限:ohos.permission.PLACE_CALL +ohos.permission.PLACE_CALL权限级别为system_basic,在申请权限前,请保证符合[权限使用的基本原则](../security/accesstoken-overview.md#权限使用的基本原则)。然后参考[配置文件权限声明指导文档](../security/accesstoken-guidelines.md#配置文件权限声明)声明对应权限。 +2. 导入call和observer模块。 +3. 调用hasVoiceCapability,确认当前设备是否支持拨号。 + 如果设备支持呼叫能力,则继续跳转到拨号界面,并显示拨号的号码。 +4. 调用dial接口,拨打电话。 +5.(可选)订阅通话业务状态变化。 + ```js + // import需要的模块 + import call from '@ohos.telephony.call' + import observer from '@ohos.telephony.observer' + + // 调用查询能力接口 + let isSupport = call.hasVoiceCapability(); + if (!isSupport) { + console.log("not support voice capability, return."); + return; + } + // 如果设备支持呼叫能力,调用以下接口进行拨号 + call.dial("13xxxx", (err, data) => { + this.output = this.output + `dial: ${JSON.stringify(data)}\n` + console.log(`callback: dial err->${JSON.stringify(err)} data->${JSON.stringify(data)}`) + }) + + // 订阅通话业务状态变化(可选) + observer.on("callStateChange", {slotId: 0}, (data) => { + console.log("call state change, data is:" + JSON.stringify(data)); + }); + ``` + +### 使用makecall拨打电话 + +1. 导入call和observer模块。 +2. 调用hasVoiceCapability,确认当前设备是否支持拨号。 + 如果设备支持呼叫能力,则继续跳转到拨号界面,并显示拨号的号码。 +3. 调用makecall接口,拉起系统电话应用,拨打电话。 +4.(可选)订阅通话业务状态变化。 + + ```js + // import需要的模块 + import call from '@ohos.telephony.call' + import observer from '@ohos.telephony.observer' + + // 调用查询能力接口 + let isSupport = call.hasVoiceCapability(); + if (!isSupport) { + console.log("not support voice capability, return."); + return; + } + // 如果设备支持呼叫能力,则继续跳转到拨号界面,并显示拨号的号码 + call.makeCall("13xxxx", (err)=> { + if (!err) { + console.log("make call success."); + } else { + console.log("make call fail, err is:" + JSON.stringify(err)); + } + }); + + // 订阅通话业务状态变化(可选) + observer.on("callStateChange", {slotId: 0}, (data) => { + console.log("call state change, data is:" + JSON.stringify(data)); + }); + ``` + +## 相关实例 + +拨打电话有以下相关实例可供参考: + +- [拨打电话](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/Call) diff --git a/zh-cn/application-dev/telephony/telephony-overview.md b/zh-cn/application-dev/telephony/telephony-overview.md index 2870b050a9ce77a4c4729b9b0505721ff2048d50..34583ca3c98debfda5989c6b95d34d71fae0b615 100644 --- a/zh-cn/application-dev/telephony/telephony-overview.md +++ b/zh-cn/application-dev/telephony/telephony-overview.md @@ -1,14 +1,17 @@ # 电话服务开发概述 -电话服务系统提供了一系列的API用于[拨打电话](../reference/apis/js-apis-call.md)、获取[无线蜂窝网络](../reference/apis/js-apis-telephony-data.md)和[SIM卡](../reference/apis/js-apis-sim.md)相关信息。 +电话服务系统提供系列API帮助开发者开发通讯类应用,包括: -应用可以通过调用API来获取当前注册网络名称、网络服务状态、信号强度以及SIM卡的相关信息,具体可参考[获取当前蜂窝网络信号信息](cellular-network-signal-info.md)开发指导。 +- call模块(拨打电话):系统应用可以直接拨打电话,在应用界面显示通话;三方应用可以拉起系统电话应用,跳转至拨号界面,从而实现拨打电话的功能,具体可参考[拨打电话开发指导](telephony-call.md)。除此之外,应用还可以通过call模块,实现格式化电话号码、判断是否紧急号码等功能,详情请参考[@ohos.telephony.call API参考](../reference/apis/js-apis-call.md)。 -直接拨打电话需要系统权限ohos.permission.PLACE_CALL,建议应用使用makeCall(),跳转到拨号界面,并显示拨号的号码,具体可参考[跳转拨号界面](jumping-to-the-dial-screen.md)开发指导。 +- sms模块(短信服务):应用可以实现创建、发送短信消息的功能,具体可参考[发送短信开发指导](telephony-sms.md)。除此之外,应用还可以实现获取、设置短信服务中心地址,和检查当前设备是否具备短信发送和接收能力等功能,详情请参考[@ohos.telephony.sms API参考](../reference/apis/js-apis-sms.md)。 +- radio模块(网络搜索):应用可以调用API获取当前注册网络名称、网络服务状态以及信号强度相关信息,详情请参考[@ohos.telephony.radio API参考](../reference/apis/js-apis-radio.md)。 +- data模块(蜂窝数据):蜂窝数据是无线通讯技术标准的一种,从数据的传输到交换都采用分组技术(Packet Switch),能够为移动设备提供话音、数据、视频图像等业务,经常用于支持用户在智能设备上使用应用程序,以及在移动网络上浏览网页,详情请参考[@ohos.telephony.data API参考](../reference/apis/js-apis-telephony-data.md)。 + +- sim模块(SIM卡管理):应用可以调用API获取SIM卡相关信息,如服务提供商、ISO(International Organization for Standardization,国际标准化组织)国家码、归属PLMN(Public Land Mobile Network,公共陆地移动网络)号等,详情请参考[@ohos.telephony.sim API参考](../reference/apis/js-apis-sim.md)。 -## 约束与限制 -搭载设备需要支持以下硬件: +## 约束与限制 -可以进行独立蜂窝通信的Modem以及SIM卡。 \ No newline at end of file +在调用电话服务API前,请确保使用的硬件设备有可以独立蜂窝通信的Modem和SIM卡。 diff --git a/zh-cn/application-dev/telephony/telephony-sms.md b/zh-cn/application-dev/telephony/telephony-sms.md new file mode 100644 index 0000000000000000000000000000000000000000..15050311040ed94a7a8d10cde184e8e512cd8498 --- /dev/null +++ b/zh-cn/application-dev/telephony/telephony-sms.md @@ -0,0 +1,118 @@ +# 短信服务 + +## 场景介绍 + +短信服务模块提供了管理短信的一些基础能力,包括创建、发送短信,获取、设置发送短信的默认SIM卡槽ID,获取、设置短信服务中心地址,以及检查当前设备是否具备短信发送和接收能力等。 + +## 基本概念 + +- 短信服务 + + 即SMS(Short Messaging Service),是一种存储和转发服务。用户的移动电话可以通过它进行相互收发短信,内容以文本、数字或二进制非文本数据为主。发送方的信息通过短信服务中心进行储存并转发给接收方。 + +- 短信服务中心 + + 即SMSC(Short Message Service Center),负责在基站和移动设备间中继、储存或转发短消息。移动设备到短信服务中心的协议能传输来自移动设备或朝向移动设备的短消息,协议内容遵从GMS 03.40协议。 + +- 协议数据单元 + + 即PDU(Protocol Data Unit),PDU模式收发短信可以使用3种编码:7-bit、8-bit和UCS-2编码。7-bit编码用于发送普通的ASCII字符,8-bit编码通常用于发送数据短信,UCS-2编码用于发送Unicode字符。 + +## 约束与限制 + +1. 仅支持在标准系统上运行。 +2. 需授予发送短信权限且插入SIM卡才可成功发送短信。 + + +## 接口说明 + +> **说明:** +> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-sms.md)。 + +| 接口名 | 描述 | +| ------------------------------------------------------------ | ------------------------------------------------------- | +| createMessage(pdu: Array, specification: string, callback: AsyncCallback): void | 基于协议数据单元(PDU)和指定的SMS协议创建SMS消息实例。 | +| sendMessage(options: SendMessageOptions): void | 发送文本或数据SMS消息。 | +| getDefaultSmsSlotId(callback: AsyncCallback): void | 获取用于发送短信的默认SIM卡。 | +| setSmscAddr(slotId: number, smscAddr: string, callback: AsyncCallback): void | 根据指定的插槽ID设置短信服务中心的地址。 | +| getSmscAddr(slotId: number, callback: AsyncCallback): void | 根据指定的插槽ID获取短信服务中心地址。 | + + +## 开发步骤 + +1. 声明接口调用所需要的权限: + - 如果是想发送短信,则调用sendMessage接口,需要配置ohos.permission.SEND_MESSAGES权限,权限级别为system_basic。 + - 如果是想设置短信服务中心地址,则调用setSmscAddr接口,需要配置ohos.permission.SET_TELEPHONY_STATE权限,权限级别为system_basic。 + - 如果是想获取短信服务中心地址,则调用getSmscAddr接口,需要配置ohos.permission.GET_TELEPHONY_STATE权限,权限级别为system_basic。 + 在申请权限前,请保证符合[权限使用的基本原则](../security/accesstoken-overview.md#权限使用的基本原则)。然后参考[配置文件权限声明指导文档](../security/accesstoken-guidelines.md#配置文件权限声明)声明对应权限。 + +2. import需要的模块。 + +3. 基于协议数据单元(PDU)和指定的SMS协议创建SMS消息实例。 + +4. 发送SMS消息。 + + ```js + // import需要的模块 + import sms from '@ohos.telephony.sms' + + export default class SmsModel { + async createMessage() { + const specification = '3gpp' + const pdu = [0x08, 0x91] // 以数组的形式显示协议数据单元(PDU),类型为number + const shortMessage = await sms.createMessage(pdu, specification) + Logger.info(`${TAG}, createMessageCallback: shortMessage = ${JSON.stringify(shortMessage)}`) + return shortMessage + } + + sendMessage(slotId, content, destinationHost, serviceCenter, destinationPort, handleSend, handleDelivery) { + Logger.info(`${TAG}, sendMessage start ${slotId} ${content} ${destinationHost} ${serviceCenter} ${destinationPort}`) + const options = + { + slotId: slotId, + content: content, + destinationHost: destinationHost, + serviceCenter: serviceCenter, + destinationPort: destinationPort, + sendCallback(err, data) { + Logger.info(`${TAG}, sendCallback: data = ${JSON.stringify(data)} err = ${JSON.stringify(err)}`) + handleSend(err, data) + }, + deliveryCallback(err, data) { + Logger.info(`${TAG}, deliveryCallback: data = ${JSON.stringify(data)} err = ${JSON.stringify(err)}`) + handleDelivery(err, data) + } + } + // 发送SMS消息 + sms.sendMessage(options) + Logger.info(`${TAG}, sendMessage end`) + } + + // 获取用于发送短信的默认SIM卡 + async getDefaultSmsSlotId() { + const defaultSmsSlotId = await sms.getDefaultSmsSlotId() + Logger.info(`${TAG}, getDefaultSmsSlotId: defaultSmsSlotId = ${defaultSmsSlotId}`) + return defaultSmsSlotId + } + + // 根据指定的插槽ID设置短信服务中心的地址 + async setSmscAddr(slotId, smscAddr) { + const serviceCenter = await sms.setSmscAddr(slotId, smscAddr) + Logger.info(`${TAG}, setSmscAddr: serviceCenter = ${JSON.stringify(serviceCenter)}`) + return serviceCenter + } + + // 根据指定的插槽ID获取短信服务中心地址 + async getSmscAddr(slotId) { + const serviceCenter = await sms.getSmscAddr(slotId) + Logger.info(`${TAG}, getSmscAddr: serviceCenter = ${JSON.stringify(serviceCenter)}`) + return serviceCenter + } + } + ``` + + +## 相关实例 + +针对短信的使用,有以下相关实例可供参考: +- [短信服务](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/Message) diff --git a/zh-cn/application-dev/tools/Readme-CN.md b/zh-cn/application-dev/tools/Readme-CN.md index 817df156a6735de838661c0bf68b09925d6d22f4..8d00e136013134ad7f0f0015c4d49e5971dbc908 100644 --- a/zh-cn/application-dev/tools/Readme-CN.md +++ b/zh-cn/application-dev/tools/Readme-CN.md @@ -7,3 +7,4 @@ - [拆包工具](unpacking-tool.md) - [cem工具](cem-tool.md) - [anm工具](anm-tool.md) +- [restool工具](restool.md) diff --git a/zh-cn/application-dev/tools/restool.md b/zh-cn/application-dev/tools/restool.md new file mode 100755 index 0000000000000000000000000000000000000000..c69595ea160dea9be2673bda27f58ee253c56080 --- /dev/null +++ b/zh-cn/application-dev/tools/restool.md @@ -0,0 +1,74 @@ +# restool工具 + + +## 简介 + +restool(资源编译工具)是一种资源构建工具。通过编译资源文件创建资源索引、解析资源。restool保存在sdk安装目录下的toolchains子目录。 + +## 参数说明 + +restool当前支持以下命令选项: + +| 选项 | 是否可缺省 | 是否存在入参 | 描述 | +| -------- | -------- | -------- | -------- | +| -i | 不可缺省 | 带参数 | 指定需要构建的资源目录或者需要构建的资源中间文件目录。同一个命令可以多次指定。 | +| -j | 不可缺省 | 带参数 | 指定config.json或者module.json文件路径。 | +| -o | 不可缺省 | 带参数 | 指定已编译资源的输出路径。 | +| -p | 不可缺省 | 带参数 | 指定编译资源的bundle名称。 | +| -r | 不可缺省 | 带参数 | 指定资源的头文件路径,有三种格式:“.txt”、“.js”、“.h”。 | +| -e | 可缺省 | 带参数 | 指定生成资源的起始ID值,例如:0x01000000,范围[0x01000000, 0x06FFFFFF),[0x08000000, 0x41FFFFFF) | +| -f | 可缺省 | 不带参数 | 如果输出路径已经存在。强制删除,重新生成。 | +| -h | 可缺省 | 不带参数 | 查看工具帮助信息。 | +| -m | 可缺省 | 带参数 | 多模块联合编译时,指定多个模块名。用“,”连接。 | +| -x | 可缺省 | 带参数 | 指定生成中间文件的资源目录或单个资源路径。同一个命令可以多次指定。 | +| -z | 可缺省 | 不带参数 | 针对资源终将文件目录,生成编译结果。 | +| -v | 可缺省 | 不带参数 | 查看工具版本号。 | +| --ids | 可缺省 | 带参数 | 指定生成id_defined.json的输出目录。 | +| --defined-ids | 可缺省 | 带参数 | 指定id_defined.json文件路径,一般都是通过--ids生成。
id_defined.json包含资源类型、名称及其ID的列表。
开发者可以自定义id_defined.json中的资源ID。 | + +## 使用实例 + +例如:entry目录结构如下 +``` +entry/src/main +| |----resource +| | |----base +| | | |----element +| | | |----media +| | | |----profile +| | |----rawfile +| |----config.json/module.json +``` + +构建资源全量命令: + +``` +restool -i entry/src/main -j entry/src/main/module.json -p com.ohos.demo -o out -r out/ResourceTable.txt -f +``` + +构建资源增量命令(仅预览模式可用),具体步骤如下: + +1.生成资源中间件: +``` +restool -x entry/src/main/resource -o out +``` +2.编译中间件: +``` +restool -i out1 -i out2 -o out -p com.ohos.demo -r out/ResourceTable.txt -j entry/src/main/module.json -f -z +``` + +固定资源ID的方式有两种,如下: + +方式一:在resource/base/element/目录下存放自定义id_defined.json文件。构建成功后,生成的ID值将会和id_defined.json文件中自定义的ID值保持一致。 + +方式二:通过--ids 命令生成id_defined.json文件。--defined-ids命令指定id_defined.json文件。构建成功后,生成的ID值将会和id_defined.json文件中自定义的ID值保持一致。 + +生成id_defined.json文件: +``` +restool -i entry/src/main -j entry/src/main/module.json -p com.ohos.demo -o out -r out/ResourceTable.txt --ids out/id_defined.json -f +``` + +指定资源ID固定的id_defined.json文件: +``` +restool -i entry/src/main -j entry/src/main/module.json -p com.ohos.demo -o out1 -r out1/ResourceTable.txt --defined-ids out/id_defined.json -f +``` \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-overview.md b/zh-cn/application-dev/ui/ui-ts-overview.md index 304ddc7382ecb17004bc0fb1c515ec831ad21660..308bcc78c26833500e59f53225a828411bd0432a 100644 --- a/zh-cn/application-dev/ui/ui-ts-overview.md +++ b/zh-cn/application-dev/ui/ui-ts-overview.md @@ -88,4 +88,4 @@ ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get- - [`UpgradePopup`:自定义弹窗(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/UpgradePopup) -- [CustomComponent:组件化(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/CustomComponent) \ No newline at end of file +- [CustomComponent:组件化(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/CustomComponent) diff --git a/zh-cn/application-dev/webgl/webgl-guidelines.md b/zh-cn/application-dev/webgl/webgl-guidelines.md index b4456e87ca3331c61bf069d504508a02d0274e07..644fe8b172683880599c370f49292b3e3afbc99a 100644 --- a/zh-cn/application-dev/webgl/webgl-guidelines.md +++ b/zh-cn/application-dev/webgl/webgl-guidelines.md @@ -4,6 +4,10 @@ WebGL主要帮助开发者在前端开发中完成图形图像的相关处理,比如绘制彩色图形等。 +> **说明:** +> +> 目前该功能仅支持使用兼容JS的类Web开发范式开发。 + ## 接口说明 diff --git a/zh-cn/device-dev/subsystems/subsys-build-module.md b/zh-cn/device-dev/subsystems/subsys-build-module.md index 07c0b3022f064ca92c99795b200684f510ac7514..d9e2fd92a0778ae9fab621b399cca13313f8a57a 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-module.md +++ b/zh-cn/device-dev/subsystems/subsys-build-module.md @@ -62,18 +62,21 @@ ohos_shared_library("helloworld") { part_name = [string] # 必选,所属部件名称 output_dir - + # Sanitizer配置,每项都是可选的,默认为false/空 sanitize = { # 各个Sanitizer开关 - cfi = [boolean] - integer_overflow = [boolean] + cfi = [boolean] # 控制流完整性检测 + integer_overflow = [boolean] # 整数溢出检测 + boundary_sanitize = [boolean] # 边界检测 + ubsan = [boolean] # 部分ubsan选项 + all_ubsan = [boolean] # 全量ubsan选项 ... debug = [boolean] # 调测模式 blocklist = [string] # 屏蔽名单路径 } - + testonly = [boolean] license_as_sources = [] license_file = [] # 后缀名是.txt的文件 @@ -106,18 +109,21 @@ ohos_static_library("helloworld") { lib_dirs = [] public_configs = [] - + # Sanitizer配置,每项都是可选的,默认为false/空 sanitize = { # 各个Sanitizer开关 - cfi = [boolean] - integer_overflow = [boolean] + cfi = [boolean] # 控制流完整性检测 + integer_overflow = [boolean] # 整数溢出检测 + boundary_sanitize = [boolean] # 边界检测 + ubsan = [boolean] # 部分ubsan选项 + all_ubsan = [boolean] # 全量ubsan选项 ... debug = [boolean] # 调测模式 blocklist = [string] # 屏蔽名单路径 } - + remove_configs = [] no_default_deps = [] license_file = [] # 后缀名是.txt的文件 @@ -141,18 +147,21 @@ ohos_executable("helloworld") { ] # 这里依赖的模块必须是依赖的部件声明在inner_kits中的模块 ohos_test = [] test_output_dir = [] - + # Sanitizer配置,每项都是可选的,默认为false/空 sanitize = { # 各个Sanitizer开关 - cfi = [boolean] - integer_overflow = [boolean] + cfi = [boolean] # 控制流完整性检测 + integer_overflow = [boolean] # 整数溢出检测 + boundary_sanitize = [boolean] # 边界检测 + ubsan = [boolean] # 部分ubsan选项 + all_ubsan = [boolean] # 全量ubsan选项 ... debug = [boolean] # 调测模式 blocklist = [string] # 屏蔽名单路径 } - + testonly = [boolean] license_as_sources = [] license_file = [] # 后缀名是.txt的文件 @@ -187,18 +196,21 @@ ohos_source_set("helloworld") { external_deps = [ # 跨部件模块依赖定义, "part_name:module_name", # 定义格式为 "部件名:模块名称" ] # 这里依赖的模块必须是依赖的部件声明在inner_kits中的模块 - + # Sanitizer配置,每项都是可选的,默认为false/空 sanitize = { # 各个Sanitizer开关 - cfi = [boolean] - integer_overflow = [boolean] + cfi = [boolean] # 控制流完整性检测 + integer_overflow = [boolean] # 整数溢出检测 + boundary_sanitize = [boolean] # 边界检测 + ubsan = [boolean] # 部分ubsan选项 + all_ubsan = [boolean] # 全量ubsan选项 ... debug = [boolean] # 调测模式 blocklist = [string] # 屏蔽名单路径 } - + testonly = [boolean] license_as_sources = [] license_file = [] diff --git a/zh-cn/device-dev/subsystems/subsys-build-reference.md b/zh-cn/device-dev/subsystems/subsys-build-reference.md index 3279c9bb5db88525830fd336df94124412eec7e6..2a0530161bbf031a9c725a69a791ace1ec635c9a 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-reference.md +++ b/zh-cn/device-dev/subsystems/subsys-build-reference.md @@ -68,8 +68,11 @@ ``` shell ohos_shared_library("example") { sanitize = { - cfi = true - integer_overflow = true + cfi = true # 开启控制流完整性检测 + integer_overflow = true # 开启整数溢出检测 + boundary_sanitize = true # 开启边界检测 + ubsan = true # 开启部分ubsan选项 + all_ubsan = true # 开启全量ubsan选项 debug = true # 可选,调测模式,默认是不开启 blocklist = "./blocklist.txt" # 可选,屏蔽名单路径 } @@ -83,6 +86,9 @@ - 整数溢出排错:unsigned_integer_overflow/signed_integer_overflow/integer_overflow(同时包括无符号和有符号整数溢出两种检查) - 控制流完整性:cfi +- 边界检测:boundary_sanitize +- 部分未定义行为检测:ubsan(bool,integer-divide-by-zero,return,returns-nonnull-attribute,shift-exponent,unreachable,vla-bound等编译选项) +- 全量未定义行为检测:all_ubsan(全量undefined behavior sanitizer编译选项) **发布、调测模式** diff --git "a/zh-cn/readme/\347\224\265\350\257\235\346\234\215\345\212\241\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\347\224\265\350\257\235\346\234\215\345\212\241\345\255\220\347\263\273\347\273\237.md" index af05135d8347c7fed29359967831f316a5056c8c..deee8ba6f71171a3e68b8d3038291c911c21266e 100644 --- "a/zh-cn/readme/\347\224\265\350\257\235\346\234\215\345\212\241\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\347\224\265\350\257\235\346\234\215\345\212\241\345\255\220\347\263\273\347\273\237.md" @@ -45,7 +45,7 @@ base/telephony/ ## 约束 1. 目前开源的范围包括蜂窝通话(仅支持CS通话)、短信、数据上网,支持双SIM卡框架。 -2. 南向HDI依赖芯片厂商适配,详见:[电话服务南向开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-tel.md)。 +2. 南向HDI依赖芯片厂商适配,详见:[电话服务南向开发指导](../device-dev/subsystems/subsys-tel-overview.md)。 ## 使用说明 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.6-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.6-release.md new file mode 100644 index 0000000000000000000000000000000000000000..da1e6c71bbac5c508443b019c81efa6a8048c240 --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.1.6-release.md @@ -0,0 +1,145 @@ +# OpenHarmony 3.1.6 Release + + +## 版本概述 + +当前版本在OpenHarmony 3.1.5 Release的基础上,修复了内存泄漏及linux kernel等开源组件的安全漏洞,增强了系统安全性。修复了部分系统稳定性的issue,增强了系统稳定性。更新配套的SDK版本。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.1.6 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.12.5 (API Version 8 Relese) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.1.12.5 (API Version 8 Release) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
DevEco Studio 3.0 Beta4版本起,通过DevEco Studio获取的SDK默认为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 3.1 Preview for OpenHarmony | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.6-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二** + +通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.6-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + +**表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.1.6 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/code-v3.1.6-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/code-v3.1.6-Release.tar.gz.sha256) | +| Hi3516标准系统解决方案(二进制) | 3.1.6 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_hi3516.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_hi3516.tar.gz.sha256) | +| RK3568标准系统解决方案(二进制) | 3.1.6 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_rk3568.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/standard_rk3568.tar.gz.sha256) | +| Hi3861轻量系统解决方案(二进制) | 3.1.6 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_pegasus.tar.gz.sha256) | +| Hi3516小型系统解决方案-LiteOS(二进制) | 3.1.6 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus.tar.gz.sha256) | +| Hi3516小型系统解决方案-Linux(二进制) | 3.1.6 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/hispark_taurus_linux.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.1.12.5 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.1.12.5 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.1.12.5 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-mac-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.1.12.5 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.6/ohos-sdk-public.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony 3.1.5 Release的基础上有如下变更。 + + +### 特性变更 + +本次版本无新增特性及变更。 + +### API变更 + +3.1.6 Release对比3.1.5 Release API接口无变更。 + + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +### 修复缺陷列表 + +**表3** 修复缺陷issue列表 + +| 子系统 | 问题描述 | +| ------------------ | ------------------------------------------------------------ | +| 应用子系统 | com.ohos.callui应用多次出现jscrash 栈名:updateCallTimeList([I5LWIW](https://gitee.com/openharmony/applications_call/issues/I5LWIW)) | +| 全球化子系统 | 关键进程com.ohos.launcher下的com.ohos.launch线程多次出现libglobal_resmgr.z.so异常栈([I5LT0M](https://gitee.com/openharmony/global_resource_management/issues/I5LT0M))
进程com.ohos.permissionmanager下的2.ui线程多次出现libglobal_resmgr.z.so异常栈([I68J7P](https://gitee.com/openharmony/global_resource_management/issues/I68J7P)) | +| Misc软件服务子系统 | 进程com.example.kikakeyboard出现cppcrash, libinputmethod_client.z.so([I66W3B](https://gitee.com/openharmony/inputmethod_imf/issues/I66W3B))
通过工具进行压测出现CPPCrash问题([I65K13](https://gitee.com/openharmony/inputmethod_imf/issues/I65K13)) | +| 分布式硬件 | com.ohos.devicemanagerui多次出现jscrash([I69LD9](https://gitee.com/openharmony/distributedhardware_device_manager/issues/I69LD9)) | +| 分布式软总线 | 分布式图库组网重启后对端设备媒体资源显示不出来([I674LD](https://gitee.com/openharmony/applications_photos/issues/I674LD)) | + + + + +### 修复安全漏洞列表 + +**表4** 修复安全问题列表 + +| ISSUE | 问题描述 | 修复链接 | +| -------- | -------- | -------- | +| I5UI5A | 修复组件kernel_linux_5.10上的CVE-2022-41218、CVE-2022-3424、CVE-2022-42328、CVE-2022-3643、CVE-2022-47946安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/646) | +| I69WX6 | 修复组件ffmpeg上的CVE-2022-3341安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_ffmpeg/pulls/74) | +| I68JS0 | 修复组件ffmpeg上的CVE-2022-3109安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_ffmpeg/pulls/71) | +| I671DT | 修复组件curl上的CVE-2022-43551、CVE-2022-43552安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_curl/pulls/99) | +| I6A4YJ | 修复组件kernel_linux_5.10上的CVE-2022-20568安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/629) | +| I6A55C | 修复组件kernel_linux_5.10上的CVE-2023-0047安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/631) | + +## 遗留缺陷列表 + +**表5** 遗留缺陷列表 + +| issue | 问题描述 | 影响 | 计划解决日期 | +| ------------------------------------------------------------ | ---------------------------------------------------------- | ---------------- | ------------ | +| [I6AF0Y](https://gitee.com/openharmony/ability_ability_runtime/issues/I6AF0Y) | 两个窗口分屏配对后,关闭其中一个窗口,另一个窗口也会关闭。 | 分屏功能退出失效 | 2/15 | + diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-LocalStorage.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-LocalStorage.md new file mode 100644 index 0000000000000000000000000000000000000000..b26cfb5125493aa5d9227e32f74f3ad8a9caba8e --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelog-LocalStorage.md @@ -0,0 +1,116 @@ +# ArkUI子系统LocalStorage类接口ChangeLog + +## cl.LocalStorage.1 get接口返回类型变更 + +**变更影响** + +返回类型从get(propName: string): T变更为get(propName: string): T | undefined +应用不需要进行适配。 + +## cl.LocalStorage.2 setOrCreate参数newValue变成必选 +**变更影响** + +原接口声明: +```js +setOrCreate(propName: string, newValue?: T): boolean +``` +现接口声明: +```js +setOrCreate(propName: string, newValue: T): boolean +``` +第二个参数newValue变为必选。 +如果应用调用这个接口没有指定newValue参数,在替换新的sdk后会编译不过,需要手动指定newValue。 + +**适配指导** + +```js +let storage = new LocalStorage(); +storage.setOrCreate('propA', 'hello'); +``` +## cl.LocalStorage.3 link参数和返回类型变更 +**变更影响** + +原接口声明: +```js +link(propName: string, linkUser?: T, subscribersName?: string): T +``` +现接口声明: +```js +link(propName: string): SubscribedAbstractProperty +``` +1. link第二三个参数为框架内部调用,不应对外开发,所以将接口变更为一个参数; +2. 返回类型T变更为SubscribedAbstractProperty; + +**适配指导** + +```js +let storage = new LocalStorage({"PropA": "47"}); +let linA = storage.link("PropA"); +linA.set(50); +``` + +## cl.LocalStorage.4 setAndLink参数和返回类型变更 +**变更影响** + +原接口声明: +```js +setAndLink(propName: string, defaultValue: T, linkUser?: T, subscribersName?: string): T +``` +现接口声明: +```js +setAndLink(propName: string, defaultValue: T): SubscribedAbstractProperty +``` +1. setAndLink第三四个参数为框架内部调用,不应对外开发,所以将接口变更为2个参数; +2. 返回类型T变更为SubscribedAbstractProperty; + +**适配指导** + +```js +let storage = new LocalStorage({"PropA": "47"}); +let linA = storage.setAndLink("PropA", "48") +linA.set(50); +``` + +## cl.LocalStorage.5 prop参数和返回类型变更 +**变更影响** + +原接口声明: +```js +prop(propName: string, propUser?: T, subscribersName?: string): T +``` +现接口声明: +```js +prop(propName: string): SubscribedAbstractProperty +``` +1. prop第二三个参数为框架内部调用,不应对外开发,所以将接口变更为1个参数; +2. 返回类型T变更为SubscribedAbstractProperty; + +**适配指导** + +```js +let storage = new LocalStorage({"PropA": "47"}); +let propA = storage.prop("PropA"); +propA.set(51); // one-way sync +``` + +## cl.LocalStorage.6 setAndProp参数和返回类型变更 +**变更影响** + +原接口声明: +```js +setAndProp(propName: string, defaultValue: T, propUser?: T, subscribersName?: string): T +``` +现接口声明: +```js +setAndProp(propName: string, defaultValue: S): SubscribedAbstractProperty +``` +1. setAndProp第三四个参数为框架内部调用,不应对外开发,所以将接口变更为2个参数; +2. 返回类型T变更为SubscribedAbstractProperty; + +**适配指导** + +```js +let storage = new LocalStorage({"PropA": "47"}); +let propA = storage.setAndProp("PropA", "48"); +propA.set(51); // one-way sync +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-ability.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-ability.md index 9f4bb4556589e98c26ad2746c213c07c72bb2217..19e914fa005fa0acb6d9a0a59512a6454f36a38e 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-ability.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-ability.md @@ -99,7 +99,7 @@ onWindowStageCreate() { - 方法 registerAbilityLifecycleCallback、unregisterAbilityLifecycleCallback、registerEnvironmentCallback、unregisterEnvironmentCallback 被删除。可以使用 on、off 替换。 - application/ServiceExtensionContext.d.ts - 方法 connectAbility、connectAbilityWithAccount、disconnectAbility 被删除。可以使用 connectServiceExtensionAbility、connectServiceExtensionAbilityWithAccount、disconnectServiceExtensionAbility 替换。 -- @ohos.application.ExtensionAbility.d.ts +- @ohos.application.FormExtension.d.ts - 生命周期onCreate、onCastToNormal、onUpdate、onVisibilityChange、onEvent、onDestroy、onAcquireFormState、onShare 被删除。可以使用@ohos.app.form.FormExtensionAbility.d.ts的onAddForm、onCastToNormalForm、onUpdateForm、onChangeFormVisibility、onFormEvent、onRemoveForm、onAcquireFormState、onShareForm - @ohos.application.abilityDelegatorRegistry.d.ts - 导出类 AbilityDelegator、AbilityDelegatorArgs、AbilityMonitor、ShellCmdResult 被删除。可以使用@ohos.app.ability.abilityDelegatorRegistry.d.ts中的同名导出类替换。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md index 4ef6169a1e412d95b7ea091c17459ebd2bcc7b44..8b8cad7dbf026cb17c1599e61ebdbae510073a30 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-account_os_account.md @@ -20,7 +20,6 @@ ```ts import account_osAccount from "@ohos.account.osAccount" -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' let accountMgr = account_osAccount.getAccountManager(); let domainInfo = { @@ -31,6 +30,67 @@ try { await accountMgr.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo); await accountMgr.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo); } catch (err) { - expect(err.code).assertEqual(12300004); + console.log("activateOsAccount err: " + JSON.stringify(err)); // error.code = 12300004; } ``` + +## cl.account_os_account.2 应用帐号getAllAccounts接口权限场景变更 + +应用使用getAllAccounts接口查询自己可访问的帐号列表时,不需要申请权限ohos.permission.GET_ALL_APP_ACCOUNTS。 + +**变更影响** + +基于此后版本开发的应用,查询自己可访问的帐号列表时,无需申请权限。 + +**关键接口/组件变更** +- AccountManager + - getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void; + - getAllAccounts(): Promise<Array<AppAccountInfo>>; + +**适配指导** + +应用未申请ohos.permission.GET_ALL_APP_ACCOUNTS,查询自己可访问的帐号列表示例代码如下: + +```ts +import account_appAccount from "@ohos.account.appAccount" + +let accountMgr = account_appAccount.createAppAccountManager(); +try { + await accountMgr.addAccount("accessibleAccount_promise_nopermission"); + var data = await accountMgr.getAllAccounts(); + if (data[0].name == "accessibleAccount_promise_nopermission") { + console.log("getAllAccounts successfully"); + } +} catch (err) { + console.log("getAllAccounts err: " + JSON.stringify(err)); +} +``` + +## cl.account_os_account.3 应用帐号getAccountsByOwner接口权限场景变更 + +应用使用getAccountsByOwner接口查询可访问的指定应用的帐号列表时,不需要申请权限ohos.permission.GET_ALL_APP_ACCOUNTS。 + +**变更影响** + +基于此后版本开发的应用,查询指定应用可访问的帐号列表时,无需申请权限。 + +**关键接口/组件变更** +- AccountManager + - getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void; + - getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>>; + +**适配指导** + +应用未申请ohos.permission.GET_ALL_APP_ACCOUNTS,查询指定应用可访问的帐号列表示例代码如下: + +```ts +import account_appAccount from "@ohos.account.appAccount" + +let accountMgr = account_appAccount.createAppAccountManager(); +try { + var ownerName = "com.example.owner"; + var data = await accountMgr.getAllAccounts(ownerName); +} catch (err) { + console.log("getAllAccounts err: " + JSON.stringify(err)); +} +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.6/changelogs-ability.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.6/changelogs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..903fbad8c70147006c457bca8c4a7e6548a8b808 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.6/changelogs-ability.md @@ -0,0 +1,36 @@ +# 元能力子系统ChangeLog + +## cl.ability.1 appRecovery接口中RestartFlag属性名称变更,删除了未支持的属性 + +appRecovery接口中RestartFlag枚举命名从特定故障发生后**不重启**改成了特定故障发生后**重启**。 +删除了CPP_CRASH_NO_RESTART。 + +**变更影响** + +3.2.10.6版本之前使用CPP_CRASH_NO_RESTART/JS_CRASH_NO_RESTART/APP_FREEZE_NO_RESTART类型开发的应用,在3.2.10.6版本之后行为会发生变化。 + +**关键接口/组件变更** + +**RestartFlag** 9+ + +变更前: +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALWAYS_RESTART | 0 | 总是重启应用。 | +| CPP_CRASH_NO_RESTART | 0x0001 | 发生CPP_CRASH时**不重启**应用。 | +| JS_CRASH_NO_RESTART | 0x0002 | 发生JS_CRASH时**不重启**应用。 | +| APP_FREEZE_NO_RESTART | 0x0004 | 发生APP_FREEZE时**不重启**应用。 | +| NO_RESTART | 0xFFFF | 总是不重启应用。 | + +变更后: +| 名称 | 值 | 说明 | +| ---------- | ---- | ---------- | +| ALWAYS_RESTART | 0 | 总是重启应用。 | +| CPP_CRASH_NO_RESTART | NA | **删除**,不支持该场景的重启。 | +| RESTART_WHEN_JS_CRASH | 0x0001 | 发生JS_CRASH时**重启**应用。 | +| RESTART_WHEN_APP_FREEZE | 0x0002 | 发生APP_FREEZE时**重启**应用。 | +| NO_RESTART | 0xFFFF | 总是不重启应用。 | + +**适配指导** + +按新的语义进行适配。 \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..5740c1bc54aa92cc3e32843d28ad907d7ad39e21 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-ability.md @@ -0,0 +1,109 @@ +# 元能力子系统JS API变更Changelog + +## cl.ability.1 AreaMode接口变更 +AreaMode接口有多个重复,删除掉重复的AreaMode。 + +**变更影响** + +影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.app.ability.common.d.ts | common.AreaMode | | 删除 | +| application/Context.d.ts | AreaMode | | 删除 | + + +**适配指导** + +使用@ohos.app.ability.contextConstant.d.ts中的AreaMode + +```ts +import contextConstant from '@ohos.app.ability.contextConstant'; +let area: contextConstant.AreaMode = contextConstant.AreaMode.EL1; +``` + + + +## cl.ability.2 killProcessesBySelf接口变更 + +killProcessesBySelf接口命名不合理,修改为killAllProcesses。 + +**变更影响** + +影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------------ | ------------------ | ----------------------------------------------------- | -------- | +| application/ApplicationContext | ApplicationContext | killProcessesBySelf(): Promise\; | 删除 | +| application/ApplicationContext | ApplicationContext | killProcessesBySelf(callback: AsyncCallback\); | 删除 | +| application/ApplicationContext | ApplicationContext | killAllProcesses(): Promise\; | 新增 | +| application/ApplicationContext | ApplicationContext | killAllProcesses(callback: AsyncCallback\); | 新增 | + + +**适配指导** + +应用中调用killProcessesBySelf可参考下列代码 + +变更前代码: + +```ts +let context: common.UIAbilityContext = globalThis.abilityContext; +let appContext = context.getApplicationContext(); +appContext.killProcessesBySelf() +``` + +变更后代码: + +```ts +let context: common.UIAbilityContext = globalThis.abilityContext; +let appContext = context.getApplicationContext(); +appContext.killAllProcesses() +``` + + + +## cl.ability.3 getProcessRunningInformation接口变更 + +getProcessRunningInformation接口命名不合理,修改为getRunningProcessInformation。 + +**变更影响** + +影响API9版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ----------------------------------- | ------------------ | ------------------------------------------------------------ | -------- | +| @ohos.app.ability.appManager.d.ts | appManager | function getProcessRunningInformation(): Promise\\>; | 删除 | +| @ohos.app.ability.appManager.d.ts | appManager | function getProcessRunningInformation(callback: AsyncCallback\\>): void; | 删除 | +| @ohos.app.ability.appManager.d.ts | appManager | function getRunningProcessInformation(): Promise\\>; | 新增 | +| @ohos.app.ability.appManager.d.ts | appManager | function getRunningProcessInformation(callback: AsyncCallback\\>): void; | 新增 | +| application/ApplicationContext.d.ts | ApplicationContext | getProcessRunningInformation(): Promise\\>; | 删除 | +| application/ApplicationContext.d.ts | ApplicationContext | getProcessRunningInformation(callback: AsyncCallback\\>): void; | 删除 | +| application/ApplicationContext.d.ts | ApplicationContext | getRunningProcessInformation(): Promise\\>; | 新增 | +| application/ApplicationContext.d.ts | ApplicationContext | getRunningProcessInformation(callback: AsyncCallback\\>): void; | 新增 | + +**适配指导** + +应用中调用getProcessRunningInformation可参考下列代码 + +变更前代码: + +```ts +let context: common.UIAbilityContext = globalThis.abilityContext; +let appContext = context.getApplicationContext(); +appContext.getProcessRunningInformation() +``` + +变更后代码: + +```ts +let context: common.UIAbilityContext = globalThis.abilityContext; +let appContext = context.getApplicationContext(); +appContext.getRunningProcessInformation() +``` + diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-bundlemanager.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..c6af59bceb2177840fc4d5a64ba2d8469a707909 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.7/changelogs-bundlemanager.md @@ -0,0 +1,73 @@ +# 包管理子系统ChangeLog + +## cl.bundlemanager.1 包管理删除@ohos.bundle.bundleManager.d.ts中的getAbilityIcon接口,可以使用@ohos.resourceManager.d.ts中的getMediaContent替换。 + +包管理删除[@ohos.bundle.bundleManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.bundleManager.d.ts)中的getAbilityIcon接口,可以使用[@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts)中的getMediaContent替换。 + +**变更影响**
+使用之前已发布的API 9各beta版本且使用到了getAbilityIcon接口的,需要改为使用getMediaContent接口。 + +**关键的接口/组件变更**
+删除@ohos.bundle.bundleManager.d.ts中的getAbilityIcon接口。 + +**适配指导**
+使用@ohos.bundle.bundleManager.d.ts下面的getAbilityIcon,需要修改为@ohos.resourceManager.d.ts中的getMediaContent。需要提前获取到图标的资源ID值,可参考该接口的[使用指导](../../../application-dev/reference/apis/js-apis-resource-manager.md#getmediacontent9)。 + +## cl.bundlemanager.2 包管理底层能力变更,仅支持系统资源HAP自定义权限,其它HAP均不支持自定义权限。 + +仅支持系统资源HAP自定义权限,其它HAP均不支持自定义权限。包管理在解析HAP时,仅支持解析资源HAP(包名为:ohos.global.systemres)的配置文件中的definePermissions字段,该字段用来定义权限。其它HAP中配置的definePermissions字段将不会解析。 +如果有应用需要自定义权限,可以在资源HAP的[配置文件](https://gitee.com/openharmony/utils_system_resources/blob/master/systemres/main/config.json)中definePermissions字段下面新增定义权限。格式可参考[定义权限](../../../application-dev/quick-start/module-structure.md#definepermissions对象内部结构)。 + + +**变更影响**
+升级新版本镜像后,应用自定义的权限将不会生效,使用方在申请该权限时,会授权失败。 + +**关键的接口/组件变更**
+包管理底层能力变更,仅支持系统资源HAP自定义权限,其它HAP均不支持自定义权限。 + +**适配指导**
+如果有应用需要自定义权限,可以在资源HAP的[配置文件](https://gitee.com/openharmony/utils_system_resources/blob/master/systemres/main/config.json)中definePermissions字段下面新增定义权限。格式可参考[定义权限](../../../application-dev/quick-start/module-structure.md#definepermissions对象内部结构)。 + +## cl.bundlemanager.3 包管理二级模块文件名称变更,修改为文件内对应的接口名称 + +包管理二级模块文件名称变更,修改为文件内对应的接口名称,变更文件如下: + +| 原文件名称 |变更后文件名称 | +|----|----| +| bundleManager/abilityInfo.d.ts | bundleManager/AbilityInfo.d.ts | +| bundleManager/applicationInfo.d.ts | bundleManager/ApplicationInfo.d.ts | +| bundleManager/bundleInfo.d.ts | bundleManager/BundleInfo.d.ts | +| bundleManager/dispatchInfo.d.ts | bundleManager/DispatchInfo.d.ts | +| bundleManager/elementName.d.ts | bundleManager/ElementName.d.ts | +| bundleManager/extensionAbilityInfo.d.ts | bundleManager/ExtensionAbilityInfo.d.ts | +| bundleManager/hapModuleInfo.d.ts | bundleManager/HapModuleInfo.d.ts | +| bundleManager/launcherAbilityInfo.d.ts | bundleManager/LauncherAbilityInfo.d.ts | +| bundleManager/metadata.d.ts | bundleManager/Metadata.d.ts | +| bundleManager/packInfo.d.ts | bundleManager/BundlePackInfo.d.ts | +| bundleManager/permissionDef.d.ts | bundleManager/PermissionDef.d.ts | +| bundleManager/remoteAbilityInfo.d.ts | bundleManager/RemoteAbilityInfo.d.ts | +| bundleManager/shortcutInfo.d.ts | bundleManager/ShortcutInfo.d.ts | + +除了免安装相关的BundlePackInfo文件名称增加了Bundle,其余文件名称均是修改为大写开头。 + +**变更影响**
+仅修改二级模块文件名称,不会影响一级模块的使用。在使用之前已发布的API 9各beta版本时,如果在ts文件中直接导入了bundleManager下面二级模块接口的,IDE中编译报错的话,需要修改导入的文件名称。 + +**关键的接口/组件变更**
+变更bundleManager文件夹下面的d.ts名称,修改为文件中的接口名称。 + +**适配指导**
+使用新的sdk后,正常情况下应用无需适配该变更。如果在应用中直接导入了bundleManager文件夹下面的文件,则需要修改导入的文件名称。可以按照如下的修改方式: + +**修改前:** +```ts +import {AbilityInfo} from 'bundleManger/abilityInfo'; +import {ExtensionAbilityInfo} from 'bundleManger/extensionAbilityInfo'; +import {BundlePackInfo} from 'bundleManger/packInfo'; +``` +**修改后:** +```ts +import {AbilityInfo} from 'bundleManger/AbilityInfo'; +import {ExtensionAbilityInfo} from 'bundleManger/ExtensionAbilityInfo'; +import {BundlePackInfo} from 'bundleManger/BundlePackInfo'; +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-distributeddatamgr.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-distributeddatamgr.md new file mode 100644 index 0000000000000000000000000000000000000000..cea1a4047360d76a40fe1c715909a8709b83a375 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-distributeddatamgr.md @@ -0,0 +1,48 @@ +# 分布式数据管理子系统JS API变更Changelog + +## cl.distributeddatamgr.1 接口变更 +distributeddatamgr子系统relationalStore组件接口存在变更: + +变更前: +应用调用getRdbStore接口后,通过返回对象rdbStore的openStatus属性(openStatus == ON_CREATE)判断数据库是否为新创建。 +变更后: +应用调用getRdbStore接口后,通过返回对象rdbStore的version属性(version == 0)判断数据库是否为新创建。 + +开发者需要根据以下说明对应用进行适配。 + + **变更影响** + +影响API10版本的JS接口,应用需要进行适配才可以在新版本SDK环境正常实现功能。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------------ | --------------- | ---------------- | ------- | +| @ohos.data.relationalStore | RdbStore | openStatus: number; 改为 version: number; | 变更 | + + +**适配指导** + +应用中设置和获取数据库版本可参考下列代码: + +```ts +const STORE_CONFIG = { + name: "rdbstore.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + // 变更前: + // if (rdbStore.openStatus == ON_CREATE) { + // rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) // create table xxx + // } + + // 变更后: + if (rdbStore.version == 0) { + rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) // create table xxx + // 设置数据库版本,值为大于0的正整数 + rdbStore.version == 3 + } + // 获取数据库版本 + console.info("Get RdbStore version is " + rdbStore.version) +}) +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-sensor.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..bfec2426ed62dc23cd29c88d180f6e1960d7f73b --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-sensor.md @@ -0,0 +1,49 @@ +# 泛sensor子系统ChangeLog + +## cl.ability.1 Sensor接口中venderName属性名称变更,更改为vendorName。 + +venderName为错别字,更正为vendorName。 + +**变更影响** + +该venderName属性无法再使用,请使用新增属性vendorName替换。 + +**关键的接口/组件变更** + +- 变更前: + +```js + interface Sensor { + sensorName:string; /**< Sensor name */ + venderName:string; /**< Sensor vendor version */ + firmwareVersion:string; /**< Sensor firmware version */ + hardwareVersion:string; /**< Sensor hardware version */ + sensorId:number; /**< Sensor type ID, {@code SensorType} */ + maxRange:number; /**< Maximum measurement range of the sensor */ + minSamplePeriod:number; /**< Minimum sample period allowed, in ns */ + maxSamplePeriod:number; /**< maximum sample period allowed, in ns */ + precision:number; /**< Sensor accuracy */ + power:number; /**< Sensor power */ + } +``` + +- 变更后: + +```js + interface Sensor { + sensorName:string; /**< Sensor name */ + vendorName:string; /**< Sensor vendor version */ + firmwareVersion:string; /**< Sensor firmware version */ + hardwareVersion:string; /**< Sensor hardware version */ + sensorId:number; /**< Sensor type ID, {@code SensorType} */ + maxRange:number; /**< Maximum measurement range of the sensor */ + minSamplePeriod:number; /**< Minimum sample period allowed, in ns */ + maxSamplePeriod:number; /**< maximum sample period allowed, in ns */ + precision:number; /**< Sensor accuracy */ + power:number; /**< Sensor power */ + } +``` + +**适配指导** + +该venderName属性删除无法再使用,请使用新增属性vendorName替换。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.3.2/changelog-security.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.3.2/changelog-security.md new file mode 100644 index 0000000000000000000000000000000000000000..4a91c2a910e8f7b7a0fee4daaef30c1f74c3fe2d --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.3.2/changelog-security.md @@ -0,0 +1,61 @@ +# security子系统ChangeLog + +## cl.security.1 ParamsSpec属性名变更为algName。 +结构体ParamsSpec的属性algoName由于API命名统一,名称更改为algName。 + +**变更影响** + +影响已发布的JS接口,对ParamsSpec以及其子类IvParamsSpec,GcmParamsSpec与CcmParamsSpec,使用这些对象作为参数或返回值时,其属性名需要更改为algName。 +应用需要进行适配,才可以在新版本SDK环境正常编译通过。 + +**关键的接口/组件变更** + +修改前的接口原型: + + ```ts +interface ParamsSpec { + /** + * Indicates the algorithm name. Should be set before initialization of a cipher object. + * @type { string } + * @syscap SystemCapability.Security.CryptoFramework + * @since 9 + */ + algoName : string; +} + ``` +修改后的接口原型: + + ```ts +interface ParamsSpec { + /** + * Indicates the algorithm name. Should be set before initialization of a cipher object. + * @type { string } + * @syscap SystemCapability.Security.CryptoFramework + * @since 9 + */ + algName : string; +} + ``` + +**适配指导** + +对ParamsSpec以及其子类IvParamsSpec,GcmParamsSpec与CcmParamsSpec,使用这些对象作为参数或返回值时,其属性名需要从algoName更改为algName。 + ```ts +function genGcmParamsSpec() { + let arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0 , 0, 0]; // 12 bytes + let dataIv = new Uint8Array(arr); + let ivBlob = {data : dataIv}; + + arr = [0, 0, 0, 0 , 0, 0, 0, 0]; // 8 bytes + let dataAad = new Uint8Array(arr); + let aadBlob = {data : dataAad}; + + arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes + let dataTag = new Uint8Array(arr); + let tagBlob = {data : dataTag}; + let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algName : "GcmParamsSpec"}; + return gcmParamsSpec; +} + ``` +详细查看API参考中ParamsSpec对应的接口适配指南: +[加解密算法库框架-ParamsSpec-API参考](../../../application-dev/reference/apis/js-apis-cryptoFramework.md#paramsspec) \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md b/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md index b8baef9aa857112649ac8dec9b388be3624f4bd8..c7e6d21f570298ae525d9cbbbbd15329301d3dc0 100644 --- a/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md +++ b/zh-cn/release-notes/changelogs/v3.1-Release/changelogs-account_os_account.md @@ -33,25 +33,25 @@ **适配指导** ```ts import account_osAccount from "@ohos.account.osAccount" -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' let accountMgr = account_osAccount.getAccountManager(); -accountMgr.createOsAccount('account_test', account_osAccount.OsAccountType.GUEST).then((accountInfo) => { - expect(accountInfo.type).assertEqual(account_osAccount.OsAccountType.GUEST); +accountMgr.createOsAccount("account_test", account_osAccount.OsAccountType.GUEST).then((accountInfo) => { + if (accountInfo.type == account_osAccount.OsAccountType.GUEST) { + console.log("createOsAccount successfully"); + } accountMgr.activateOsAccount(accountInfo.localId).then(() => { - console.log('activateOsAccount successfully'); + console.log("activateOsAccount successfully"); accountMgr.getOsAccountTypeFromProcess().then((accountType) => { - expect(accountType).assertEqual(account_osAccount.OsAccountType.GUEST); + if (accountType == account_osAccount.OsAccountType.GUEST) { + console.log("getOsAccountTypeFromProcess successfully"); + } }).catch((err) => { - console.log('activateOsAccount err: ' + JSON.stringify(err)); - expect().assertFail(); + console.log("activateOsAccount err: " + JSON.stringify(err)); }); }).catch((err) => { - console.log('activateOsAccount err: ' + JSON.stringify(err)); - expect().assertFail(); + console.log("activateOsAccount err: " + JSON.stringify(err)); }); }).catch((err) => { - console.log('createOsAccount err: ' + JSON.stringify(err)); - expect().assertFail(); + console.log("createOsAccount err: " + JSON.stringify(err)); }); ``` diff --git a/zh-cn/website.md b/zh-cn/website.md index 61370de150269925f62de0510ccaa16ed342e262..6fa4303f428e661c368ca9a1bf9a7a9b99f6705a 100644 --- a/zh-cn/website.md +++ b/zh-cn/website.md @@ -4,6 +4,7 @@ - [术语](glossary.md) - 版本说明 - OpenHarmony 3.x Releases + - [OpenHarmony v3.2 Beta5 (2023-01-30)](release-notes/OpenHarmony-v3.2-beta5.md) - [OpenHarmony v3.2 Beta4 (2022-11-30)](release-notes/OpenHarmony-v3.2-beta4.md) - [OpenHarmony v3.2 Beta3 (2022-09-30)](release-notes/OpenHarmony-v3.2-beta3.md) - [OpenHarmony v3.2 Beta2 (2022-07-30)](release-notes/OpenHarmony-v3.2-beta2.md)