diff --git a/CODEOWNERS b/CODEOWNERS index e62f30a3bd5e21f7ed3f181a108e770f518ac4da..638941c1a2a1765ad2a55dd81cf65ca72dce37be 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -338,7 +338,7 @@ zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenm zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids -zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @Buda-Liu @ningningW @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @liuzuming @ningningW @yangqing3 zh-cn/application-dev/reference/apis/js-apis-environment.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-errorManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-eventhub.md @jayleehw @RayShih @li-weifeng2 @currydavids @@ -384,7 +384,7 @@ zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge- zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-list.md @gongjunsong @ge-yafang @flyingwolf @BlackStone -zh-cn/application-dev/reference/apis/js-apis-logs.md @huaweimaxuchu @ningningW @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-logs.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xxb-wzy @currydavids zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy @@ -456,7 +456,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @nin zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong zh-cn/application-dev/reference/apis/js-apis-thermal.md @aqxyjay @zengyawen @aqxyjay @alien0208 -zh-cn/application-dev/reference/apis/js-apis-timer.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-timer.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-touchevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-treemap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-treeset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md index a8dbb1b636a19fe6a2b7e6dee741b56dac0e6289..1aecb0171e73b02bcbcb9347497f594bf96c912e 100644 --- a/en/OpenHarmony-Overview.md +++ b/en/OpenHarmony-Overview.md @@ -189,7 +189,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code ## How to Participate -For details about how to join in the OpenHarmony community, see [OpenHarmony Community](https://gitee.com/openharmony/community/blob/master/README-EN.md) +For details about how to join in the OpenHarmony community, see [OpenHarmony Community](https://gitee.com/openharmony/community/blob/master/README_EN.md) For details about how to contribute, see [How to contribute](contribute/how-to-contribute.md). diff --git a/en/application-dev/ability-deprecated/ability-delegator.md b/en/application-dev/ability-deprecated/ability-delegator.md index f72a192dc510c28104511fb1530a915c9f9827cc..b32d472176a5b6270fece94ae4bd8ae9a7bd73fa 100644 --- a/en/application-dev/ability-deprecated/ability-delegator.md +++ b/en/application-dev/ability-deprecated/ability-delegator.md @@ -63,7 +63,7 @@ For details about how to use DevEco Studio to start the test framework, see [Ope **Example** ```javascript -import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); @@ -87,11 +87,11 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { **Modules to Import** ```javascript -import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' ``` ```javascript -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() ``` ### Starting an Ability and Listening for the Ability State diff --git a/en/application-dev/ability-deprecated/fa-dataability.md b/en/application-dev/ability-deprecated/fa-dataability.md index 8d94e8f225a3966d676e6c7631968c25f5634531..217f617db77ff329eb1d0fa0eef7dcb6172cf45a 100644 --- a/en/application-dev/ability-deprecated/fa-dataability.md +++ b/en/application-dev/ability-deprecated/fa-dataability.md @@ -154,7 +154,7 @@ The basic dependency packages include: import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_rdb from '@ohos.data.rdb' - + var urivar = "dataability:///com.ix.DataAbility" var DAHelper = featureAbility.acquireDataAbilityHelper( urivar diff --git a/en/application-dev/ability-deprecated/fa-formability.md b/en/application-dev/ability-deprecated/fa-formability.md index 5c08a1b0b3955472d6f3b16cf7a343a083a0116a..96ed58d8ef2206d6c66e413d0a6fc34423651974 100644 --- a/en/application-dev/ability-deprecated/fa-formability.md +++ b/en/application-dev/ability-deprecated/fa-formability.md @@ -25,7 +25,7 @@ Carry out the following operations to develop the widget provider based on the [ 1. Implement lifecycle callbacks by using the **LifecycleForm** APIs. 2. Create a **FormBindingData** instance. 3. Update a widget by using the **FormProvider** APIs. -4. Develop the widget UI pages. +4. Develop the widget UI page. ## Available APIs @@ -231,7 +231,7 @@ You should override **onDestroy** to implement widget data deletion. } ``` -For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md). The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. @@ -402,3 +402,5 @@ The code snippet is as follows: } } ``` + + \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/fa-pageability.md b/en/application-dev/ability-deprecated/fa-pageability.md index 28b5ce36e292acc9e350f8ae96cb7bcf17f8c8c3..e28c0f2823ff61f6c60f469eaaf9d197184e8f50 100644 --- a/en/application-dev/ability-deprecated/fa-pageability.md +++ b/en/application-dev/ability-deprecated/fa-pageability.md @@ -47,7 +47,7 @@ You can specify the launch type by setting **launchType** in the **config.json** | Launch Type | Description |Description | | ----------- | ------- |---------------- | -| standard | Multi-instance | A new instance is started each time an ability starts.| +| standard | Multi-instance | A new instance is started each time an ability starts.| | singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| By default, **singleton** is used. diff --git a/en/application-dev/ability-deprecated/stage-ability-continuation.md b/en/application-dev/ability-deprecated/stage-ability-continuation.md index b53d57d849c8c771b92d4e86a2095163aab0a395..f99966aff24d9b465627ba475cda018671820809 100644 --- a/en/application-dev/ability-deprecated/stage-ability-continuation.md +++ b/en/application-dev/ability-deprecated/stage-ability-continuation.md @@ -6,7 +6,7 @@ Ability continuation is to continue the current mission of an application, inclu ## Available APIs -The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). +The following table lists the APIs used for ability continuation. For details about the APIs, see [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md). **Table 1** Ability continuation APIs @@ -48,96 +48,88 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar } ``` - - - - Configure the application startup type. - - If **launchType** is set to **standard** in the **module.json5** file, the application is of the multi-instance launch type. During ability continuation, regardless of whether the application is already open, the target starts the application and restores the UI page. If **launchType** is set to **singleton**, the application is of the singleton launch type. If the application is already open, the target clears the existing page stack and restores the UI page. For more information, see "Launch Type" in [Ability Development](./stage-ability.md). + + If **launchType** is set to **multiton** in the **module.json5** file, the application is of the multi-instance launch type. During ability continuation, regardless of whether the application is already open, the target starts the application and restores the UI page. If **launchType** is set to **singleton**, the application is of the singleton launch type. If the application is already open, the target clears the existing page stack and restores the UI page. For more information, see "Launch Type" in [Ability Development](./stage-ability.md). + + Configure a multi-instance application as follows: + + ```javascript + { + "module": { + "abilities": [ + { + "launchType": "multiton" + } + ] + } + } + ``` + + Configure a singleton application as follows or retain the default settings of **launchType**: + + ```javascript + { + "module": { + "abilities": [ + { + "launchType": "singleton" + } + ] + } + } + ``` + + - Apply for the distributed permissions. - Configure a multi-instance application as follows: + Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. - ```javascript - { - "module": { - "abilities": [ - { - "launchType": "standard" - } - ] - } - } - ``` + ```javascript + "requestPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + }, + ``` - Configure a singleton application as follows or retain the default settings of **launchType**: + This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: - ```javascript - { - "module": { - "abilities": [ - { - "launchType": "singleton" + ```javascript + requestPermissions = async () => { + let permissions: Array = [ + "ohos.permission.DISTRIBUTED_DATASYNC" + ]; + let needGrantPermission = false + let accessManger = accessControl.createAtManager() + Logger.info("app permission get bundle info") + let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100) + Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`) + for (const permission of permissions) { + Logger.info(`app permission query grant status ${permission}`) + try { + let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission) + if (grantStatus === PERMISSION_REJECT) { + needGrantPermission = true + break; + } + } catch (err) { + Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`) + needGrantPermission = true + break; + } + } + if (needGrantPermission) { + Logger.info("app permission needGrantPermission") + try { + await accessManger.requestPermissionsFromUser(this.context, permissions) + } catch (err) { + Logger.error(`app permission ${JSON.stringify(err)}`) + } + } else { + Logger.info("app permission already granted") + } } - ] - } - } - ``` - - - - - Apply for the distributed permissions. - - Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. - - ```javascript - "requestPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - }, - ``` - - - - This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: - - ```javascript - requestPermissions = async () => { - let permissions: Array = [ - "ohos.permission.DISTRIBUTED_DATASYNC" - ]; - let needGrantPermission = false - let accessManger = accessControl.createAtManager() - Logger.info("app permission get bundle info") - let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100) - Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`) - for (const permission of permissions) { - Logger.info(`app permission query grant status ${permission}`) - try { - let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission) - if (grantStatus === PERMISSION_REJECT) { - needGrantPermission = true - break; - } - } catch (err) { - Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`) - needGrantPermission = true - break; - } - } - if (needGrantPermission) { - Logger.info("app permission needGrantPermission") - try { - await accessManger.requestPermissionsFromUser(this.context, permissions) - } catch (err) { - Logger.error(`app permission ${JSON.stringify(err)}`) - } - } else { - Logger.info("app permission already granted") - } - } - ``` - - + ``` + 2. Implement the **onContinue()** API. @@ -155,7 +147,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar You can obtain the target device ID (identified by the key **targetDevice**) and the version number (identified by the key **version**) of the application installed on the target device from the **wantParam** parameter of this API. The version number can be used for compatibility check. If the current application version is incompatible with that on the target device, **OnContinueResult.MISMATCH** can be returned to reject the continuation request. - Example + Example: ```javascript onContinue(wantParam : {[key: string]: any}) { @@ -168,8 +160,6 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar } ``` - - 3. Implement the continuation logic in the **onCreate()** or **onNewWant()** API. The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. @@ -178,11 +168,9 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar After data restore is complete, call **restoreWindowStage** to trigger page restoration. - - You can also use **want.parameters.version** in the **want** parameter to obtain the application version number of the initiator. - - Example + + Example: ```javascript import UIAbility from '@ohos.app.ability.UIAbility'; @@ -190,7 +178,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar export default class EntryAbility extends UIAbility { storage : LocalStorag; - + onCreate(want, launchParam) { Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { @@ -211,7 +199,7 @@ For a singleton ability, use **onNewWant()** to achieve the same implementation. Use distributed objects. -Distributed objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](../database/database-distributedobject-guidelines.md). +Distributed objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Sharing Distributed Data Objects](../database/data-sync-of-distributed-data-object.md). In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. @@ -249,8 +237,6 @@ In the ability continuation scenario, the distributed data object is used to syn }); ``` - - - The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated. ```javascript @@ -283,8 +269,6 @@ In the ability continuation scenario, the distributed data object is used to syn } ``` - - ### More Information 1. Timeout @@ -294,15 +278,13 @@ In the ability continuation scenario, the distributed data object is used to syn 2. By default, the system supports page stack information migration, which means that the page stack of the initiator will be automatically migrated to the target device. No adaptation is required. - - ### Restrictions 1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/module-configuration-file.md). 2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system. - - ### Best Practice For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. + + \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-ability.md b/en/application-dev/ability-deprecated/stage-ability.md index 60f954c78f306193e7bfefe1e6ceee2babf86da4..2cd18f7aa3052cee86785d55bc81d68cfdece802 100644 --- a/en/application-dev/ability-deprecated/stage-ability.md +++ b/en/application-dev/ability-deprecated/stage-ability.md @@ -12,8 +12,8 @@ An ability can be launched in the **standard**, **singleton**, or **specified** | Launch Type | Description |Action | | ----------- | ------- |---------------- | -| standard | Standard mode | A new instance is started each time an ability starts.| -| singleton | Singleton mode | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| +| multiton | Multi-instance mode| A new instance is started each time an ability starts.| +| singleton | Singleton mode | Default type. The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| By default, the singleton mode is used. The following is an example of the **module.json5** file: @@ -39,7 +39,7 @@ The table below describes the APIs provided by the **AbilityStage** class, which |onAcceptWant(want: Want): string|Called when a specified ability is started.| |onConfigurationUpdated(config: Configuration): void|Called when the global configuration is updated.| -The table below describes the APIs provided by the **Ability** class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). +The table below describes the APIs provided by the **Ability** class. For details about the APIs, see [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md). **Table 2** Ability APIs @@ -190,7 +190,7 @@ export default class EntryAbility extends UIAbility { ``` ## Starting an Ability ### Available APIs -The **Ability** class has the **context** attribute, which belongs to the **AbilityContext** class. The **AbilityContext** class has the **abilityInfo**, **currentHapModuleInfo**, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md). +The **Ability** class has the **context** attribute, which belongs to the **AbilityContext** class. The **AbilityContext** class has the **abilityInfo**, **currentHapModuleInfo**, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md). **Table 3** AbilityContext APIs |API|Description| @@ -207,7 +207,7 @@ The **Ability** class has the **context** attribute, which belongs to the **Abil An application can obtain the context of an **Ability** instance through **this.context** and then use the **startAbility** API in the **AbilityContext** class to start the ability. The ability can be started by specifying **Want**, **StartOptions**, and **accountId**, and the operation result can be returned using a callback or **Promise** instance. The sample code is as follows: ```ts let context = this.context -var want = { +let want = { "deviceId": "", "bundleName": "com.example.MyApplication", "abilityName": "EntryAbility" @@ -224,7 +224,7 @@ context.startAbility(want).then(() => { In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows: ```ts let context = this.context -var want = { +let want = { "deviceId": getRemoteDeviceId(), "bundleName": "com.example.MyApplication", "abilityName": "EntryAbility" @@ -239,9 +239,9 @@ Obtain the ID of a specified device from **DeviceManager**. The sample code is a ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - var list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + if (typeof dmClass === 'object' && dmClass !== null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') { console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } diff --git a/en/application-dev/ability-deprecated/stage-call.md b/en/application-dev/ability-deprecated/stage-call.md index 71f5f6934dda385161f4adcb95837924c691c278..d9269295e06633fa0f55bdebad51eb1c354f2934 100644 --- a/en/application-dev/ability-deprecated/stage-call.md +++ b/en/application-dev/ability-deprecated/stage-call.md @@ -31,12 +31,12 @@ The ability call process is as follows: > Currently, only system applications can use the ability call. ## Available APIs -The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller). +The table below describes the ability call APIs. For details, see [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md#caller). **Table 2** Ability call APIs |API|Description| |:------|:------| -|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or **ServiceExtensionContext**.| +|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall) or **ServiceExtensionContext**.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.| |call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability.| @@ -47,242 +47,263 @@ The table below describes the ability call APIs. For details, see [Ability](../r ## How to Develop The procedure for developing the ability call is as follows: 1. Create a callee ability. - 2. Access the callee ability. ### Creating a Callee Ability For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. -**1. Configure the ability launch type.** - - Set **launchType** of the callee ability to **singleton** in the **module.json5** file. -|JSON Field|Description| -|:------|:------| -|"launchType"|Ability launch type. Set this parameter to **singleton**.| - -An example of the ability configuration is as follows: -```json -"abilities":[{ - "name": ".CalleeAbility", - "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", - "launchType": "singleton", - "description": "$string:CalleeAbility_desc", - "icon": "$media:icon", - "label": "$string:CalleeAbility_label", - "visible": true -}] -``` -**2. Import the Ability module.** -```ts -import Ability from '@ohos.app.ability.UIAbility' -``` -**3. Define the agreed sequenceable data.** - - The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The code snippet is as follows: -```ts -export default class MySequenceable { - num: number = 0 - str: string = "" - - constructor(num, string) { - this.num = num - this.str = string - } - - marshalling(messageParcel) { - messageParcel.writeInt(this.num) - messageParcel.writeString(this.str) - return true - } - - unmarshalling(messageParcel) { - this.num = messageParcel.readInt() - this.str = messageParcel.readString() - return true - } -} -``` -**4. Implement Callee.on and Callee.off.** - - The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The code snippet is as follows: -```ts -const TAG: string = '[CalleeAbility]' -const MSG_SEND_METHOD: string = 'CallSendMsg' - -function sendMsgCallback(data) { - console.log('CalleeSortFunc called') - - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, '') - data.readSequenceable(receivedData) - console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`) - - // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) -} - -export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - } - - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD) - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) - } - } -} -``` +1. **Configure the ability launch type.** + + Set **launchType** of the callee ability to **singleton** in the **module.json5** file. + + |JSON Field|Description| + |:------|:------| + |"launchType"|Ability launch type. Set this parameter to **singleton**.| + + An example of the ability configuration is as follows: + + ```json + "abilities":[{ + "name": ".CalleeAbility", + "srcEntry": "./ets/CalleeAbility/CalleeAbility.ts", + "launchType": "singleton", + "description": "$string:CalleeAbility_desc", + "icon": "$media:icon", + "label": "$string:CalleeAbility_label", + "exported": true + }] + ``` + +2. **Import the UIAbility module.** + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + ``` + +3. **Define the agreed sequenceable data.** + + The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The code snippet is as follows: + + ```ts + export default class MySequenceable { + num: number = 0 + str: string = "" + + constructor(num, string) { + this.num = num + this.str = string + } + + marshalling(messageParcel) { + messageParcel.writeInt(this.num) + messageParcel.writeString(this.str) + return true + } + + unmarshalling(messageParcel) { + this.num = messageParcel.readInt() + this.str = messageParcel.readString() + return true + } + } + ``` + +4. **Implement Callee.on and Callee.off.** + + The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The code snippet is as follows: + + ```ts + const TAG: string = '[CalleeAbility]' + const MSG_SEND_METHOD: string = 'CallSendMsg' + + function sendMsgCallback(data) { + console.log('CalleeSortFunc called') + + // Obtain the sequenceable data sent by the caller ability. + let receivedData = new MySequenceable(0, '') + data.readSequenceable(receivedData) + console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`) + + // Process the data. + // Return the sequenceable data result to the caller ability. + return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) + } + + export default class CalleeAbility extends Ability { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + } + + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD) + } catch (error) { + console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) + } + } + } + ``` ### Accessing the Callee Ability -**1. Import the Ability module.** -```ts -import Ability from '@ohos.app.ability.UIAbility' -``` -**2. Obtain the Caller object.** - - The **context** attribute of the ability implements **startAbilityByCall** to obtain the **Caller** object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the **Caller** object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows: -```ts -// Register the onRelease listener of the caller ability. -private regOnRelease(caller) { - try { - caller.on("release", (msg) => { - console.log(`caller onRelease is called ${msg}`) - }) - console.log('caller register OnRelease succeed') - } catch (error) { - console.log(`caller register OnRelease failed with ${error}`) - } -} - -async onButtonGetCaller() { - try { - this.caller = await context.startAbilityByCall({ - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' - }) - if (this.caller === undefined) { - console.log('get caller failed') - return - } - console.log('get caller success') - this.regOnRelease(this.caller) - } catch (error) { - console.log(`get caller failed with ${error}`) - } -} -``` - In the cross-device scenario, you need to specify the ID of the peer device. The code snippet is as follows: -```ts -async onButtonGetRemoteCaller() { - var caller = undefined - var context = this.context - - context.startAbilityByCall({ - deviceId: getRemoteDeviceId(), - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' - }).then((data) => { - if (data != null) { - caller = data - console.log('get remote caller success') - // Register the onRelease listener of the caller ability. - caller.on("release", (msg) => { - console.log(`remote caller onRelease is called ${msg}`) - }) - console.log('remote caller register OnRelease succeed') - } - }).catch((error) => { - console.error(`get remote caller failed with ${error}`) - }) -} -``` - Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The code snippet is as follows: -```ts -import deviceManager from '@ohos.distributedHardware.deviceManager'; -var dmClass; -function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - var list = dmClass.getTrustedDeviceListSync() - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null") - return - } - console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) - return list[0].deviceId - } else { - console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null") - } -} -``` - In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows: -```ts -import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; - -requestPermission() { - let context = this.context - let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] - let atManager = abilityAccessCtrl.createAtManager(); - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) - }).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) - }) -} -``` -**3. Send agreed sequenceable data.** - - The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. The code snippet is as follows: -```ts -const MSG_SEND_METHOD: string = 'CallSendMsg' -async onButtonCall() { - try { - let msg = new MySequenceable(1, 'origin_Msg') - await this.caller.call(MSG_SEND_METHOD, msg) - } catch (error) { - console.log(`caller call failed with ${error}`) - } -} -``` - - In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. The code snippet is as follows: -```ts -const MSG_SEND_METHOD: string = 'CallSendMsg' -originMsg: string = '' -backMsg: string = '' -async onButtonCallWithResult(originMsg, backMsg) { - try { - let msg = new MySequenceable(1, originMsg) - const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) - console.log('caller callWithResult succeed') - - let result = new MySequenceable(0, '') - data.readSequenceable(result) - backMsg(result.str) - console.log(`caller result is [${result.num}, ${result.str}]`) - } catch (error) { - console.log(`caller callWithResult failed with ${error}`) - } -} -``` -**4. Release the Caller object.** - - When the **Caller** object is no longer required, use **release()** to release it. The code snippet is as follows: -```ts -releaseCall() { - try { - this.caller.release() - this.caller = undefined - console.log('caller release succeed') - } catch (error) { - console.log(`caller release failed with ${error}`) - } -} -``` +1. **Import the Ability module.** + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + ``` + +2. **Obtain the Caller object.** + + The **context** attribute of the ability implements **startAbilityByCall** to obtain the **Caller** object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the **Caller** object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows: + + ```ts + // Register the onRelease listener of the caller ability. + private regOnRelease(caller) { + try { + caller.on("release", (msg) => { + console.log(`caller onRelease is called ${msg}`) + }) + console.log('caller register OnRelease succeed') + } catch (error) { + console.log(`caller register OnRelease failed with ${error}`) + } + } + + async onButtonGetCaller() { + try { + this.caller = await context.startAbilityByCall({ + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }) + if (this.caller === undefined) { + console.log('get caller failed') + return + } + console.log('get caller success') + this.regOnRelease(this.caller) + } catch (error) { + console.log(`get caller failed with ${error}`) + } + } + ``` + + In the cross-device scenario, you need to specify the ID of the peer device. The code snippet is as follows: + + ```ts + async onButtonGetRemoteCaller() { + var caller = undefined + var context = this.context + + context.startAbilityByCall({ + deviceId: getRemoteDeviceId(), + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }).then((data) => { + if (data != null) { + caller = data + console.log('get remote caller success') + // Register the onRelease listener of the caller ability. + caller.on("release", (msg) => { + console.log(`remote caller onRelease is called ${msg}`) + }) + console.log('remote caller register OnRelease succeed') + } + }).catch((error) => { + console.error(`get remote caller failed with ${error}`) + }) + } + ``` + + Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The code snippet is as follows: + + ```ts + import deviceManager from '@ohos.distributedHardware.deviceManager'; + var dmClass; + function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + var list = dmClass.getTrustedDeviceListSync() + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null") + return + } + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) + return list[0].deviceId + } else { + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null") + } + } + ``` + + In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows: + + ```ts + import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; + + requestPermission() { + let context = this.context + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(context, permissions).then((data) => { + console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) + }).catch((error) => { + console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) + }) + } + ``` + +3. **Send agreed sequenceable data.** + + The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. The code snippet is as follows: + + ```ts + const MSG_SEND_METHOD: string = 'CallSendMsg' + async onButtonCall() { + try { + let msg = new MySequenceable(1, 'origin_Msg') + await this.caller.call(MSG_SEND_METHOD, msg) + } catch (error) { + console.log(`caller call failed with ${error}`) + } + } + ``` + + In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. The code snippet is as follows: + + ```ts + const MSG_SEND_METHOD: string = 'CallSendMsg' + originMsg: string = '' + backMsg: string = '' + async onButtonCallWithResult(originMsg, backMsg) { + try { + let msg = new MySequenceable(1, originMsg) + const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) + console.log('caller callWithResult succeed') + + let result = new MySequenceable(0, '') + data.readSequenceable(result) + backMsg(result.str) + console.log(`caller result is [${result.num}, ${result.str}]`) + } catch (error) { + console.log(`caller callWithResult failed with ${error}`) + } + } + ``` + +4. **Release the Caller object.** + + When the **Caller** object is no longer required, use **release()** to release it. The code snippet is as follows: + + ```ts + releaseCall() { + try { + this.caller.release() + this.caller = undefined + console.log('caller release succeed') + } catch (error) { + console.log(`caller release failed with ${error}`) + } + } + ``` \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md index bc1c54afe9d2e323f0938bca250f83737df9cbdb..8a0425f4fab41b97cd15ecb9986f77b4a108ae7a 100644 --- a/en/application-dev/ability-deprecated/stage-formextension.md +++ b/en/application-dev/ability-deprecated/stage-formextension.md @@ -135,7 +135,7 @@ To create a widget in the stage model, you need to implement lifecycle callbacks | Name | Description | Data Type | Default Value Allowed | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | | name | Name of the Extension ability. This field must be specified. | String | No | - | srcEntrance | Path of the Extension ability lifecycle code. This field must be specified.| String | No | + | srcEntry | Path of the Extension ability lifecycle code. This field must be specified.| String | No | | description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| | icon | Index of the Extension ability icon file. | String | Yes (initial value: left empty)| | label | Descriptive information about the Extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| @@ -150,7 +150,7 @@ To create a widget in the stage model, you need to implement lifecycle callbacks ```json "extensionAbilities": [{ "name": "FormAbility", - "srcEntrance": "./ets/FormAbility/FormAbility.ts", + "srcEntry": "./ets/FormAbility/FormAbility.ts", "label": "$string:form_FormAbility_label", "description": "$string:form_FormAbility_desc", "type": "form", @@ -242,7 +242,7 @@ You should override **onDestroy** to implement widget data deletion. } ``` -For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. @@ -366,7 +366,7 @@ You can set router and message events for components on a widget. The router eve 1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. 2. Set the router event. - **action**: **"router"**, which indicates a router event. - - **abilityName**: target ability name, for example, **EntryAbility**, which is the default UIAbility name in DevEco Studio for the stage model. + - **abilityName**: target ability name, for example, **EntryAbility**, which is the default main ability name in DevEco Studio for the stage model. - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the stage model, you can obtain **want** and its **parameters** field. 3. Set the message event. - **action**: **"message"**, which indicates a message event. @@ -413,3 +413,5 @@ The code snippet is as follows: } } ``` + + \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-serviceextension.md b/en/application-dev/ability-deprecated/stage-serviceextension.md index aee8f9c8116dffb49956a2bb9a1cad2ad263a166..8f77e3251d56ff8023d8215546a38b0614f5c8b3 100644 --- a/en/application-dev/ability-deprecated/stage-serviceextension.md +++ b/en/application-dev/ability-deprecated/stage-serviceextension.md @@ -33,8 +33,8 @@ OpenHarmony does not support creation of a Service Extension ability for third-p "icon": "$media:icon", "description": "service", "type": "service", - "visible": true, - "srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts" + "exported": true, + "srcEntry": "./ets/ServiceExtAbility/ServiceExtAbility.ts" }] ``` diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index ca206e65fd11a48631e950f26c1c9b656f298e13..1ad5989d2cf8258c46e219a239a2c8c5a1d1274c 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -24,6 +24,8 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: + +- [Web](web/web-component-overview.md) - [Notification](notification/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md) - [WebGL](webgl/Readme-EN.md) @@ -32,6 +34,7 @@ Then, equip yourself for developing the key features, with the following guideli - [Connectivity](connectivity/Readme-EN.md) - [Telephony Service](telephony/Readme-EN.md) - [Data Management](database/Readme-EN.md) +- [File Management](file-management/Readme-EN.md) - [Task Management](task-management/Readme-EN.md) - [Device Management](device/Readme-EN.md) - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) @@ -40,7 +43,6 @@ Then, equip yourself for developing the key features, with the following guideli - [Application Test](application-test/Readme-EN.md) - [IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/Readme-EN.md) -- [File Management](file-management/medialibrary-overview.md) ### Tools @@ -70,3 +72,5 @@ They are organized as follows: ### Readme For details about the principles and basic information of each subsystem, see the README file in [docs/en/readme](../readme). + + \ No newline at end of file diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index c7b49ac56b0638e8c4ba9908582683f9c4c46d21..8170d075cf08e8258b7c8b3731661f0e4959c6aa 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -4,7 +4,7 @@ The application development documents provide reference for you to develop appli The documents are carefully organized as follows: -### Getting Started +## Getting Started [Here](quick-start/start-overview.md) you'll learn how to quickly get started with OpenHarmony application development. @@ -12,7 +12,7 @@ Browse the documents on the instructions for quickly building your first applica Check out the development fundamentals, which comprise descriptions of the package structure configuration file for OpenHarmony applications and the instructions for use of resource files. -### Development +## Development To facilitate your application development, we provide development guidelines for key features. @@ -24,14 +24,17 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: + +- [Web](web/web-component-overview.md) - [Notification](notification/notification-overview.md) - [Window Manager](windowmanager/window-overview.md) - [WebGL](webgl/webgl-overview.md) -- [Media](media/audio-overview.md) +- [Media](media/media-application-overview.md) - [Security](security/userauth-overview.md) - [Connectivity](connectivity/ipc-rpc-overview.md) - [Telephony Service](telephony/telephony-overview.md) -- [Data Management](database/database-mdds-overview.md) +- [Data Management](database/data-mgmt-overview.md) +- [File Management](file-management/file-management-overview.md) - [Task Management](task-management/background-task-overview.md) - [Device](device/usb-overview.md) - [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md) @@ -40,32 +43,29 @@ Then, equip yourself for developing the key features, with the following guideli - [Application Test](application-test/arkxtest-guidelines.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md) -- [File Management](file-management/medialibrary-overview.md) -### Tools +## Tools DevEco Studio is a high-performance integrated development environment (IDE) recommended for developing OpenHarmony applications. [Here](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421) you can learn everything about DevEco Studio, including how to use this tool to create a project and sign, debug, and run an application. -### Hands-On Tutorials +## Hands-On Tutorials To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). -### API References +## API References API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. They are organized as follows: -- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - -- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - -- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) - -- [JS and TS APIs](reference/apis/js-apis-ability-dataUriUtils.md) - +- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-components-summary.md) +- [Component Reference (JavaScript-compatible Web-like Development Paradigm-ArkUI.Full)](reference/arkui-js/js-components-common-attributes.md) +- [Component Reference (JavaScript-compatible Web-like Development Paradigm-ArkUI.Lite)](reference/arkui-js-lite/js-framework-file.md) +- [JS Service Widget UI Components](reference/js-service-widget-ui/js-service-widget-file.md) +- [JS and TS APIs](reference/apis/development-intro.md) - Native APIs - [Standard Library](reference/native-lib/third_party_libc/musl.md) - - [Node_API](reference/native-lib/third_party_napi/napi.md) + - [Node_API](reference/native-lib/third_party_napi/napi.md) + \ No newline at end of file diff --git a/en/application-dev/device/inputdevice-guidelines.md b/en/application-dev/device/inputdevice-guidelines.md index da6eef71d750b74e01d1ea8a9eaaf49b1bf598cb..c15955d9b01239605d0ce1afa9bfe5f693b22940 100644 --- a/en/application-dev/device/inputdevice-guidelines.md +++ b/en/application-dev/device/inputdevice-guidelines.md @@ -29,7 +29,6 @@ When a user enters text, the input method determines whether to launch the virtu 1. Call the **getDeviceList** API to obtain the list of connected input devices. Call the **getKeyboardType** API to traverse all connected devices to check whether a physical keyboard exists. If a physical keyboard exists, mark the physical keyboard as connected. This step ensures that your application detects all inserted input devices before listening for device hot swap events. 2. Call the **on** API to listen for device hot swap events. If a physical keyboard is inserted, mark the physical keyboard as connected. If a physical keyboard is removed, mark the physical keyboard as disconnected. -3. When a user enters text, check whether a physical keyboard is connected. If a physical keyboard is not connected, launch the virtual keyboard. ```js @@ -65,6 +64,4 @@ try { } catch (error) { console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } - // 3. Determine whether to launch the virtual keyboard based on the value of isPhysicalKeyboardExist. - // TODO ``` diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md index cf31f6ae4c18f0de1e850cad5cb34be2122bc0d0..5c297d3357d83feb0b6c1465f67ec2b085ade7b3 100644 --- a/en/application-dev/dfx/apprecovery-guidelines.md +++ b/en/application-dev/dfx/apprecovery-guidelines.md @@ -125,12 +125,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; #### Actively Saving the Application State and Restoring Data -- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. +- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. For details about its usage, see [errorManager](../reference/apis/js-apis-app-ability-errorManager.md). ```ts var registerId = -1; var callback = { - onUnhandledException: function (errMsg) { + onUnhandledException(errMsg) { console.log(errMsg); appRecovery.saveAppState(); appRecovery.restartApp(); @@ -142,7 +142,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; console.log("[Demo] EntryAbility onWindowStageCreate") globalThis.registerObserver = (() => { - registerId = errorManager.registerErrorObserver(callback); + registerId = errorManager.on('error', callback); }) windowStage.loadContent("pages/index", null); @@ -158,7 +158,7 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, // Ability has called to save app data console.log("[Demo] EntryAbility onSaveState") wantParams["myData"] = "my1234567"; - return AbilityConstant.onSaveResult.ALL_AGREE; + return AbilityConstant.OnSaveResult.ALL_AGREE; } ``` @@ -188,8 +188,8 @@ onWindowStageDestroy() { console.log("[Demo] EntryAbility onWindowStageDestroy") globalThis.unRegisterObserver = (() => { - errorManager.unregisterErrorObserver(registerId, (result) => { - console.log("[Demo] result " + result.code + ";" + result.message) + errorManager.off('error', registerId, (err) => { + console.error("[Demo] err:", err); }); }) } @@ -217,7 +217,7 @@ export default class EntryAbility extends Ability { // Ability has called to save app data console.log("[Demo] EntryAbility onSaveState") wantParams["myData"] = "my1234567"; - return AbilityConstant.onSaveResult.ALL_AGREE; + return AbilityConstant.OnSaveResult.ALL_AGREE; } } ``` diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 640b9185ee236dbe0fb5dfe3808b14322a401a23..569b16d587af811d32e425a534ab4dc0df6a4be6 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -146,9 +146,3 @@ The following example illustrates how to log and subscribe to button click event HiAppEvent eventPkg.size=124 HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1670268234523,"tz_":"+0800","pid_":3295,"tid_":3309,"click_time":100} ``` - -## Samples - -The following sample is provided to help you better understand how to develop the application event logging feature: - -- [`JsDotTest`: Event Logging (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest) diff --git a/en/application-dev/faqs/faqs-bundle.md b/en/application-dev/faqs/faqs-bundle.md index 61a5277c6d4a1493d0281fdd66b88a99a07141ae..fda41c42bccc357d6b8800ce3f5401e1e2abbceb 100644 --- a/en/application-dev/faqs/faqs-bundle.md +++ b/en/application-dev/faqs/faqs-bundle.md @@ -14,7 +14,7 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Obtain the bundle name through **context.abilityInfo.bundleName**. -Reference: [AbilityContext](../reference/apis/js-apis-ability-context.md) and [AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) +Reference: [AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) ## How do I obtain an application icon? diff --git a/en/application-dev/faqs/faqs-language.md b/en/application-dev/faqs/faqs-language.md index 22a450b4c8e37dc85a28c2ea3b972b03d6ea16ae..6d3ded94a76155feae22d761bdb63422e07f0316 100644 --- a/en/application-dev/faqs/faqs-language.md +++ b/en/application-dev/faqs/faqs-language.md @@ -251,7 +251,6 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 To listen for in-depth changes of **@State** decorated variables, you can use **@Observed** and **@ObjectLink** decorators. -Reference: [@Observed and @ObjectLink](../quick-start/arkts-state-mgmt-page-level.md#observed-and-objectlink) ## How do I implement character string encoding and decoding? diff --git a/en/application-dev/faqs/faqs-web-arkts.md b/en/application-dev/faqs/faqs-web-arkts.md index be2d58f82d54c9b95596ad3e767954fb7acfceca..6fe2c75a4bf0bc9b1d2f73929a34dc618c503d5b 100644 --- a/en/application-dev/faqs/faqs-web-arkts.md +++ b/en/application-dev/faqs/faqs-web-arkts.md @@ -76,4 +76,4 @@ Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9 4. Use message port 0 on the application side to send messages to message port 1 on the HTML side. -Reference: [Web](../reference/arkui-ts/ts-basic-components-web.md#postmessage9) +Reference: [Web](../reference/arkui-ts/ts-basic-components-web.md) diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index f6902595cadbea27765ebf1812544821b3c68a09..f3a233ca129527db112459ab5110df49b8e1052d 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -1,29 +1,60 @@ # Media +- [Media Application Overview](media-application-overview.md) - Audio and Video - - [Audio Overview](audio-overview.md) - - [Audio Rendering Development](audio-renderer.md) - - [Audio Stream Management Development](audio-stream-manager.md) - - [Audio Capture Development](audio-capturer.md) - - [OpenSL ES Audio Playback Development](opensles-playback.md) - - [OpenSL ES Audio Recording Development](opensles-capture.md) - - [Audio Interruption Mode Development](audio-interruptmode.md) - - [Volume Management Development](audio-volume-manager.md) - - [Audio Routing and Device Management Development](audio-routing-manager.md) - - [AVPlayer Development (Recommended)](avplayer-playback.md) - - [AVRecorder Development (Recommended)](avrecorder.md) - - [Audio Playback Development (To Be Deprecated Soon)](audio-playback.md) - - [Audio Recording Development (To Be Deprecated Soon)](audio-recorder.md) - - [Video Playback Development (To Be Deprecated Soon)](video-playback.md) - - [Video Recording Development (To Be Deprecated Soon)](video-recorder.md) - -- AVSession + - [Audio and Video Overview](av-overview.md) + - [AVPlayer and AVRecorder](avplayer-avrecorder-overview.md) + - Audio Playback + - [Audio Playback Overview](audio-playback-overview.md) + - [Using AVPlayer for Audio Playback](using-avplayer-for-playback.md) + - [Using AudioRenderer for Audio Playback](using-audiorenderer-for-playback.md) + - [Using OpenSL ES for Audio Playback](using-opensl-es-for-playback.md) + - [Using TonePlayer for Audio Playback (for System Applications Only)](using-toneplayer-for-playback.md) + - [Audio Playback Concurrency Policy](audio-playback-concurrency.md) + - [Volume Management](volume-management.md) + - [Audio Playback Stream Management](audio-playback-stream-management.md) + - [Audio Output Device Management](audio-output-device-management.md) + - [Distributed Audio Playback (for System Applications Only)](distributed-audio-playback.md) + - Audio Recording + - [Audio Recording Overview](audio-recording-overview.md) + - [Using AVRecorder for Audio Recording](using-avrecorder-for-recording.md) + - [Using AudioCapturer for Audio Recording](using-audiocapturer-for-recording.md) + - [Using OpenSL ES for Audio Recording](using-opensl-es-for-recording.md) + - [Microphone Management](mic-management.md) + - [Audio Recording Stream Management](audio-recording-stream-management.md) + - [Audio Input Device Management](audio-input-device-management.md) + - Audio Call + - [Audio Call Overview](audio-call-overview.md) + - [Developing Audio Call](audio-call-development.md) + - [Video Playback](video-playback.md) + - [Video Recording](video-recording.md) +- AVSession (for System Applications Only) - [AVSession Overview](avsession-overview.md) - - [AVSession Development](avsession-guidelines.md) - + - Local AVSession + - [Local AVSession Overview](local-avsession-overview.md) + - [AVSession Provider](using-avsession-developer.md) + - [AVSession Controller](using-avsession-controller.md) + - Distributed AVSession + - [Distributed AVSession Overview](distributed-avsession-overview.md) + - [Using Distributed AVSession](using-distributed-avsession.md) +- Camera (for System Applications Only) + - [Camera Overview](camera-overview.md) + - Camera Development + - [Camera Development Preparations](camera-preparation.md) + - [Device Input Management](camera-device-input.md) + - [Session Management](camera-session-management.md) + - [Camera Preview](camera-preview.md) + - [Camera Photographing](camera-shooting.md) + - [Video Recording](camera-recording.md) + - [Camera Metadata](camera-metadata.md) + - Best Practices + - [Camera Photographing Sample](camera-shooting-case.md) + - [Video Recording Sample](camera-recording-case.md) - Image - - [Image Development](image.md) - -- Camera - - [Camera Development](camera.md) - - [Distributed Camera Development](remote-camera.md) + - [Image Overview](image-overview.md) + - [Image Decoding](image-decoding.md) + - Image Processing + - [Image Transformation](image-transformation.md) + - [Pixel Map Operation](image-pixelmap-operation.md) + - [Image Encoding](image-encoding.md) + - [Image Tool](image-tool.md) diff --git a/en/application-dev/media/audio-call-development.md b/en/application-dev/media/audio-call-development.md new file mode 100644 index 0000000000000000000000000000000000000000..8234c837c2ce985c2a1a7dc91c7e0002fb3d4a69 --- /dev/null +++ b/en/application-dev/media/audio-call-development.md @@ -0,0 +1,259 @@ +# Developing Audio Call + +During an audio call, audio output (playing the peer voice) and audio input (recording the local voice) are carried out simultaneously. You can use the AudioRenderer to implement audio output and the AudioCapturer to implement audio input. + +Before starting or stopping using the audio call service, the application needs to check the [audio scene](audio-call-overview.md#audio-scene) and [ringer mode](audio-call-overview.md#ringer-mode) to adopt proper audio management and prompt policies. + +The sample code below demonstrates the basic process of using the AudioRenderer and AudioCapturer to implement the audio call service, without the process of call data transmission. In actual development, the peer call data transmitted over the network needs to be decoded and played, and the sample code uses the process of reading an audio file instead; the local call data needs to be encoded and packed and then sent to the peer over the network, and the sample code uses the process of writing an audio file instead. + +## Using AudioRenderer to Play the Peer Voice + +This process is similar to the process of [using AudioRenderer to develop audio playback](using-audiorenderer-for-playback.md). The key differences lie in the **audioRendererInfo** parameter and audio data source. In the **audioRendererInfo** parameter used for audio calling, **content** must be set to **CONTENT_TYPE_SPEECH**, and **usage** must be set to **STREAM_USAGE_VOICE_COMMUNICATION**. + +```ts +import audio from '@ohos.multimedia.audio'; +import fs from '@ohos.file.fs'; +const TAG = 'VoiceCallDemoForAudioRenderer'; +// The process is similar to the process of using AudioRenderer to develop audio playback. The key differences lie in the audioRendererInfo parameter and audio data source. +export default class VoiceCallDemoForAudioRenderer { + private renderModel = undefined; + private audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. + channels: audio.AudioChannel.CHANNEL_2, // Channel. + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. + } + private audioRendererInfo = { + // Parameters corresponding to the call scenario need to be used. + content: audio.ContentType.CONTENT_TYPE_SPEECH, // Audio content type: speech. + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, // Audio stream usage type: voice communication. + rendererFlags: 0 // AudioRenderer flag. The default value is 0. + } + private audioRendererOptions = { + streamInfo: this.audioStreamInfo, + rendererInfo: this.audioRendererInfo + } + // Create an AudioRenderer instance, and set the events to listen for. + init() { + audio.createAudioRenderer(this.audioRendererOptions, (err, renderer) => { // Create an AudioRenderer instance. + if (!err) { + console.info(`${TAG}: creating AudioRenderer success`); + this.renderModel = renderer; + this.renderModel.on('stateChange', (state) => { // Set the events to listen for. A callback is invoked when the AudioRenderer is switched to the specified state. + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); + } + }); + this.renderModel.on('markReach', 1000, (position) => { // Subscribe to the markReach event. A callback is triggered when the number of rendered frames reaches 1000. + if (position == 1000) { + console.info('ON Triggered successfully'); + } + }); + } else { + console.info(`${TAG}: creating AudioRenderer failed, error: ${err.message}`); + } + }); + } + // Start audio rendering. + async start() { + let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; + if (stateGroup.indexOf(this.renderModel.state) === -1) { // Rendering can be started only when the AudioRenderer is in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state. + console.error(TAG + 'start failed'); + return; + } + await this.renderModel.start(); // Start rendering. + const bufferSize = await this.renderModel.getBufferSize(); + // The process of reading audio file data is used as an example. In actual audio call development, audio data transmitted from the peer needs to be read. + let context = getContext(this); + let path = context.filesDir; + + const filePath = path + '/voice_call_data.wav'; // Sandbox path. The actual path is /data/storage/el2/base/haps/entry/files/voice_call_data.wav. + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + let stat = await fs.stat(filePath); + let buf = new ArrayBuffer(bufferSize); + let len = stat.size % bufferSize === 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); + for (let i = 0; i < len; i++) { + let options = { + offset: i * bufferSize, + length: bufferSize + }; + let readsize = await fs.read(file.fd, buf, options); + // buf indicates the audio data to be written to the buffer. Before calling AudioRenderer.write(), you can preprocess the audio data for personalized playback. The AudioRenderer reads the audio data written to the buffer for rendering. + let writeSize = await new Promise((resolve, reject) => { + this.renderModel.write(buf, (err, writeSize) => { + if (err) { + reject(err); + } else { + resolve(writeSize); + } + }); + }); + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { // The rendering stops if the AudioRenderer is in the STATE_RELEASED state. + fs.close(file); + await this.renderModel.stop(); + } + if (this.renderModel.state === audio.AudioState.STATE_RUNNING) { + if (i === len - 1) { // The rendering stops if the file finishes reading. + fs.close(file); + await this.renderModel.stop(); + } + } + } + } + // Pause the rendering. + async pause() { + // Rendering can be paused only when the AudioRenderer is in the STATE_RUNNING state. + if (this.renderModel.state !== audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + await this.renderModel.pause(); // Pause rendering. + if (this.renderModel.state === audio.AudioState.STATE_PAUSED) { + console.info('Renderer is paused.'); + } else { + console.error('Pausing renderer failed.'); + } + } + // Stop rendering. + async stop() { + // Rendering can be stopped only when the AudioRenderer is in the STATE_RUNNING or STATE_PAUSED state. + if (this.renderModel.state !== audio.AudioState.STATE_RUNNING && this.renderModel.state !== audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused.'); + return; + } + await this.renderModel.stop(); // Stop rendering. + if (this.renderModel.state === audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped.'); + } else { + console.error('Stopping renderer failed.'); + } + } + // Release the instance. + async release() { + // The AudioRenderer can be released only when it is not in the STATE_RELEASED state. + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { + console.info('Renderer already released'); + return; + } + await this.renderModel.release(); // Release the instance. + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.error('Renderer release failed.'); + } + } +} +``` + +## Using AudioCapturer to Record the Local Voice + +This process is similar to the process of [using AudioCapturer to develop audio recording](using-audiocapturer-for-recording.md). The key differences lie in the **audioCapturerInfo** parameter and audio data stream direction. In the **audioCapturerInfo** parameter used for audio calling, **source** must be set to **SOURCE_TYPE_VOICE_COMMUNICATION**. + +```ts +import audio from '@ohos.multimedia.audio'; +import fs from '@ohos.file.fs'; +const TAG = 'VoiceCallDemoForAudioCapturer'; +// The process is similar to the process of using AudioCapturer to develop audio recording. The key differences lie in the audioCapturerInfo parameter and audio data stream direction. +export default class VoiceCallDemoForAudioCapturer { + private audioCapturer = undefined; + private audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, // Sampling rate. + channels: audio.AudioChannel.CHANNEL_1, // Channel. + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. + } + private audioCapturerInfo = { + // Parameters corresponding to the call scenario need to be used. + source: audio.SourceType.SOURCE_TYPE_VOICE_COMMUNICATION, // Audio source type: voice communication. + capturerFlags: 0 // AudioCapturer flag. The default value is 0. + } + private audioCapturerOptions = { + streamInfo: this.audioStreamInfo, + capturerInfo: this.audioCapturerInfo + } + // Create an AudioCapturer instance, and set the events to listen for. + init() { + audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // Create an AudioCapturer instance. + if (err) { + console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info(`${TAG}: create AudioCapturer success`); + this.audioCapturer = capturer; + this.audioCapturer.on('markReach', 1000, (position) => { // Subscribe to the markReach event. A callback is triggered when the number of captured frames reaches 1000. + if (position === 1000) { + console.info('ON Triggered successfully'); + } + }); + this.audioCapturer.on('periodReach', 2000, (position) => { // Subscribe to the periodReach event. A callback is triggered when the number of captured frames reaches 2000. + if (position === 2000) { + console.info('ON Triggered successfully'); + } + }); + }); + } + // Start audio recording. + async start() { + let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; + if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // Recording can be started only when the AudioRenderer is in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state. + console.error(`${TAG}: start failed`); + return; + } + await this.audioCapturer.start(); // Start recording. + // The following describes how to write audio data to a file. In actual audio call development, the local audio data needs to be encoded and packed, and then sent to the peer through the network. + let context = getContext(this); + const path = context.filesDir + '/voice_call_data.wav'; // Path for storing the recorded audio file. + let file = fs.openSync(path, 0o2 | 0o100); // Create the file if it does not exist. + let fd = file.fd; + let numBuffersToCapture = 150; // Write data for 150 times. + let count = 0; + while (numBuffersToCapture) { + let bufferSize = await this.audioCapturer.getBufferSize(); + let buffer = await this.audioCapturer.read(bufferSize, true); + let options = { + offset: count * bufferSize, + length: bufferSize + }; + if (buffer === undefined) { + console.error(`${TAG}: read buffer failed`); + } else { + let number = fs.writeSync(fd, buffer, options); + console.info(`${TAG}: write date: ${number}`); + } + numBuffersToCapture--; + count++; + } + } + // Stop recording. + async stop() { + // The AudioCapturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. + if (this.audioCapturer.state !== audio.AudioState.STATE_RUNNING && this.audioCapturer.state !== audio.AudioState.STATE_PAUSED) { + console.info('Capturer is not running or paused'); + return; + } + await this.audioCapturer.stop(); // Stop recording. + if (this.audioCapturer.state === audio.AudioState.STATE_STOPPED) { + console.info('Capturer stopped'); + } else { + console.error('Capturer stop failed'); + } + } + // Release the instance. + async release() { + // The AudioCapturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. + if (this.audioCapturer.state === audio.AudioState.STATE_RELEASED || this.audioCapturer.state === audio.AudioState.STATE_NEW) { + console.info('Capturer already released'); + return; + } + await this.audioCapturer.release(); // Release the instance. + if (this.audioCapturer.state == audio.AudioState.STATE_RELEASED) { + console.info('Capturer released'); + } else { + console.error('Capturer release failed'); + } + } +} +``` diff --git a/en/application-dev/media/audio-call-overview.md b/en/application-dev/media/audio-call-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..1462198c201203da3eecc902de556c005ad3aae9 --- /dev/null +++ b/en/application-dev/media/audio-call-overview.md @@ -0,0 +1,49 @@ +# Audio Call Development + +Typically, audio calls are classified into VoIP calls and cellular calls. + +- Voice over Internet Protocol (VoIP) is a technology that enables you to make voice calls using a broadband Internet connection. During a VoIP call, call information is packed into data packets and transmitted over the network. Therefore, the VoIP call has high requirements on the network quality, and the call quality is closely related to the network connection speed. + +- Cellular call refers to the traditional telephony service provided by carriers. Currently, APIs for developing cellular calling are available only for system applications. + +When developing the audio call service, you must use a proper audio processing policy based on the [audio scene](#audio-scene) and [ringer mode](#ringer-mode). + +## Audio Scene + +When an application uses the audio call service, the system switches to the call-related audio scene (specified by [AudioScene](../reference/apis/js-apis-audio.md#audioscene8)). The system has preset multiple audio scenes, including ringing, cellular call, and voice chat, and uses a scene-specific policy to process audio. + +For example, in the cellular call audio scene, the system prioritizes voice clarity. To deliver a crystal clear voice during calls, the system uses the 3A algorithm to preprocess audio data, suppress echoes, eliminates background noise, and adjusts the volume range. The 3A algorithm refers to three audio processing algorithms: Acoustic Echo Cancellation (AEC), Active Noise Control (ANC), and Automatic Gain Control (AGC). + +Currently, the following audio scenes are preset: + +- **AUDIO_SCENE_DEFAULT**: default audio scene, which can be used in all scenarios except audio calls. + +- **AUDIO_SCENE_RINGING**: ringing audio scene, which is used when a call is coming and is open only to system applications. + +- **AUDIO_SCENE_PHONE_CALL**: cellular call audio scene, which is used for cellular calls and is open only to system applications. + +- **AUDIO_SCENE_VOICE_CHAT**: voice chat scene, which is used for VoIP calls. + +The application can call **getAudioScene** in the [AudioManager](../reference/apis/js-apis-audio.md#audiomanager) class to obtain the audio scene in use. Before starting or stopping using the audio call service, the application can call this API to check whether the system has switched to the suitable audio scene. + +## Ringer Mode + +When an audio call is coming, the application notifies the user by playing a ringtone or vibrating, depending on the setting of [AudioRingMode](../reference/apis/js-apis-audio.md#audioringmode). + +The system has preset the following ringer modes: + +- **RINGER_MODE_SILENT**: silent mode, in which no sound is played when a call is coming in. + +- **RINGER_MODE_VIBRATE**: vibration mode, in which no sound is played but the device vibrates when a call is coming in. + +- **RINGER_MODE_NORMAL**: normal mode, in which a ringtone is played when a call is coming in. + +The application can call **getRingerMode** in the [AudioVolumeGroupManager](../reference/apis/js-apis-audio.md#audiovolumegroupmanager9) class to obtain the ringer mode in use so as to use a proper policy to notify the user. + +If the application wants to obtain the ringer mode changes in time, it can call **on('ringerModeChange')** in the **AudioVolumeGroupManager** class to listen for the changes. When the ringer mode changes, it will receive a notification and can make adjustment accordingly. + +## Audio Device Switching During a Call + +When a call is coming, the system selects an appropriate audio device based on the default priority. The application can switch the call to another audio device as required. + +The audio devices that can be used for the audio call are specified by [CommunicationDeviceType](../reference/apis/js-apis-audio.md#communicationdevicetype9). The application can call **isCommunicationDeviceActive** in the [AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9) class to check whether a communication device is active. It can also call **setCommunicationDevice** in the **AudioRoutingManager** class to set a communication device to the active state so that the device can be used for the call. diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md deleted file mode 100644 index f7b01ce2a387af3471b297de329fe3267b9e9785..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-capturer.md +++ /dev/null @@ -1,258 +0,0 @@ -# Audio Capture Development - -## Introduction - -You can use the APIs provided by **AudioCapturer** to record raw audio files, thereby implementing audio data collection. - -**Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. - -## Working Principles - -This following figure shows the audio capturer state transitions. - -**Figure 1** Audio capturer state transitions - -![audio-capturer-state](figures/audio-capturer-state.png) - -- **PREPARED**: The audio capturer enters this state by calling **create()**. -- **RUNNING**: The audio capturer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. -- **STOPPED**: The audio capturer in the **RUNNING** state can call **stop()** to stop playing audio data. -- **RELEASED**: The audio capturer in the **PREPARED** or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state. - -## Constraints - -Before developing the audio data collection feature, configure the **ohos.permission.MICROPHONE** permission for your application. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - -## How to Develop - -For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8). - -1. Use **createAudioCapturer()** to create a global **AudioCapturer** instance. - - Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, and register a callback for notification. - - ```js - import audio from '@ohos.multimedia.audio'; - import fs from '@ohos.file.fs'; // It will be used for the call of the read function in step 3. - - // Perform a self-test on APIs related to audio rendering. - @Entry - @Component - struct AudioRenderer { - @State message: string = 'Hello World' - private audioCapturer: audio.AudioCapturer; // It will be called globally. - - async initAudioCapturer(){ - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - let audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0. - } - - let audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - this.audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - console.log('AudioRecLog: Create audio capturer success.'); - } - - ``` - -2. Use **start()** to start audio recording. - - The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. - - ```js - async startCapturer() { - let state = this.audioCapturer.state; - // The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. - if (state == audio.AudioState.STATE_PREPARED || state == audio.AudioState.STATE_PAUSED || - state == audio.AudioState.STATE_STOPPED) { - await this.audioCapturer.start(); - state = this.audioCapturer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.error('AudioRecLog: Capturer start failed'); - } - } - } - ``` - -3. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application stops the recording. - - The following example shows how to write recorded data into a file. - - ```js - async readData(){ - let state = this.audioCapturer.state; - // The read operation can be performed only when the state is STATE_RUNNING. - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Capturer is not in a correct state to read'); - return; - } - const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file. - let file = fs.openSync(path, 0o2); - let fd = file.fd; - if (file !== null) { - console.info('AudioRecLog: file created'); - } else { - console.info('AudioRecLog: file create : FAILED'); - return; - } - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - let numBuffersToCapture = 150; // Write data for 150 times. - let count = 0; - while (numBuffersToCapture) { - this.bufferSize = await this.audioCapturer.getBufferSize(); - let buffer = await this.audioCapturer.read(this.bufferSize, true); - let options = { - offset: count * this.bufferSize, - length: this.bufferSize - } - if (typeof(buffer) == undefined) { - console.info('AudioRecLog: read buffer failed'); - } else { - let number = fs.writeSync(fd, buffer, options); - console.info(`AudioRecLog: data written: ${number}`); - } - numBuffersToCapture--; - count++; - } - } - ``` - -4. Once the recording is complete, call **stop()** to stop the recording. - - ```js - async StopCapturer() { - let state = this.audioCapturer.state; - // The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. - if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { - console.info('AudioRecLog: Capturer is not running or paused'); - return; - } - - await this.audioCapturer.stop(); - - state = this.audioCapturer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.error('AudioRecLog: Capturer stop failed'); - } - } - ``` - -5. After the task is complete, call **release()** to release related resources. - - ```js - async releaseCapturer() { - let state = this.audioCapturer.state; - // The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. - if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { - console.info('AudioRecLog: Capturer already released'); - return; - } - - await this.audioCapturer.release(); - - state = this.audioCapturer.state; - if (state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } - } - ``` - -6. (Optional) Obtain the audio capturer information. - - You can use the following code to obtain the audio capturer information: - - ```js - async getAudioCapturerInfo(){ - // Obtain the audio capturer state. - let state = this.audioCapturer.state; - // Obtain the audio capturer information. - let audioCapturerInfo : audio.AudioCapturerInfo = await this.audioCapturer.getCapturerInfo(); - // Obtain the audio stream information. - let audioStreamInfo : audio.AudioStreamInfo = await this.audioCapturer.getStreamInfo(); - // Obtain the audio stream ID. - let audioStreamId : number = await this.audioCapturer.getAudioStreamId(); - // Obtain the Unix timestamp, in nanoseconds. - let audioTime : number = await this.audioCapturer.getAudioTime(); - // Obtain a proper minimum buffer size. - let bufferSize : number = await this.audioCapturer.getBufferSize(); - } - ``` - -7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. - - After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. - - ```js - async markReach(){ - this.audioCapturer.on('markReach', 10, (reachNumber) => { - console.info('Mark reach event Received'); - console.info(`The Capturer reached frame: ${reachNumber}`); - }); - this.audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. - } - ``` - -8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. - - After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. - - ```js - async periodReach(){ - this.audioCapturer.on('periodReach', 10, (reachNumber) => { - console.info('Period reach event Received'); - console.info(`In this period, the Capturer reached frame: ${reachNumber}`); - }); - this.audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. - } - ``` - -9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type. - - ```js - async stateChange(){ - this.audioCapturer.on('stateChange', (state) => { - console.info(`AudioCapturerLog: Changed State to : ${state}`) - switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } - }); - } - ``` diff --git a/en/application-dev/media/audio-input-device-management.md b/en/application-dev/media/audio-input-device-management.md new file mode 100644 index 0000000000000000000000000000000000000000..ebdadfaad7a9316cf055d3216ac3a94a1b052a33 --- /dev/null +++ b/en/application-dev/media/audio-input-device-management.md @@ -0,0 +1,88 @@ +# Audio Input Device Management + +If a device is connected to multiple audio input devices, you can use **AudioRoutingManager** to specify an audio input device to record audio. For details about the API reference, see [AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9). + +## Creating an AudioRoutingManager Instance + +Before using **AudioRoutingManager** to manage audio devices, import the audio module and create an **AudioManager** instance. + +```ts +import audio from '@ohos.multimedia.audio'; // Import the audio module. + +let audioManager = audio.getAudioManager(); // Create an AudioManager instance. + +let audioRoutingManager = audioManager.getRoutingManager(); // Call an API of AudioManager to create an AudioRoutingManager instance. +``` + +## Supported Audio Input Device Types + +The table below lists the supported audio input devices. + +| Name| Value| Description| +| -------- | -------- | -------- | +| WIRED_HEADSET | 3 | Wired headset with a microphone.| +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links.| +| MIC | 15 | Microphone.| +| USB_HEADSET | 22 | USB Type-C headset.| + +## Obtaining Input Device Information + +Use **getDevices()** to obtain information about all the input devices. + +```ts +audioRoutingManager.getDevices(audio.DeviceFlag.INPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); +}); +``` + +## Listening for Device Connection State Changes + +Set a listener to listen for changes of the device connection state. When a device is connected or disconnected, a callback is triggered. + +```ts +// Listen for connection state changes of audio devices. +audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type: ' + deviceChanged.type); // Device connection state change. The value 0 means that the device is connected and 1 means that the device is disconnected. + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceRole); // Device role. + console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceType); // Device type. +}); + +// Cancel the listener for the connection state changes of audio devices. +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); +}); +``` + +## Selecting an Audio Input Device (for System Applications only) + +Currently, only one input device can be selected, and the device ID is used as the unique identifier. For details about audio device descriptors, see [AudioDeviceDescriptors](../reference/apis/js-apis-audio.md#audiodevicedescriptors). + +> **NOTE** +> +> The user can connect to a group of audio devices (for example, a pair of Bluetooth headsets), but the system treats them as one device (a group of devices that share the same device ID). + +```ts +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; + +async function getRoutingManager(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Invoke selectInputDevice succeeded.'); + }).catch((err) => { + console.error(`Invoke selectInputDevice failed, code is ${err.code}, message is ${err.message}`); + }); +} + +``` diff --git a/en/application-dev/media/audio-interruptmode.md b/en/application-dev/media/audio-interruptmode.md deleted file mode 100644 index 48a53bf5d5990ac88aae1271466a6aa36d52ac98..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-interruptmode.md +++ /dev/null @@ -1,55 +0,0 @@ -# Audio Interruption Mode Development - -## Introduction -The audio interruption mode is used to control the playback of multiple audio streams. - -Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**. - -In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID. - -**Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. - -## How to Develop - -For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). - -1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. - - Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. - - This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. - -```js - import audio from '@ohos.multimedia.audio'; - - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 - } - - var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - -let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); - ``` - -2. Set the audio interruption mode. - - After the **AudioRenderer** instance is initialized, you can set the audio interruption mode.
- - ```js - var mode_ = audio.InterruptMode.SHARE_MODE; - await this.audioRenderer.setInterruptMode(mode_).then(() => { - console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success"); - }); - ``` diff --git a/en/application-dev/media/audio-output-device-management.md b/en/application-dev/media/audio-output-device-management.md new file mode 100644 index 0000000000000000000000000000000000000000..ad20276c60ce7e535f99778e18d04e4e50e29dc6 --- /dev/null +++ b/en/application-dev/media/audio-output-device-management.md @@ -0,0 +1,90 @@ +# Audio Output Device Management + +If a device is connected to multiple audio output devices, you can use **AudioRoutingManager** to specify an audio output device to play audio. For details about the API reference, see [AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9). + +## Creating an AudioRoutingManager Instance + +Before using **AudioRoutingManager** to manage audio devices, import the audio module and create an **AudioManager** instance. + +```ts +import audio from '@ohos.multimedia.audio'; // Import the audio module. + +let audioManager = audio.getAudioManager(); // Create an AudioManager instance. + +let audioRoutingManager = audioManager.getRoutingManager(); // Call an API of AudioManager to create an AudioRoutingManager instance. +``` + +## Supported Audio Output Device Types + +The table below lists the supported audio output devices. + +| Name| Value| Description| +| -------- | -------- | -------- | +| EARPIECE | 1 | Earpiece.| +| SPEAKER | 2 | Speaker.| +| WIRED_HEADSET | 3 | Wired headset with a microphone.| +| WIRED_HEADPHONES | 4 | Wired headset without microphone.| +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links.| +| BLUETOOTH_A2DP | 8 | Bluetooth device using Advanced Audio Distribution Profile (A2DP) links.| +| USB_HEADSET | 22 | USB Type-C headset.| + +## Obtaining Output Device Information + +Use **getDevices()** to obtain information about all the output devices. + +```ts +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); +}); +``` + +## Listening for Device Connection State Changes + +Set a listener to listen for changes of the device connection state. When a device is connected or disconnected, a callback is triggered. + +```ts +// Listen for connection state changes of audio devices. +audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type: ' + deviceChanged.type); // Device connection state change. The value 0 means that the device is connected and 1 means that the device is disconnected. + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceRole); // Device role. + console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceType); // Device type. +}); + +// Cancel the listener for the connection state changes of audio devices. +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); +}); +``` + +## Selecting an Audio Output Device (for System Applications only) + +Currently, only one output device can be selected, and the device ID is used as the unique identifier. For details about audio device descriptors, see [AudioDeviceDescriptors](../reference/apis/js-apis-audio.md#audiodevicedescriptors). + +> **NOTE** +> +> The user can connect to a group of audio devices (for example, a pair of Bluetooth headsets), but the system treats them as one device (a group of devices that share the same device ID). + +```ts +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; + +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Invoke selectOutputDevice succeeded.'); + }).catch((err) => { + console.error(`Invoke selectOutputDevice failed, code is ${err.code}, message is ${err.message}`); + }); +} +``` diff --git a/en/application-dev/media/audio-overview.md b/en/application-dev/media/audio-overview.md deleted file mode 100755 index e1fd93eab8238b8ae55c9ce3dff2e807a1585a00..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-overview.md +++ /dev/null @@ -1,20 +0,0 @@ -# Audio Overview - -You can use APIs provided by the audio module to implement audio-related features, including audio playback and volume management. - -## Basic Concepts - -- **Sampling** - Sampling is a process to obtain discrete-time signals by extracting samples from analog signals in a continuous time domain at a specific interval. - -- **Sampling rate** - Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz. - -- **Channel** - Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback. - -- **Audio frame** - Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements. - -- **PCM**
- Pulse code modulation (PCM) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples. diff --git a/en/application-dev/media/audio-playback-concurrency.md b/en/application-dev/media/audio-playback-concurrency.md new file mode 100644 index 0000000000000000000000000000000000000000..0b36594f6bef62c7ba7588bc8977af67609a6c9d --- /dev/null +++ b/en/application-dev/media/audio-playback-concurrency.md @@ -0,0 +1,119 @@ +# Audio Playback Concurrency Policy + +## Audio Interruption Policy + +If multiple audio streams are played at the same time, the user may feel uncomfortable or even painful. To address this issue, OpenHarmony presets the audio interruption policy so that only the audio stream holding audio focus can be played. + +When an application attempts to play an audio, the system requests audio focus for the audio stream. The audio stream that gains the focus can be played. If the request is rejected, the audio stream cannot be played. If the audio stream is interrupted by another, it loses the focus and therefore the playback is paused. All these actions are automatically performed by the system and do not require additional operations on the application. However, to maintain state consistency between the application and the system and ensure good user experience, it is recommended that the application [listen for the audio interruption event](#listening-for-the-audio-interruption-event) and perform the corresponding processing when receiving such an event (specified by [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9)). + +OpenHarmony presets two [audio interruption modes](#audio-interruption-mode) to specify whether audio concurrency is controlled by the application or system. You can choose a mode for each of the audio streams created by the same application. + +The audio interruption policy determines the operations (for example, pause, resume, duck, or unduck) to be performed on the audio stream. These operations can be performed by the system or application. To distinguish the body that executes the operations, the [audio interruption type](#audio-interruption-type) is introduced, and two audio interruption types are preset. + +### Audio Interruption Mode + +Two audio interruption modes, specified by [InterruptMode](../reference/apis/js-apis-audio.md#interruptmode9), are preset in the audio interruption policy: + +- **SHARED_MODE**: Multiple audio streams created by an application share one audio focus. The concurrency rules between these audio streams are determined by the application, without the use of the audio interruption policy. However, if another application needs to play audio while one of these audio streams is being played, the audio interruption policy is triggered. + +- **INDEPENDENT_MODE**: Each audio stream created by an application has an independent audio focus. When multiple audio streams are played concurrently, the audio interruption policy is triggered. + +The application can select an audio interruption mode as required. By default, the **SHARED_MODE** is used. + +You can set the audio interruption mode in either of the following ways: + +- If you [use the AVPlayer to develop audio playback](using-avplayer-for-playback.md), set the [audioInterruptMode](../reference/apis/js-apis-media.md#avplayer9) attribute of the AVPlayer to set the audio interruption mode. + +- If you [use the AudioRenderer to develop audio playback](using-audiorenderer-for-playback.md), call [setInterruptMode](../reference/apis/js-apis-audio.md#setinterruptmode9) of the AudioRenderer to set the audio interruption mode. + + +### Audio Interruption Type + +The audio interruption policy (containing two audio interruption modes) determines the operation to be performed on each audio stream. These operations can be carried out by the system or application. To distinguish the executors, the audio interruption type, specified by [InterruptForceType](../reference/apis/js-apis-audio.md#interruptforcetype9), is introduced. + +- **INTERRUPT_FORCE**: The operation is performed by the system. The system forcibly interrupts audio playback. + +- **INTERRUPT_SHARE**: The operation is performed by the application. The application can take action or ignore as required. + +For the pause operation, the **INTERRUPT_FORCE** type is always used and cannot be changed by the application. However, the application can choose to use **INTERRUPT_SHARE** for other operations, such as the resume operation. The application can obtain the audio interruption type based on the value of the member variable **forceType** in the audio interruption event. + +During audio playback, the system automatically requests, holds, and releases the focus for the audio stream. When audio interruption occurs, the system forcibly pauses or stops playing or ducks the volume down for the audio stream, and sends an audio interruption event callback to the application. To maintain state consistency between the application and the system and ensure good user experience, it is recommended that the application [listen for the audio interruption event](#listening-for-the-audio-interruption-event) and perform processing when receiving such an event. + +For operations that cannot be forcibly performed by the system (for example, resume), the system sends the audio interruption event containing **INTERRUPT_SHARE**, and the application can choose to take action or ignore. + +## Listening for the Audio Interruption Event + +Your application are advised to listen for the audio interruption event when playing audio. When audio interruption occurs, the system performs processing on the audio stream according to the preset policy, and sends the audio interruption event to the application. + +Upon the receipt of the event, the application carries out processing based on the event content to ensure that the application state is consistent with the expected effect. + +You can use either of the following methods to listen for the audio interruption event: + +- If you [use the AVPlayer to develop audio playback](using-avplayer-for-playback.md), call [on('audioInterrupt')](../reference/apis/js-apis-media.md#onaudiointerrupt9) of the AVPlayer to listen for the event. + +- If you [use the AudioRenderer to develop audio playback](using-audiorenderer-for-playback.md), call [on('audioInterrupt')](../reference/apis/js-apis-audio.md#onaudiointerrupt9) of the AudioRenderer to listen for the event. + + To deliver an optimal user experience, the application needs to perform processing based on the event content. The following uses the AudioRenderer as an example to describe the recommended application processing. (The recommended processing is similar if the AVPlayer is used to develop audio playback.) You can customize the code to implement your own audio playback functionality or application processing based on service requirements. + +```ts +let isPlay; // An identifier specifying whether the audio stream is being played. In actual development, this parameter corresponds to the module related to the audio playback state. +let isDucked; // An identifier specifying whether to duck the volume down. In actual development, this parameter corresponds to the module related to the audio volume. +let started; // An identifier specifying whether the start operation is successful. + +async function onAudioInterrupt(){ + // The AudioRenderer is used as an example to describe how to develop audio playback. The audioRenderer variable is the AudioRenderer instance created for playback. + audioRenderer.on('audioInterrupt', async(interruptEvent) => { + // When an audio interruption event occurs, the audioRenderer receives the interruptEvent callback and performs processing based on the content in the callback. + // The audioRenderer reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation. + // The audioRenderer then reads the value of interruptEvent.hintType and performs corresponding processing. + if (interruptEvent.forceType === audio.InterruptForceType.INTERRUPT_FORCE) { + // If the value of interruptEvent.forceType is INTERRUPT_FORCE, the system has performed audio-related processing, and the application needs to update its state and make adjustments accordingly. + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + // The system has paused the audio stream (the focus is temporarily lost). To ensure state consistency, the application needs to switch to the audio paused state. + // Temporarily losing the focus: After the other audio stream releases the focus, the current audio stream will receive the audio interruption event corresponding to resume and automatically resume the playback. + isPlay = false; // A simplified processing indicating several operations for switching the application to the audio paused state. + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + // The system has stopped the audio stream (the focus is permanently lost). To ensure state consistency, the application needs to switch to the audio paused state. + // Permanently losing the focus: No audio interruption event will be received. The user must manually trigger the operation to resume playback. + isPlay = false; // A simplified processing indicating several operations for switching the application to the audio paused state. + break; + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + // The system has ducked the volume down (20% of the normal volume by default). To ensure state consistency, the application needs to switch to the volume decreased state. + // If the application does not want to play at a lower volume, it can select another processing mode, for example, proactively pausing the playback. + isDucked = true; // A simplified processing indicating several operations for switching the application to the volume decreased state. + break; + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + // The system has restored the audio volume to normal. To ensure state consistency, the application needs to switch to the normal volume state. + isDucked = false; // A simplified processing indicating several operations for switching the application to the normal volume state. + break; + default: + break; + } + } else if (interruptEvent.forceType === audio.InterruptForceType.INTERRUPT_SHARE) { + // If the value of interruptEvent.forceType is INTERRUPT_SHARE, the application can take action or ignore as required. + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + // The paused audio stream can be played. It is recommended that the application continue to play the audio stream and switch to the audio playing state. + // If the application does not want to continue the playback, it can ignore the event. + // To continue the playback, the application needs to call start(), and use the identifier variable started to record the execution result of start(). + await audioRenderer.start().then(async function () { + started = true; // Calling start() is successful. + }).catch((err) => { + started = false; // Calling start() fails. + }); + // If calling start() is successful, the application needs to switch to the audio playing state. + if (started) { + isPlay = true; // A simplified processing indicating several operations for switching the application to the audio playing state. + } else { + // Resuming the audio playback fails. + } + break; + default: + break; + } + } + }); +} +``` diff --git a/en/application-dev/media/audio-playback-overview.md b/en/application-dev/media/audio-playback-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d17970d6de9b8b238db74d971ad5f58c605462eb --- /dev/null +++ b/en/application-dev/media/audio-playback-overview.md @@ -0,0 +1,25 @@ +# Audio Playback Development + +## Selecting an Audio Playback Development Mode + +OpenHarmony provides multiple classes for you to develop audio playback applications. You can select them based on the audio data formats, audio sources, audio usage scenarios, and even the programming language you use. Selecting a suitable class helps you reduce development workload and your application deliver a better effect. + +- [AVPlayer](using-avplayer-for-playback.md): provides ArkTS and JS APIs to implement audio and video playback. It also supports parsing streaming media and local assets, decapsulating media assets, decoding audio, and outputting audio. It can play audio files in MP3 and M4A formats, but not in PCM format. + +- [AudioRenderer](using-audiorenderer-for-playback.md): provides ArkTS and JS API to implement audio output. It supports only the PCM format and requires applications to continuously write audio data. The applications can perform data preprocessing, for example, setting the sampling rate and bit width of audio files, before audio input. This class can be used to develop more professional and diverse playback applications. To use this class, you must have basic audio processing knowledge. + +- [OpenSLES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. + +- [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS API to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is application to specific scenarios where dialing tones and ringback tones are played. is available only to system applications. + +- Applications often need to use short sound effects, such as camera shutter sound effect, key press sound effect, and game shooting sound effect. Currently, only the **AVPlayer** class can implement audio file playback. More APIs will be provided to support this scenario in later versions. + +## Precautions for Developing Audio Playback Applications + +To enable your application to play a video in the background or when the screen is off, the application must meet the following conditions: + +1. The application is registered with the system for unified management through the **AVSession** APIs. Otherwise, the playback will be forcibly stopped when the application switches to the background. For details, see [AVSession Development](avsession-overview.md). + +2. The application must request a continuous task to prevent from being suspended. For details, see [Continuous Task Development](../task-management/continuous-task-dev-guide.md). + +If the playback is interrupted when the application switches to the background, you can view the log to see whether the application has requested a continuous task. If the application has requested a continuous task, there is no log recording **pause id**; otherwise, there is a log recording **pause id**. diff --git a/en/application-dev/media/audio-playback-stream-management.md b/en/application-dev/media/audio-playback-stream-management.md new file mode 100644 index 0000000000000000000000000000000000000000..c6cf398b8403b3f799a1db20716021c91ca6e078 --- /dev/null +++ b/en/application-dev/media/audio-playback-stream-management.md @@ -0,0 +1,120 @@ +# Audio Playback Stream Management + +An audio playback application must notice audio stream state changes and perform corresponding operations. For example, when detecting that an audio stream is being played or paused, the application must change the UI display of the **Play** button. + +## Reading or Listening for Audio Stream State Changes in the Application + +Create an AudioRenderer by referring to [Using AudioRenderer for Audio Playback](using-audiorenderer-for-playback.md) or [audio.createAudioRenderer](../reference/apis/js-apis-audio.md#audiocreateaudiorenderer8). Then obtain the audio stream state changes in either of the following ways: + +- Check the [state](../reference/apis/js-apis-audio.md#attributes) of the AudioRenderer. + + ```ts + let audioRendererState = audioRenderer.state; + console.info(`Current state is: ${audioRendererState }`) + ``` + +- Register **stateChange** to listen for state changes of the AudioRenderer. + + ```ts + audioRenderer.on('stateChange', (rendererState) => { + console.info(`State change to: ${rendererState}`) + }); + ``` + +The application then performs an operation, for example, changing the display of the **Play** button, by comparing the obtained state with [AudioState](../reference/apis/js-apis-audio.md#audiostate8). + +## Reading or Listening for Changes in All Audio Streams + +If an application needs to obtain the change information about all audio streams, it can use **AudioStreamManager** to read or listen for the changes of all audio streams. + +> **NOTE** +> +> The audio stream change information marked as the system API can be viewed only by system applications. + +The figure below shows the call relationship of audio stream management. + +![Call relationship of audio stream management](figures/audio-stream-mgmt-invoking-relationship.png) + +During application development, first use **getStreamManager()** to create an **AudioStreamManager** instance. Then call **on('audioRendererChange')** to listen for audio stream changes and obtain a notification when the audio stream state or device changes. To cancel the listening for these changes, call **off('audioRendererChange')**. You can also call **getCurrentAudioRendererInfoArray()** to obtain information such as the unique ID of the playback stream, UID of the playback stream client, and stream status. + +For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9). + +## How to Develop + +1. Create an **AudioStreamManager** instance. + + Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. + + ```ts + import audio from '@ohos.multimedia.audio'; + let audioManager = audio.getAudioManager(); + let audioStreamManager = audioManager.getStreamManager(); + ``` + +2. Use **on('audioRendererChange')** to listen for audio playback stream changes. If the application needs to receive a notification when the audio playback stream state or device changes, it can subscribe to this event. + + ```ts + audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + }); + ``` + +3. (Optional) Use **off('audioRendererChange')** to cancel listening for audio playback stream changes. + + ```ts + audioStreamManager.off('audioRendererChange'); + console.info('RendererChange Off is called '); + ``` + +4. (Optional) Call **getCurrentAudioRendererInfoArray()** to obtain the information about all audio playback streams. + + This API can be used to obtain the unique ID of the audio playback stream, UID of the audio playback client, audio status, and other information about the audio player. + > **NOTE** + > + > Before listening for state changes of all audio streams, the application must request the **ohos.permission.USE_BLUETOOTH** [permission](../security/accesstoken-guidelines.md), for the device name and device address (Bluetooth related attributes) to be displayed correctly. + + ```ts + async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray Get Promise is called `); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`Invoke getCurrentAudioRendererInfoArray failed, code is ${err.code}, message is ${err.message}`); + }); + } + ``` diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md deleted file mode 100644 index 1c7953d32b8ecee4c0ff34e82ab8d13947ac9271..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-playback.md +++ /dev/null @@ -1,243 +0,0 @@ -# Audio Playback Development - -## Introduction - -You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can control the playback and volume, obtain track information, and release resources. - -## Working Principles - -The following figures show the audio playback state transition and the interaction with external modules for audio playback. - -**Figure 1** Audio playback state transition - -![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png) - -**NOTE**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value. - - - -**Figure 2** Interaction with external modules for audio playback - -![en-us_image_audio_player](figures/en-us_image_audio_player.png) - -**NOTE**: When a third-party application calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework and outputs the audio data decoded by the software to the audio HDI of the hardware interface layer to implement audio playback. - -## How to Develop - -For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md#audioplayer). - -> **NOTE** -> -> The method for obtaining the path in the FA model is different from that in the stage model. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines). - -### Full-Process Scenario - -The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting the player, and releasing resources. - -For details about the **src** types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes). - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -// Print the stream track information. -function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } -} - -// Set the player callbacks. -function setCallBack(audioPlayer) { - 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(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. - }); - audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); - audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. - }); - audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.info('audio pause success'); - audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. - }); - audioPlayer.on('stop', () => { // Set the 'stop' event callback. - console.info('audio stop success'); - audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. - }); - 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 (typeof(seekDoneTime) == 'undefined') { - console.info('audio seek fail'); - return; - } - console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. - }); - audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.info('audio volumeChange success'); - audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. - if (typeof (arrlist) != 'undefined') { - for (let i = 0; i < arrlist.length; i++) { - printfDescription(arrlist[i]); - } - } else { - console.log(`audio getTrackDescription fail, error:${error.message}`); - } - audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. - }); - }); - audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. - console.info('audio play finish'); - }); - audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); - console.info(`audio error called, errCode is ${error.code}`); - console.info(`audio error called, errMessage is ${error.message}`); - }); -} - -async function audioPlayerDemo() { - // 1. Create an AudioPlayer instance. - let audioPlayer = media.createAudioPlayer(); - setCallBack(audioPlayer); // Set the event callbacks. - // 2. Set the URI of the audio file. - 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\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. - let path = pathDir + '/01.mp3' - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. -} -``` - -### Normal Playback Scenario - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -export class AudioDemo { - // Set the player callbacks. - setCallBack(audioPlayer) { - 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(); // Call the play() API to start the playback and trigger the 'play' event callback. - }); - audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); - }); - audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. - console.info('audio play finish'); - audioPlayer.release(); // Release the AudioPlayer instance. - audioPlayer = undefined; - }); - } - - async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. - 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\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. - let path = pathDir + '/01.mp3' - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. - } -} -``` - -### Switching to the Next Song - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -export class AudioDemo { -// Set the player callbacks. - private isNextMusic = false; - setCallBack(audioPlayer) { - 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(); // Call the play() API to start the playback and trigger the 'play' event callback. - }); - audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); - audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. - }); - audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.info('audio play success'); - if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. - this.nextMusic(audioPlayer); // Changing songs is implemented. - } else { - audioPlayer.release(); // Release the AudioPlayer instance. - audioPlayer = undefined; - } - }); - } - - async nextMusic(audioPlayer) { - this.isNextMusic = true; - let nextFdPath = '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\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. - let nextpath = pathDir + '/02.mp3' - let nextFile = await fs.open(nextpath); - nextFdPath = nextFdPath + '' + nextFile.fd; - audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback. - } - - async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. - 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\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. - let path = pathDir + '/01.mp3' - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. - } -} -``` - -### Looping a Song - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -export class AudioDemo { - // Set the player callbacks. - setCallBack(audioPlayer) { - 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.loop = true; // Set the loop playback attribute. - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. - }); - audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback. - console.info('audio play success'); - }); - } - - async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. - 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\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. - let path = pathDir + '/01.mp3' - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. - } -} -``` diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md deleted file mode 100644 index 78650a61d0a803811394e623ab0bc46155438ba9..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-recorder.md +++ /dev/null @@ -1,197 +0,0 @@ -# Audio Recording Development - -## Introduction - -During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and output file path for audio recording. - -## Working Principles - -The following figures show the audio recording state transition and the interaction with external modules for audio recording. - -**Figure 1** Audio recording state transition - -![en-us_image_audio_recorder_state_machine](figures/en-us_image_audio_recorder_state_machine.png) - - - -**Figure 2** Interaction with external modules for audio recording - -![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png) - -**NOTE**: When a third-party recording application or recorder calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework to obtain the audio data captured through the audio HDI. The framework layer then encodes the audio data through software and saves the encoded and encapsulated audio data to a file to implement audio recording. - -## Constraints - -Before developing audio recording, configure the **ohos.permission.MICROPHONE** permission for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). - -## How to Develop - -For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md#audiorecorder). - -### Full-Process Scenario - -The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources. - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' -export class AudioRecorderDemo { - private testFdNumber; // Used to save the FD address. - - // Set the callbacks related to audio recording. - setCallBack(audioRecorder) { - audioRecorder.on('prepare', () => { // Set the prepare event callback. - console.log('prepare success'); - audioRecorder.start(); // Call the start API to start recording and trigger the start event callback. - }); - audioRecorder.on('start', () => { // Set the start event callback. - console.log('audio recorder start success'); - audioRecorder.pause(); // Call the pause API to pause recording and trigger the pause event callback. - }); - audioRecorder.on('pause', () => { // Set the pause event callback. - console.log('audio recorder pause success'); - audioRecorder.resume(); // Call the resume API to resume recording and trigger the resume event callback. - }); - audioRecorder.on('resume', () => { // Set the resume event callback. - console.log('audio recorder resume success'); - audioRecorder.stop(); // Call the stop API to stop recording and trigger the stop event callback. - }); - audioRecorder.on('stop', () => { // Set the stop event callback. - console.log('audio recorder stop success'); - audioRecorder.reset(); // Call the reset API to reset the recorder and trigger the reset event callback. - }); - audioRecorder.on('reset', () => { // Set the reset event callback. - console.log('audio recorder reset success'); - audioRecorder.release(); // Call the release API to release resources and trigger the release event callback. - }); - audioRecorder.on('release', () => { // Set the release event callback. - console.log('audio recorder release success'); - audioRecorder = undefined; - }); - audioRecorder.on('error', (error) => { // Set the error event callback. - console.info(`audio error called, errName is ${error.name}`); - console.info(`audio error called, errCode is ${error.code}`); - console.info(`audio error called, errMessage is ${error.message}`); - }); - } - - // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3. - // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. - async getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - this.testFdNumber = "fd://" + fdNumber.toString(); - } - } - - async audioRecorderDemo() { - // 1. Create an AudioRecorder instance. - let audioRecorder = media.createAudioRecorder(); - // 2. Set the callbacks. - this.setCallBack(audioRecorder); - await this.getFd('01.mp3'); // Call the getFd method to obtain the FD address of the file to be recorded. - // 3. Set the recording parameters. - let audioRecorderConfig = { - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - uri : this.testFdNumber, // testFdNumber is generated by getFd. - location : { latitude : 30, longitude : 130}, - audioEncoderMime : media.CodecMimeType.AUDIO_AAC, - fileFormat : media.ContainerFormatType.CFT_MPEG_4A, - } - audioRecorder.prepare(audioRecorderConfig); // Call the prepare method to trigger the prepare event callback. - } -} -``` - -### Normal Recording Scenario - -Unlike the full-process scenario, the normal recording scenario does not include the process of pausing and resuming recording. - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' -export class AudioRecorderDemo { - private testFdNumber; // Used to save the FD address. - - // Set the callbacks related to audio recording. - setCallBack(audioRecorder) { - audioRecorder.on('prepare', () => { // Set the prepare event callback. - console.log('prepare success'); - audioRecorder.start(); // Call the start API to start recording and trigger the start event callback. - }); - audioRecorder.on('start', () => { // Set the start event callback. - console.log('audio recorder start success'); - audioRecorder.stop(); // Call the stop API to stop recording and trigger the stop event callback. - }); - audioRecorder.on('stop', () => { // Set the stop event callback. - console.log('audio recorder stop success'); - audioRecorder.release(); // Call the release API to release resources and trigger the release event callback. - }); - audioRecorder.on('release', () => { // Set the release event callback. - console.log('audio recorder release success'); - audioRecorder = undefined; - }); - audioRecorder.on('error', (error) => { // Set the error event callback. - console.info(`audio error called, errName is ${error.name}`); - console.info(`audio error called, errCode is ${error.code}`); - console.info(`audio error called, errMessage is ${error.message}`); - }); - } - - // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3. - // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. - async getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - this.testFdNumber = "fd://" + fdNumber.toString(); - } - } - - async audioRecorderDemo() { - // 1. Create an AudioRecorder instance. - let audioRecorder = media.createAudioRecorder(); - // 2. Set the callbacks. - this.setCallBack(audioRecorder); - await this.getFd('01.mp3'); // Call the getFd method to obtain the FD address of the file to be recorded. - // 3. Set the recording parameters. - let audioRecorderConfig = { - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - uri : this.testFdNumber, // testFdNumber is generated by getFd. - location : { latitude : 30, longitude : 130}, - audioEncoderMime : media.CodecMimeType.AUDIO_AAC, - fileFormat : media.ContainerFormatType.CFT_MPEG_4A, - } - audioRecorder.prepare(audioRecorderConfig); // Call the prepare method to trigger the prepare event callback. - } -} -``` diff --git a/en/application-dev/media/audio-recording-overview.md b/en/application-dev/media/audio-recording-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..698255fddd78d98f9e635b16b3db94e6980bd4a0 --- /dev/null +++ b/en/application-dev/media/audio-recording-overview.md @@ -0,0 +1,17 @@ +# Audio Recording Development + +## Selecting an Audio Recording Development Mode + +OpenHarmony provides multiple classes for you to develop audio recording applications. You can select them based on the recording output formats, audio usage scenarios, and even the programming language you use. Selecting a suitable class helps you reduce development workload and your application deliver a better effect. + +- [AVRecorder](using-avrecorder-for-recording.md): provides ArkTS and JS APIs to implement audio and video recording. It also supports audio input, audio encoding, and media encapsulation. You can directly call device hardware, such as microphone, for recording and generate M4A audio files. + +- [AudioCapturer](using-audiocapturer-for-recording.md): provides ArkTS and JS API to implement audio input. It supports only the PCM format and requires applications to continuously read audio data. The application can perform data processing after audio output. This class can be used to develop more professional and diverse recording applications. To use this class, you must have basic audio processing knowledge. + +- [OpenSLES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. + +## Precautions for Developing Audio Recording Applications + +The application must request the **ohos.permission.MICROPHONE** permission from the user before invoking the microphone to record audio. + +For details about how to request the permission, see [Permission Application Guide](../security/accesstoken-guidelines.md). For details about how to use and manage microphones, see [Microphone Management](mic-management.md). diff --git a/en/application-dev/media/audio-recording-stream-management.md b/en/application-dev/media/audio-recording-stream-management.md new file mode 100644 index 0000000000000000000000000000000000000000..8161d1bd5bbe5fbc55560ab557570baaaa99976a --- /dev/null +++ b/en/application-dev/media/audio-recording-stream-management.md @@ -0,0 +1,118 @@ +# Audio Recording Stream Management + +An audio recording application must notice audio stream state changes and perform corresponding operations. For example, when detecting that the user stops recording, the application must notify the user that the recording finishes. + +## Reading or Listening for Audio Stream State Changes in the Application + +Create an AudioCapturer by referring to [Using AudioCapturer for Audio Recording](using-audiocapturer-for-recording.md) or [audio.createAudioCapturer](../reference/apis/js-apis-audio.md#audiocreateaudiocapturer8). Then obtain the audio stream state changes in either of the following ways: + +- Check the [state](../reference/apis/js-apis-audio.md#attributes) of the AudioCapturer. + + ```ts + let audioCapturerState = audioCapturer.state; + console.info(`Current state is: ${audioCapturerState }`) + ``` + +- Register **stateChange** to listen for state changes of the AudioCapturer. + + ```ts + audioCapturer.on('stateChange', (capturerState) => { + console.info(`State change to: ${capturerState}`) + }); + ``` + +The application then performs an operation, for example, displays a message indicating the end of the recording, by comparing the obtained state with [AudioState](../reference/apis/js-apis-audio.md#audiostate8). + +## Reading or Listening for Changes in All Audio Streams + +If an application needs to obtain the change information about all audio streams, it can use **AudioStreamManager** to read or listen for the changes of all audio streams. + +> **NOTE** +> +> The audio stream change information marked as the system API can be viewed only by system applications. + +The figure below shows the call relationship of audio stream management. + +![Call relationship of recording stream management](figures/invoking-relationship-recording-stream-mgmt.png) + +During application development, first use **getStreamManager()** to create an **AudioStreamManager** instance. Then call **on('audioCapturerChange')** to listen for audio stream changes and obtain a notification when the audio stream state or device changes. To cancel the listening for these changes, call **off('audioCapturerChange')**. You can call **getCurrentAudioCapturerInfoArray()** to obtain information such as the unique ID of the recording stream, UID of the recording stream client, and stream status. + +For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9). + + +## How to Develop + +1. Create an **AudioStreamManager** instance. + + Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. + + ```ts + import audio from '@ohos.multimedia.audio'; + let audioManager = audio.getAudioManager(); + let audioStreamManager = audioManager.getStreamManager(); + ``` + +2. Use **on('audioCapturerChange')** to listen for audio recording stream changes. If the application needs to receive a notification when the audio recording stream state or device changes, it can subscribe to this event. + + ```ts + audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + }); + ``` + +3. (Optional) Use **off('audioCapturerChange')** to cancel listening for audio recording stream changes. + + ```ts + audioStreamManager.off('audioCapturerChange'); + console.info('CapturerChange Off is called'); + ``` + +4. (Optional) Call **getCurrentAudioCapturerInfoArray()** to obtain information about the current audio recording stream. + + This API can be used to obtain the unique ID of the audio recording stream, UID of the audio recording client, audio status, and other information about the AudioCapturer. + > **NOTE** + > + > Before listening for state changes of all audio streams, the application must request the **ohos.permission.USE_BLUETOOTH** [permission](../security/accesstoken-guidelines.md), for the device name and device address (Bluetooth related attributes) to be displayed correctly. + + ```ts + async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray Get Promise Called '); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`Invoke getCurrentAudioCapturerInfoArray failed, code is ${err.code}, message is ${err.message}`); + }); + } + ``` diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md deleted file mode 100644 index 0a58ea5251744162d9948c23e75351b298a95bb8..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-renderer.md +++ /dev/null @@ -1,522 +0,0 @@ -# Audio Rendering Development - -## Introduction - -**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. -Before calling the APIs, be familiar with the following terms: - -- **Audio interruption**: When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. -- **Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. -- **Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). -- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus transfer is triggered by focus preemption. When focus transfer occurs, the **AudioRenderer** instance that is having the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to switch to the independent mode. - -## Working Principles - -The following figure shows the audio renderer state transitions. - -**Figure 1** Audio renderer state transitions - -![audio-renderer-state](figures/audio-renderer-state.png) - -- **PREPARED**: The audio renderer enters this state by calling **create()**. -- **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. -- **PAUSED**: The audio renderer enters this state by calling **pause()** when it is in the **RUNNING** state. When the audio playback is paused, it can call **start()** to resume the playback. -- **STOPPED**: The audio renderer enters this state by calling **stop()** when it is in the **PAUSED** or **RUNNING** state. -- **RELEASED**: The audio renderer enters this state by calling **release()** when it is in the **PREPARED**, **PAUSED**, or **STOPPED** state. In this state, the audio renderer releases all occupied hardware and software resources and will not transit to any other state. - -## How to Develop - -For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). - -1. Use **createAudioRenderer()** to create a global **AudioRenderer** instance. - Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. - - ```js - import audio from '@ohos.multimedia.audio'; - import fs from '@ohos.file.fs'; - - // Perform a self-test on APIs related to audio rendering. - @Entry - @Component - struct AudioRenderer1129 { - private audioRenderer: audio.AudioRenderer; - private bufferSize; // It will be used for the call of the write function in step 3. - private audioRenderer1: audio.AudioRenderer; // It will be used for the call in the complete example in step 14. - private audioRenderer2: audio.AudioRenderer; // It will be used for the call in the complete example in step 14. - - async initAudioRender(){ - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - let audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. - } - let audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - this.audioRenderer = await audio.createAudioRenderer(audioRendererOptions); - console.log("Create audio renderer success."); - } - } - ``` - -2. Use **start()** to start audio rendering. - - ```js - async startRenderer() { - let state = this.audioRenderer.state; - // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state when start() is called. - if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && - state != audio.AudioState.STATE_STOPPED) { - console.info('Renderer is not in a correct state to start'); - return; - } - - await this.audioRenderer.start(); - - state = this.audioRenderer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('Renderer started'); - } else { - console.error('Renderer start failed'); - } - } - ``` - - The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. - -3. Call **write()** to write data to the buffer. - - Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. Import fs from '@ohos.file.fs'; as step 1. - - ```js - async writeData(){ - // Set a proper buffer size for the audio renderer. You can also select a buffer of another size. - this.bufferSize = await this.audioRenderer.getBufferSize(); - let dir = globalThis.fileDir; // You must use the sandbox path. - const filePath = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav - console.info(`file filePath: ${ filePath}`); - - let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); - let stat = await fs.stat(filePath); // Music file information. - let buf = new ArrayBuffer(this.bufferSize); - let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - for (let i = 0;i < len; i++) { - let options = { - offset: i * this.bufferSize, - length: this.bufferSize - } - let readsize = await fs.read(file.fd, buf, options) - let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer.write(buf,(err,writeSize)=>{ - if(err){ - reject(err) - }else{ - resolve(writeSize) - } - }) - }) - } - - fs.close(file) - await this.audioRenderer.stop(); // Stop rendering. - await this.audioRenderer.release(); // Release the resources. - } - ``` - -4. (Optional) Call **pause()** or **stop()** to pause or stop rendering. - - ```js - async pauseRenderer() { - let state = this.audioRenderer.state; - // The audio renderer can be paused only when it is in the STATE_RUNNING state. - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await this.audioRenderer.pause(); - - state = this.audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async stopRenderer() { - let state = this.audioRenderer.state; - // The audio renderer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. - if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await this.audioRenderer.stop(); - - state = this.audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } - } - ``` - -5. (Optional) Call **drain()** to clear the buffer. - - ```js - async drainRenderer() { - let state = this.audioRenderer.state; - // drain() can be used only when the audio renderer is in the STATE_RUNNING state. - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await this.audioRenderer.drain(); - state = this.audioRenderer.state; - } - ``` - -6. After the task is complete, call **release()** to release related resources. - - **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete. - - ```js - async releaseRenderer() { - let state = this.audioRenderer.state; - // The audio renderer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. - if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { - console.info('Renderer already released'); - return; - } - await this.audioRenderer.release(); - - state = this.audioRenderer.state; - if (state == audio.AudioState.STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } - } - ``` - -7. (Optional) Obtain the audio renderer information. - - You can use the following code to obtain the audio renderer information: - - ```js - async getRenderInfo(){ - // Obtain the audio renderer state. - let state = this.audioRenderer.state; - // Obtain the audio renderer information. - let audioRendererInfo : audio.AudioRendererInfo = await this.audioRenderer.getRendererInfo(); - // Obtain the audio stream information. - let audioStreamInfo : audio.AudioStreamInfo = await this.audioRenderer.getStreamInfo(); - // Obtain the audio stream ID. - let audioStreamId : number = await this.audioRenderer.getAudioStreamId(); - // Obtain the Unix timestamp, in nanoseconds. - let audioTime : number = await this.audioRenderer.getAudioTime(); - // Obtain a proper minimum buffer size. - let bufferSize : number = await this.audioRenderer.getBufferSize(); - // Obtain the audio renderer rate. - let renderRate : audio.AudioRendererRate = await this.audioRenderer.getRenderRate(); - } - ``` - -8. (Optional) Set the audio renderer information. - - You can use the following code to set the audio renderer information: - - ```js - async setAudioRenderInfo(){ - // Set the audio renderer rate to RENDER_RATE_NORMAL. - let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; - await this.audioRenderer.setRenderRate(renderRate); - // Set the interruption mode of the audio renderer to SHARE_MODE. - let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; - await this.audioRenderer.setInterruptMode(interruptMode); - // Set the volume of the stream to 0.5. - let volume : number = 0.5; - await this.audioRenderer.setVolume(volume); - } - ``` - -9. (Optional) Use **on('audioInterrupt')** to subscribe to the audio interruption event, and use **off('audioInterrupt')** to unsubscribe from the event. - - Audio interruption means that Stream A will be interrupted when Stream B with a higher or equal priority requests to become active and use the output device. - - In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. - - In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption-unaware applications can use **audioRenderer.state** to check the audio renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). - - It should be noted that the audio interruption event subscription of the **AudioRenderer** module is slightly different from **on('interrupt')** in [AudioManager](../reference/apis/js-apis-audio.md#audiomanager). The **on('interrupt')** and **off('interrupt')** APIs are deprecated since API version 9. In the **AudioRenderer** module, you only need to call **on('audioInterrupt')** to listen for focus change events. When the **AudioRenderer** instance created by the application performs actions such as start, stop, and pause, it requests the focus, which triggers focus transfer and in return enables the related **AudioRenderer** instance to receive a notification through the callback. For instances other than **AudioRenderer**, such as frequency modulation (FM) and voice wakeup, the application does not create an instance. In this case, the application can call **on('interrupt')** in **AudioManager** to receive a focus change notification. - - ```js - async subscribeAudioRender(){ - this.audioRenderer.on('audioInterrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info(`InterruptType: ${interruptEvent.eventType}`); - console.info(`InterruptForceType: ${interruptEvent.forceType}`); - console.info(`AInterruptHint: ${interruptEvent.hintType}`); - - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Forcible pausing initiated by the audio framework. To prevent data loss, stop the write operation. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('isPlay is false'); - break; - // Forcible stopping initiated by the audio framework. To prevent data loss, stop the write operation. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.info('isPlay is false'); - break; - // Forcible ducking initiated by the audio framework. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Undocking initiated by the audio framework. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Notify the application that the rendering starts. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - this.startRenderer(); - break; - // Notify the application that the audio stream is interrupted. The application then determines whether to continue. (In this example, the application pauses the rendering.) - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('isPlay is false'); - this.pauseRenderer(); - break; - } - } - }); - } - ``` - -10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. - - After the mark reached event is subscribed to, when the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned. - - ```js - async markReach(){ - this.audioRenderer.on('markReach', 50, (position) => { - if (position == 50) { - console.info('ON Triggered successfully'); - } - }); - this.audioRenderer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. - } - ``` - -11. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. - - After the period reached event is subscribed to, each time the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned. - - ```js - async periodReach(){ - this.audioRenderer.on('periodReach',10, (reachNumber) => { - console.info(`In this period, the renderer reached frame: ${reachNumber} `); - }); - - this.audioRenderer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. - } - ``` - -12. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. - - After the **stateChange** event is subscribed to, when the audio renderer state changes, a callback is triggered and the audio renderer state is returned. - - ```js - async stateChange(){ - this.audioRenderer.on('stateChange', (audioState) => { - console.info('State change event Received'); - console.info(`Current renderer state is: ${audioState}`); - }); - } - ``` - -13. (Optional) Handle exceptions of **on()**. - - If the string or the parameter type passed in **on()** is incorrect , the application throws an exception. In this case, you can use **try catch** to capture the exception. - - ```js - async errorCall(){ - try { - this.audioRenderer.on('invalidInput', () => { // The string is invalid. - }) - } catch (err) { - console.info(`Call on function error, ${err}`); // The application throws exception 401. - } - try { - this.audioRenderer.on(1, () => { // The type of the input parameter is incorrect. - }) - } catch (err) { - console.info(`Call on function error, ${err}`); // The application throws exception 6800101. - } - } - ``` - -14. (Optional) Refer to the complete example of **on('audioInterrupt')**. - Declare audioRenderer1 and audioRenderer2 first. For details, see step 1. - Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRender1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. - ```js - async runningAudioRender1(){ - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - let audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_MUSIC, - usage: audio.StreamUsage.STREAM_USAGE_MEDIA, - rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. - } - let audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - - // 1.1 Create an instance. - this.audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); - console.info("Create audio renderer 1 success."); - - // 1.2 Set the independent mode. - this.audioRenderer1.setInterruptMode(1).then( data => { - console.info('audioRenderer1 setInterruptMode Success!'); - }).catch((err) => { - console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); - }); - - // 1.3 Set the listener. - this.audioRenderer1.on('audioInterrupt', async(interruptEvent) => { - console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) - }); - - // 1.4 Start rendering. - await this.audioRenderer1.start(); - console.info('startAudioRender1 success'); - - // 1.5 Obtain the buffer size, which is the proper minimum buffer size of the audio renderer. You can also select a buffer of another size. - const bufferSize = await this.audioRenderer1.getBufferSize(); - console.info(`audio bufferSize: ${bufferSize}`); - - // 1.6 Obtain the original audio data file. - let dir = globalThis.fileDir; // You must use the sandbox path. - const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav - console.info(`audioRender1 file path: ${ path1}`); - let file1 = fs.openSync(path1, fs.OpenMode.READ_ONLY); - let stat = await fs.stat(path1); // Music file information. - let buf = new ArrayBuffer(bufferSize); - let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - - // 1.7 Render the original audio data in the buffer by using audioRender. - for (let i = 0;i < len; i++) { - let options = { - offset: i * this.bufferSize, - length: this.bufferSize - } - let readsize = await fs.read(file1.fd, buf, options) - let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer1.write(buf,(err,writeSize)=>{ - if(err){ - reject(err) - }else{ - resolve(writeSize) - } - }) - }) - } - fs.close(file1) - await this.audioRenderer1.stop(); // Stop rendering. - await this.audioRenderer1.release(); // Release the resources. - } - - async runningAudioRender2(){ - let audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - let audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_MUSIC, - usage: audio.StreamUsage.STREAM_USAGE_MEDIA, - rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. - } - let audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - - // 2.1 Create another instance. - this.audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); - console.info("Create audio renderer 2 success."); - - // 2.2 Set the independent mode. - this.audioRenderer2.setInterruptMode(1).then( data => { - console.info('audioRenderer2 setInterruptMode Success!'); - }).catch((err) => { - console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); - }); - - // 2.3 Set the listener. - this.audioRenderer2.on('audioInterrupt', async(interruptEvent) => { - console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) - }); - - // 2.4 Start rendering. - await this.audioRenderer2.start(); - console.info('startAudioRender2 success'); - - // 2.5 Obtain the buffer size. - const bufferSize = await this.audioRenderer2.getBufferSize(); - console.info(`audio bufferSize: ${bufferSize}`); - - // 2.6 Read the original audio data file. - let dir = globalThis.fileDir; // You must use the sandbox path. - const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav - console.info(`audioRender2 file path: ${ path2}`); - let file2 = fs.openSync(path2, fs.OpenMode.READ_ONLY); - let stat = await fs.stat(path2); // Music file information. - let buf = new ArrayBuffer(bufferSize); - let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1); - - // 2.7 Render the original audio data in the buffer by using audioRender. - for (let i = 0;i < len; i++) { - let options = { - offset: i * this.bufferSize, - length: this.bufferSize - } - let readsize = await fs.read(file2.fd, buf, options) - let writeSize = await new Promise((resolve,reject)=>{ - this.audioRenderer2.write(buf,(err,writeSize)=>{ - if(err){ - reject(err) - }else{ - resolve(writeSize) - } - }) - }) - } - fs.close(file2) - await this.audioRenderer2.stop(); // Stop rendering. - await this.audioRenderer2.release(); // Release the resources. - } - - // Integrated invoking entry. - async test(){ - await this.runningAudioRender1(); - await this.runningAudioRender2(); - } - - ``` \ No newline at end of file diff --git a/en/application-dev/media/audio-routing-manager.md b/en/application-dev/media/audio-routing-manager.md deleted file mode 100644 index 55febdca0fad968d946601fce4faed99bc148dd2..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-routing-manager.md +++ /dev/null @@ -1,111 +0,0 @@ -# Audio Routing and Device Management Development - -## Overview - -The **AudioRoutingManager** module provides APIs for audio routing and device management. You can use the APIs to obtain the current input and output audio devices, listen for connection status changes of audio devices, and activate communication devices. - -## Working Principles - -The figure below shows the common APIs provided by the **AudioRoutingManager** module. - -**Figure 1** Common APIs of AudioRoutingManager - -![en-us_image_audio_routing_manager](figures/en-us_image_audio_routing_manager.png) - -You can use these APIs to obtain the device list, subscribe to or unsubscribe from device connection status changes, activate communication devices, and obtain their activation status. For details, see [Audio Management](../reference/apis/js-apis-audio.md). - - -## How to Develop - -For details about the APIs, see [AudioRoutingManager in Audio Management](../reference/apis/js-apis-audio.md#audioroutingmanager9). - -1. Obtain an **AudioRoutingManager** instance. - - Before using an API in **AudioRoutingManager**, you must use **getRoutingManager()** to obtain an **AudioRoutingManager** instance. - - ```js - import audio from '@ohos.multimedia.audio'; - async loadAudioRoutingManager() { - var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); - console.info('audioRoutingManager------create-------success.'); - } - - ``` - -2. (Optional) Obtain the device list and subscribe to device connection status changes. - - To obtain the device list (such as input, output, distributed input, and distributed output devices) or listen for connection status changes of audio devices, refer to the following code: - - ```js - import audio from '@ohos.multimedia.audio'; - // Obtain an AudioRoutingManager instance. - async loadAudioRoutingManager() { - var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); - console.info('audioRoutingManager------create-------success.'); - } - // Obtain information about all audio devices. (You can set DeviceFlag as required.) - async getDevices() { - await loadAudioRoutingManager(); - await audioRoutingManager.getDevices(audio.DeviceFlag.ALL_DEVICES_FLAG).then((data) => { - console.info(`getDevices success and data is: ${JSON.stringify(data)}.`); - }); - } - // Subscribe to connection status changes of audio devices. - async onDeviceChange() { - await loadAudioRoutingManager(); - await audioRoutingManager.on('deviceChange', audio.DeviceFlag.ALL_DEVICES_FLAG, (deviceChanged) => { - console.info('on device change type : ' + deviceChanged.type); - console.info('on device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); - console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); - }); - } - // Unsubscribe from the connection status changes of audio devices. - async offDeviceChange() { - await loadAudioRoutingManager(); - await audioRoutingManager.off('deviceChange', (deviceChanged) => { - console.info('off device change type : ' + deviceChanged.type); - console.info('off device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); - console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); - }); - } - // Complete process: Call APIs to obtain all devices and subscribe to device changes, then manually change the connection status of a device (for example, wired headset), and finally call APIs to obtain all devices and unsubscribe from the device changes. - async test(){ - await getDevices(); - await onDeviceChange()(); - // Manually disconnect or connect devices. - await getDevices(); - await offDeviceChange(); - } - ``` - -3. (Optional) Activate a communication device and obtain its activation status. - - ```js - import audio from '@ohos.multimedia.audio'; - // Obtain an AudioRoutingManager instance. - async loadAudioRoutingManager() { - var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); - console.info('audioRoutingManager------create-------success.'); - } - // Activate a communication device. - async setCommunicationDevice() { - await loadAudioRoutingManager(); - await audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { - console.info('setCommunicationDevice true is success.'); - }); - } - // Obtain the activation status of the communication device. - async isCommunicationDeviceActive() { - await loadAudioRoutingManager(); - await audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { - console.info(`CommunicationDevice state is: ${value}.`); - }); - } - // Complete process: Activate a device and obtain the activation status. - async test(){ - await setCommunicationDevice(); - await isCommunicationDeviceActive(); - } - ``` diff --git a/en/application-dev/media/audio-stream-manager.md b/en/application-dev/media/audio-stream-manager.md deleted file mode 100644 index 44ec37cd11f3666131214e5e908a1ce761fea111..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-stream-manager.md +++ /dev/null @@ -1,164 +0,0 @@ -# Audio Stream Management Development - -## Introduction - -You can use **AudioStreamManager** to manage audio streams. - -## Working Principles - -The following figure shows the calling relationship of **AudioStreamManager** APIs. - -**Figure 1** AudioStreamManager API calling relationship - -![en-us_image_audio_stream_manager](figures/en-us_image_audio_stream_manager.png) - -**NOTE**: During application development, use **getStreamManager()** to create an **AudioStreamManager** instance. Then, you can call **on('audioRendererChange')** or **on('audioCapturerChange')** to listen for status, client, and audio attribute changes of the audio playback or recording application. To cancel the listening for these changes, call **off('audioRendererChange')** or **off('audioCapturerChange')**. You can call **getCurrentAudioRendererInfoArray()** to obtain information about the audio playback application, such as the unique audio stream ID, UID of the audio playback client, and audio status. Similarly, you can call **getCurrentAudioCapturerInfoArray()** to obtain information about the audio recording application. - -## How to Develop - -For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9). - -1. Create an **AudioStreamManager** instance. - - Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. - - ```js - var audioManager = audio.getAudioManager(); - var audioStreamManager = audioManager.getStreamManager(); - ``` - -2. (Optional) Call **on('audioRendererChange')** to listen for audio renderer changes. - - If an application needs to receive notifications when the audio playback application status, audio playback client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). - - ```js - audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info('## RendererChange on is called for ' + i + ' ##'); - console.info('StreamId for ' + i + ' is:' + AudioRendererChangeInfo.streamId); - console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid); - console.info('Content for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content); - console.info('Stream for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.usage); - console.info('Flag ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState); - var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); - } - } - }); - ``` - -3. (Optional) Call **off('audioRendererChange')** to cancel listening for audio renderer changes. - - ```js - audioStreamManager.off('audioRendererChange'); - console.info('######### RendererChange Off is called #########'); - ``` - -4. (Optional) Call **on('audioCapturerChange')** to listen for audio capturer changes. - - If an application needs to receive notifications when the audio recording application status, audio recording client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). - - ```js - audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(' ## audioCapturerChange on is called for element ' + i + ' ##'); - console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId); - console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid); - console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); - } - } - }); - ``` - -5. (Optional) Call **off('audioCapturerChange')** to cancel listening for audio capturer changes. - - ```js - audioStreamManager.off('audioCapturerChange'); - console.info('######### CapturerChange Off is called #########'); - ``` - -6. (Optional) Call **getCurrentAudioRendererInfoArray()** to obtain information about the current audio renderer. - - This API can be used to obtain the unique ID of the audio stream, UID of the audio playback client, audio status, and other information about the audio player. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly. - - ```js - await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info('######### Get Promise is called ##########'); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info('StreamId for ' + i +' is:' + AudioRendererChangeInfo.streamId); - console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid); - console.info('Content ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content); - console.info('Stream' + i +' is:' + AudioRendererChangeInfo.rendererInfo.usage); - console.info('Flag' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState); - var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); - } - } - } - }).catch((err) => { - console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message); - }); - ``` - -7. (Optional) Call **getCurrentAudioCapturerInfoArray()** to obtain information about the current audio capturer. - This API can be used to obtain the unique ID of the audio stream, UID of the audio recording client, audio status, and other information about the audio capturer. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly. - - ```js - await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray: **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId); - console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid); - console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState); - var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name) - console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); - } - } - } - }).catch((err) => { - console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message); - }); - ``` diff --git a/en/application-dev/media/audio-volume-manager.md b/en/application-dev/media/audio-volume-manager.md deleted file mode 100644 index 28ed3dcbc8709609d092a96065a70996b4f487b5..0000000000000000000000000000000000000000 --- a/en/application-dev/media/audio-volume-manager.md +++ /dev/null @@ -1,126 +0,0 @@ -# Volume Management Development - -## Overview - -The **AudioVolumeManager** module provides APIs for volume management. You can use the APIs to obtain the volume of a stream, listen for ringer mode changes, and mute a microphone. - -## Working Principles - -The figure below shows the common APIs provided by the **AudioVolumeManager** module. - -**Figure 1** Common APIs of AudioVolumeManager - -![en-us_image_audio_volume_manager](figures/en-us_image_audio_volume_manager.png) - -**AudioVolumeManager** provides the APIs for subscribing to system volume changes and obtaining the audio volume group manager (an **AudioVolumeGroupManager** instance). Before calling any API in **AudioVolumeGroupManager**, you must call **getVolumeGroupManager** to obtain an **AudioVolumeGroupManager** instance. You can use the APIs provided by **AudioVolumeGroupManager** to obtain the volume of a stream, mute a microphone, and listen for microphone state changes. For details, see [Audio Management](../reference/apis/js-apis-audio.md). - -## Constraints - -Before developing a microphone management application, configure the permission **ohos.permission.MICROPHONE** for the application. To set the microphone state, configure the permission **ohos.permission.MANAGE_AUDIO_CONFIG** (a system permission). For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - -## How to Develop - -For details about the APIs, see [AudioVolumeManager in Audio Management](../reference/apis/js-apis-audio.md#audiovolumemanager9) - -1. Obtain an **AudioVolumeGroupManager** instance. - - Before using an API in **AudioVolumeGroupManager**, you must use **getVolumeGroupManager()** to obtain an **AudioStreamManager** instance. - - ```js - import audio from '@ohos.multimedia.audio'; - async loadVolumeGroupManager() { - const groupid = audio.DEFAULT_VOLUME_GROUP_ID; - var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); - console.error('audioVolumeGroupManager create success.'); - } - - ``` - -2. (Optional) Obtain the volume information and ringer mode. - - To obtain the volume information of an audio stream (such as the ringtone, voice call, media, and voice assistant) or obtain the ringer mode (silent, vibration, or normal) of the current device, refer to the code below. For more details, see [Audio Management](../reference/apis/js-apis-audio.md). - - ```js - import audio from '@ohos.multimedia.audio'; - async loadVolumeGroupManager() { - const groupid = audio.DEFAULT_VOLUME_GROUP_ID; - var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); - console.info('audioVolumeGroupManager create success.'); - } - - // Obtain the volume of a stream. The value ranges from 0 to 15. - async getVolume() { - await loadVolumeGroupManager(); - await audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`getVolume success and volume is: ${value}.`); - }); - } - // Obtain the minimum volume of a stream. - async getMinVolume() { - await loadVolumeGroupManager(); - await audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`getMinVolume success and volume is: ${value}.`); - }); - } - // Obtain the maximum volume of a stream. - async getMaxVolume() { - await loadVolumeGroupManager(); - await audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`getMaxVolume success and volume is: ${value}.`); - }); - } - // Obtain the ringer mode in use: silent (0) | vibrate (1) | normal (2). - async getRingerMode() { - await loadVolumeGroupManager(); - await audioVolumeGroupManager.getRingerMode().then((value) => { - console.info(`getRingerMode success and RingerMode is: ${value}.`); - }); - } - ``` - -3. (Optional) Obtain and set the microphone state, and subscribe to microphone state changes. - - To obtain and set the microphone state or subscribe to microphone state changes, refer to the following code: - - ```js - import audio from '@ohos.multimedia.audio'; - async loadVolumeGroupManager() { - const groupid = audio.DEFAULT_VOLUME_GROUP_ID; - var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); - console.info('audioVolumeGroupManager create success.'); - } - - async on() { // Subscribe to microphone state changes. - await loadVolumeGroupManager(); - await audioVolumeGroupManager.audioVolumeGroupManager.on('micStateChange', (micStateChange) => { - console.info(`Current microphone status is: ${micStateChange.mute} `); - }); - } - - async isMicrophoneMute() { // Check whether the microphone is muted. - await audioVolumeGroupManager.audioVolumeGroupManager.isMicrophoneMute().then((value) => { - console.info(`isMicrophoneMute is: ${value}.`); - }); - } - - async setMicrophoneMuteTrue() { // Mute the microphone. - await loadVolumeGroupManager(); - await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(true).then(() => { - console.info('setMicrophoneMute to mute.'); - }); - } - - async setMicrophoneMuteFalse() { // Unmute the microphone. - await loadVolumeGroupManager(); - await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(false).then(() => { - console.info('setMicrophoneMute to not mute.'); - }); - } - async test(){ // Complete process: Subscribe to microphone state changes, obtain the microphone state, mute the microphone, obtain the microphone state, and then unmute the microphone. - await on(); - await isMicrophoneMute(); - await setMicrophoneMuteTrue(); - await isMicrophoneMute(); - await setMicrophoneMuteFalse(); - } - ``` diff --git a/en/application-dev/media/av-overview.md b/en/application-dev/media/av-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..eb0ea76dbfa90a3d3e3dd13e98ecf40876714310 --- /dev/null +++ b/en/application-dev/media/av-overview.md @@ -0,0 +1,66 @@ +# Audio and Video Overview + +You will learn how to use the audio and video APIs provided by the multimedia subsystem to develop a wealth of audio and video playback or recording scenarios. For example, you can use the **TonePlayer** class to implement simple prompt tones so that a drip sound is played upon the receipt of a new message, or use the **AVPlayer** class to develop a music player, which can loop a piece of music. + +For every functionality provided by the multimedia subsystem, you will learn multiple implementation modes, each of which corresponds to a specific usage scenario. You will also learn the sub-functionalities in these scenarios. For example, in the **Audio Playback** chapter, you will learn audio concurrency policies, volume management, and output device processing methods. All these will help you develop an application with more comprehensive features. + +This development guide applies only to audio and video playback and recording, which are implemented by the [@ohos.multimedia.audio](../reference/apis/js-apis-audio.md) and [@ohos.multimedia.media](../reference/apis/js-apis-media.md) modules. The UI, image processing, media storage, or other related capabilities are not covered. + +## Development Description + +Before developing an audio feature, especially before implementing audio data processing, you are advised to understand the following acoustic concepts. This will help you understand how the OpenHarmony APIs control the audio module and how to develop audio and video applications that are easier to use and deliver better experience. + +- Audio quantization process: sampling > quantization > encoding + +- Concepts related to audio quantization: analog signal, digital signal, sampling rate, audio channel, sample format, bit width, bit rate, common encoding formats (such as AAC, MP3, PCM, and WMA), and common encapsulation formats (such as WAV, MPA, FLAC, AAC, and OGG) + +Before developing features related to audio and video playback, you are advised to understand the following concepts: + +- Playback process: network protocol > container format > audio and video codec > graphics/audio rendering +- Network protocols: HLS, HTTP, HTTPS, and more +- Container formats: MP4, MKV, MPEG-TS, WebM, and more +- Encoding formats: H.263/H.264/H.265, MPEG4/MPEG2, and more + +## Introduction to Audio Streams + +An audio stream is an independent audio data processing unit that has a specific audio format and audio usage scenario information. The audio stream can be used in playback and recording scenarios, and supports independent volume adjustment and audio device routing. + +The basic audio stream information is defined by [AudioStreamInfo](../reference/apis/js-apis-audio.md#audiostreaminfo8), which includes the sampling, audio channel, bit width, and encoding information. It describes the basic attributes of audio data and is mandatory for creating an audio playback or recording stream. To enable the audio module to correctly process audio data, the configured basic information must match the transmitted audio data. + +### Audio Stream Usage Scenario Information + +In addition to the basic information (which describes only audio data), an audio stream has usage scenario information. This is because audio streams differ in the volume, device routing, and concurrency policy. The system chooses an appropriate processing policy for an audio stream based on the usage scenario information, thereby delivering the optimal user experience. + +- Playback scenario + +Information about the audio playback scenario is defined by using [StreamUsage](../reference/apis/js-apis-audio.md#streamusage) and [ContentType](../reference/apis/js-apis-audio.md#contenttype). + +- **StreamUsage** specifies the usage type of an audio stream, for example, used for media, voice communication, voice assistant, notification, and ringtone. + +- **ContentType** specifies the content type of data in an audio stream, for example, speech, music, movie, notification tone, and ringtone. + +- Recording scenario + +Information about the audio stream recording scenario is defined by [SourceType](../reference/apis/js-apis-audio.md#sourcetype8). + + **SourceType** specifies the recording source type of an audio stream, including the mic source, voice recognition source, and voice communication source. + +## Supported Audio Formats + +The APIs of the audio module support PCM encoding, including AudioRenderer, AudioCapturer, TonePlayer, and OpenSL ES. + +Be familiar with the following about the audio format: + +- The common audio sampling rates are supported: 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, and 96000, in units of Hz. For details, see [AudioSamplingRate](../reference/apis/js-apis-audio.md#audiosamplingrate8). + +The sampling rate varies according to the device type. + +- Mono and stereo are supported. For details, see [AudioChannel](../reference/apis/js-apis-audio.md#audiochannel8). + +- The following sampling formats are supported: U8 (unsigned 8-bit integer), S16LE (signed 16-bit integer, little endian), S24LE (signed 24-bit integer, little endian), S32LE (signed 32-bit integer, little endian), and F32LE (signed 32-bit floating point number, little endian). For details, see [AudioSampleFormat](../reference/apis/js-apis-audio.md#audiosampleformat8). + +Due to system restrictions, only some devices support the sampling formats S24LE, S32LE, and F32LE. + + Little endian means that the most significant byte is stored at the largest memory address and the least significant byte of data is stored at the smallest. This storage mode effectively combines the memory address with the bit weight of the data. Specifically, the largest memory address has a high weight, and the smallest memory address has a low weight. + +The audio and video formats supported by the APIs of the media module are described in [AVPlayer and AVRecorder](avplayer-avrecorder-overview.md). diff --git a/en/application-dev/media/avplayer-avrecorder-overview.md b/en/application-dev/media/avplayer-avrecorder-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..051ca3b66ce1839046a2e783a8c274c304625045 --- /dev/null +++ b/en/application-dev/media/avplayer-avrecorder-overview.md @@ -0,0 +1,148 @@ +# AVPlayer and AVRecorder + +The media module provides the [AVPlayer](#avplayer) and [AVRecorder](#avrecorder) class to implement audio and video playback and recording. + +## AVPlayer + +The AVPlayer transcodes audio and video media assets (such as MP4, MP3, MKV, and MPEG-TS) into renderable images and hearable audio analog signals, and plays the audio and video through output devices. + +The AVPlayer provides the integrated playback capability. This means that your application only needs to provide streaming media sources to implement media playback. It does not need to parse or decode data. + + +### Audio Playback + +The figure below shows the interaction when the **AVPlayer** class is used to develop a music application. + +**Figure 1** Interaction with external modules for audio playback + +![Audio playback interaction diagram](figures/audio-playback-interaction-diagram.png) + +When a music application calls the **AVPlayer** APIs at the JS interface layer to implement audio playback, the player framework at the framework layer parses the media asset into audio data streams (in PCM format). The audio data streams are then decoded by software and output to the audio framework. The audio framework outputs the audio data streams to the audio HDI for rendering. A complete audio playback process requires the cooperation of the application, player framework, audio framework, and audio HDI. + +In Figure 1, the numbers indicate the process where data is transferred to external modules. + +1. The music application transfers the media asset to the **AVPlayer** instance. + +2. The player framework outputs the audio PCM data streams to the audio framework, which then outputs the data streams to the audio HDI. + +### Video Playback + +The figure below shows the interaction when the **AVPlayer** class is used to develop a video application. + +**Figure 2** Interaction with external modules for video playback + +![Video playback interaction diagram](figures/video-playback-interaction-diagram.png) + +When the video application calls the **AVPlayer** APIs at the JS interface layer to implement audio and video playback, the player framework at the framework layer parses the media asset into separate audio data streams and video data streams. The audio data streams are then decoded by software and output to 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 graphic framework. The graphic framework outputs the video data streams to the display HDI at the hardware interface layer to implement graphics rendering. + +A complete video playback process requires the cooperation of the application, XComponent, player framework, graphic framework, audio framework, display HDI, and audio HDI. + +In Figure 2, the numbers indicate the process where data is transferred to external modules. + +1. The application obtains a window surface ID from the XComponent. For details about how to obtain the window surface ID, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md). + +2. The application transfers the media asset and surface ID to the **AVPlayer** instance. + +3. The player framework outputs the video elementary streams (ESs) to the decoding HDI to obtain video frames (NV12/NV21/RGBA). + +4. The player framework outputs the audio PCM data streams to the audio framework, which then outputs the data streams to the audio HDI. + +5. The player framework outputs the video frames (NV12/NV21/RGBA) to the graphic framework, which then outputs the video frames to the display HDI. + +### Supported Formats and Protocols + +Audio and video containers and codecs are domains specific to content creators. You are advised to use the mainstream playback formats, 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 playback. + +The table below lists the supported protocols. + +| Scenario| Description| +| -------- | -------- | +| Local VOD| The file descriptor is supported, but the file path is not.| +| Network VoD| HTTP, HTTPS, and HLS are supported.| + +The table below lists the supported audio playback formats. + +| Audio Container Format| Description| +| -------- | -------- | +| M4A| Audio format: AAC| +| AAC| Audio format: AAC| +| MP3| Audio format: MP3| +| OGG| Audio format: VORBIS | +| WAV| Audio format: PCM | + +> **NOTE** +> +> The supported video formats are further classified into mandatory and optional ones. All vendors must support mandatory ones and can determine whether to implement optional ones based on their service requirements. You are advised to perform compatibility processing to ensure that all the application functions are compatible on different platforms. + +| Video Format| Mandatory or Not| +| -------- | -------- | +| H.264 | Yes| +| MPEG-2 | No| +| MPEG-4 | No| +| H.263 | No| +| VP8 | No| + +The table below lists the supported playback formats and mainstream resolutions. + +| Video Container Format| Description| Resolution| +| -------- | -------- | -------- | +| MP4| Video formats: H.264, MPEG-2, MPEG-4, and H.263
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| MKV| Video formats: H.264, MPEG-2, MPEG-4, and H.263
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| TS| Video formats: H.264, MPEG-2, and MPEG-4
Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| +| WebM| Video format: VP8
Audio format: VORBIS| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| + +## AVRecorder + +The AVRecorder captures audio signals, receives video signals, encodes the 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. + +**Figure 3** Interaction with external modules for video recording + +![Video recording interaction diagram](figures/video-recording-interaction-diagram.png) + +- Audio recording: When an application calls the **AVRecorder** APIs at the JS interface layer to implement audio recording, the player framework at the framework layer invokes the audio framework to capture audio data through the audio HDI. The audio data is then encoded by software and saved into a file. + +- Video recording: When an application calls the **AVRecorder** APIs at the JS interface layer to implement video recording, the camera framework is first invoked to capture image data. Through the video encoding HDI, the camera framework sends the data to the player framework at the framework layer. The player framework encodes the image data through the video HDI and saves the encoded image data into a file. + +With the AVRecorder, you can implement pure audio recording, pure video recording, and audio and video recording. + +In Figure 3, the numbers indicate the process where data is transferred to external modules. + +1. The application obtains a surface ID from the player framework through the **AVRecorder** instance. + +2. The application sets the surface ID for the camera framework, which obtains the surface corresponding to the surface ID. The camera framework captures image data through the video HDI and sends the data to the player framework at the framework layer. + +3. The camera framework transfers the video data to the player framework through the surface. + +4. The player framework encodes video data through the video HDI. + +5. The player framework sets the audio parameters for the audio framework and obtains the audio data from the audio framework. + +### Supported Formats + +The table below lists the supported audio sources. + +| Type| Description| +| -------- | -------- | +| mic | The system microphone is used as the audio source input.| + +The table below lists the supported video sources. + +| Type| Description | +| -------- | -------- | +| surface_yuv | The input surface carries raw data.| +| surface_es | The input surface carries ES data.| + +The table below lists the supported audio and video encoding formats. + +| Encoding Format| Description | +| -------- | -------- | +| audio/mp4a-latm | Audio encoding format MP4A-LATM.| +| video/mp4v-es | Video encoding format MPEG-4.| +| video/avc | Video encoding format AVC.| + +The table below lists the supported output file formats. + +| Format| Description | +| -------- | -------- | +| MP4| Video container format MP4.| +| M4A| Audio container format M4A.| diff --git a/en/application-dev/media/avplayer-playback.md b/en/application-dev/media/avplayer-playback.md deleted file mode 100644 index 9a7d9ffa10e2de83e676adbd2c5af7f9b3ba35af..0000000000000000000000000000000000000000 --- a/en/application-dev/media/avplayer-playback.md +++ /dev/null @@ -1,477 +0,0 @@ -# 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 fs from '@ohos.file.fs' - -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' - let file = await fs.open(path) - fdPath = fdPath + '' + file.fd - this.avPlayer.url = fdPath - } -} -``` - -### Normal Playback Scenario - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -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.release() // 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 fileDescriptor = undefined - // Use getRawFileDescriptor of the resource management module to obtain the media assets in the application, and use the fdSrc attribute of the AVPlayer to initialize the media assets. - // For details on the fd/offset/length parameter, see the Media API. The globalThis.abilityContext parameter is a system environment variable and is saved as a global variable on the main page during the system boost. - await globalThis.abilityContext.resourceManager.getRawFileDescriptor('H264_AAC.mp4').then((value) => { - fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length} - }) - this.avPlayer.fdSrc = fileDescriptor - } -} -``` - -### Looping a Song - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -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.release() // 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' - let file = await fs.open(path) - fdPath = fdPath + '' + file.fd - this.avPlayer.url = fdPath - } -} -``` -### Switching to the Next Video Clip - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' - -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' - let file = await fs.open(path) - fdPath = fdPath + '' + file.fd - 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' - let file = await fs.open(path) - fdPath = fdPath + '' + file.fd - this.avPlayer.url = fdPath - } -} -``` diff --git a/en/application-dev/media/avrecorder.md b/en/application-dev/media/avrecorder.md deleted file mode 100644 index 9214df032d7d060cabe9900e8a0d5ab6e7aa12f9..0000000000000000000000000000000000000000 --- a/en/application-dev/media/avrecorder.md +++ /dev/null @@ -1,488 +0,0 @@ -# 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 based on those supported by the hardware device. - let avProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : media.CodecMimeType.AUDIO_AAC, - audioSampleRate : 48000, - fileFormat : media.ContainerFormatType.CFT_MPEG_4, - videoBitrate : 2000000, - 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 pure video recording based on those supported by the hardware device. - let videoProfile = { - fileFormat : media.ContainerFormatType.CFT_MPEG_4, - videoBitrate : 2000000, - 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/avsession-guidelines.md b/en/application-dev/media/avsession-guidelines.md deleted file mode 100644 index 3d1ac479f0f358c42778e60a0d4b47edafe0a0cd..0000000000000000000000000000000000000000 --- a/en/application-dev/media/avsession-guidelines.md +++ /dev/null @@ -1,633 +0,0 @@ -# AVSession Development - -> **NOTE** -> -> All APIs of the **AVSession** module are system APIs and can be called only by system applications. - -## Development for the Session Access End - -### Basic Concepts -- **AVMetadata**: media data related attributes, including the IDs of the current media asset, previous media asset, and next media asset, title, author, album, writer, and duration. -- **AVSessionDescriptor**: descriptor about a media session, including the session ID, session type (audio/video), custom session name (**sessionTag**), and information about the corresponding application (**elementName**). -- **AVPlaybackState**: information related to the media playback state, including the playback state, position, speed, buffered time, loop mode, and whether the media asset is favorited (**isFavorite**). - -### Available APIs -The table below lists the APIs available for the development of the session access end. The APIs use either a callback or promise to return the result. The APIs listed below use a callback, which provide the same functions as their counterparts that use a promise. For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). - -Table 1 Common APIs for session access end development - -| API | Description | -|----------------------------------------------------------------------------------|-------------| -| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback\): void | Creates a session.| -| setAVMetadata(data: AVMetadata, callback: AsyncCallback\): void | Sets session metadata. | -| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback\): void | Sets the playback state information. | -| setLaunchAbility(ability: WantAgent, callback: AsyncCallback\): void | Sets the launcher ability.| -| getController(callback: AsyncCallback\): void | Obtains the controller of this session.| -| getOutputDevice(callback: AsyncCallback\): void | Obtains the output device information. | -| activate(callback: AsyncCallback\): void | Activates this session. | -| destroy(callback: AsyncCallback\): void | Destroys this session. | - -### How to Develop -1. Import the modules. - -```js -import avSession from '@ohos.multimedia.avsession'; -import wantAgent from '@ohos.app.ability.wantAgent'; -import featureAbility from '@ohos.ability.featureAbility'; -``` - -2. Create and activate a session. -```js -// Define global variables. -let mediaFavorite = false; -let currentSession = null; -let context = featureAbility.getContext(); - -// Create an audio session. -avSession.createAVSession(context, "AudioAppSample", 'audio').then((session) => { - currentSession = session; - currentSession.activate(); // Activate the session. -}).catch((err) => { - console.info(`createAVSession : ERROR : ${err.message}`); -}); -``` - -3. Set the session information, including: -- Session metadata. In addition to the current media asset ID (mandatory), you can set the title, album, author, duration, and previous/next media asset ID. For details about the session metadata, see **AVMetadata** in the API document. -- Launcher ability, which is implemented by calling an API of [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). Generally, **WantAgent** is used to encapsulate want information. -- Playback state information. -```js -// Set the session metadata. -let metadata = { - assetId: "121278", - title: "lose yourself", - artist: "Eminem", - author: "ST", - album: "Slim shady", - writer: "ST", - composer: "ST", - duration: 2222, - mediaImage: "https://www.example.com/example.jpg", // Set it based on your project requirements. - subtitle: "8 Mile", - description: "Rap", - lyric: "https://www.example.com/example.lrc", // Set it based on your project requirements. - previousAssetId: "121277", - nextAssetId: "121279", -}; -currentSession.setAVMetadata(metadata).then(() => { - console.info('setAVMetadata successfully'); -}).catch((err) => { - console.info(`setAVMetadata : ERROR : ${err.message}`); -}); -``` - -```js -// Set the launcher ability. -let wantAgentInfo = { - wants: [ - { - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.EntryAbility", - } - ], - operationType: wantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -wantAgent.getWantAgent(wantAgentInfo).then((agent) => { - currentSession.setLaunchAbility(agent).then(() => { - console.info('setLaunchAbility successfully'); - }).catch((err) => { - console.info(`setLaunchAbility : ERROR : ${err.message}`); - }); -}); -``` - -```js -// Set the playback state information. -let PlaybackState = { - state: avSession.PlaybackState.PLAYBACK_STATE_STOP, - speed: 1.0, - position:{elapsedTime: 0, updateTime: (new Date()).getTime()}, - bufferedTime: 1000, - loopMode: avSession.LoopMode.LOOP_MODE_SEQUENCE, - isFavorite: false, -}; -currentSession.setAVPlaybackState(PlaybackState).then(() => { - console.info('setAVPlaybackState successfully'); -}).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); -}); -``` - -```js -// Obtain the controller of this session. -currentSession.getController().then((selfController) => { - console.info('getController successfully'); -}).catch((err) => { - console.info(`getController : ERROR : ${err.message}`); -}); -``` - -```js -// Obtain the output device information. -currentSession.getOutputDevice().then((outputInfo) => { - console.info(`getOutputDevice successfully, deviceName : ${outputInfo.deviceName}`); -}).catch((err) => { - console.info(`getOutputDevice : ERROR : ${err.message}`); -}); -``` - -4. Subscribe to control command events. -```js -// Subscribe to the 'play' command event. -currentSession.on('play', () => { - console.log ("Call AudioPlayer.play."); - // Set the playback state information. - currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - - -// Subscribe to the 'pause' command event. -currentSession.on('pause', () => { - console.log ("Call AudioPlayer.pause."); - // Set the playback state information. - currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PAUSE}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'stop' command event. -currentSession.on('stop', () => { - console.log ("Call AudioPlayer.stop."); - // Set the playback state information. - currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_STOP}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'playNext' command event. -currentSession.on('playNext', () => { - // When the media file is not ready, download and cache the media file, and set the 'PREPARE' state. - currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PREPARE}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); - // The media file is obtained. - currentSession.setAVMetadata({assetId: '58970105', title: 'See you tomorrow'}).then(() => { - console.info('setAVMetadata successfully'); - }).catch((err) => { - console.info(`setAVMetadata : ERROR : ${err.message}`); - }); - console.log ("Call AudioPlayer.play."); - // Set the playback state information. - let time = (new Date()).getTime(); - currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'fastForward' command event. -currentSession.on('fastForward', () => { - console.log("Call AudioPlayer for fast forwarding."); - // Set the playback state information. - currentSession.setAVPlaybackState({speed: 2.0}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'seek' command event. -currentSession.on('seek', (time) => { - console.log("Call AudioPlayer.seek."); - // Set the playback state information. - currentSession.setAVPlaybackState({position: {elapsedTime: time, updateTime: (new Data()).getTime()}}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'setSpeed' command event. -currentSession.on('setSpeed', (speed) => { - console.log(`Call AudioPlayer to set the speed to ${speed}`); - // Set the playback state information. - currentSession.setAVPlaybackState({speed: speed}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'setLoopMode' command event. -currentSession.on('setLoopMode', (mode) => { - console.log(`The application switches to the loop mode ${mode}`); - // Set the playback state information. - currentSession.setAVPlaybackState({loopMode: mode}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); -}); - -// Subscribe to the 'toggleFavorite' command event. -currentSession.on('toggleFavorite', (assetId) => { - console.log(`The application favorites ${assetId}.`); - // Perform the switch based on the last status. - let favorite = mediaFavorite == false ? true : false; - currentSession.setAVPlaybackState({isFavorite: favorite}).then(() => { - console.info('setAVPlaybackState successfully'); - }).catch((err) => { - console.info(`setAVPlaybackState : ERROR : ${err.message}`); - }); - mediaFavorite = favorite; -}); - -// Subscribe to the key event. -currentSession.on('handleKeyEvent', (event) => { - console.log(`User presses the key ${event.keyCode}`); -}); - -// Subscribe to output device changes. -currentSession.on('outputDeviceChange', (device) => { - console.log(`Output device changed to ${device.deviceName}`); -}); -``` - -5. Release resources. -```js -// Unsubscribe from the events. -currentSession.off('play'); -currentSession.off('pause'); -currentSession.off('stop'); -currentSession.off('playNext'); -currentSession.off('playPrevious'); -currentSession.off('fastForward'); -currentSession.off('rewind'); -currentSession.off('seek'); -currentSession.off('setSpeed'); -currentSession.off('setLoopMode'); -currentSession.off('toggleFavorite'); -currentSession.off('handleKeyEvent'); -currentSession.off('outputDeviceChange'); - -// Deactivate the session and destroy the object. -currentSession.deactivate().then(() => { - currentSession.destroy(); -}); -``` - -### Verification -Touch the play, pause, or next button on the media application. Check whether the media playback state changes accordingly. - -### FAQs - -1. Session Service Exception -- Symptoms - - The session service is abnormal, and the application cannot obtain a response from the session service. For example, the session service is not running or the communication with the session service fails. The error message "Session service exception" is displayed. - -- Possible causes - - The session service is killed during session restart. - -- Solution - - (1) The system retries the operation automatically. If the error persists for 3 seconds or more, stop the operation on the session or controller. - - (2) Destroy the current session or session controller and re-create it. If the re-creation fails, stop the operation on the session. - -2. Session Does Not Exist -- Symptoms - - Parameters are set for or commands are sent to the session that does not exist. The error message "The session does not exist" is displayed. - -- Possible causes - - The session has been destroyed, and no session record exists on the server. - -- Solution - - (1) If the error occurs on the application, re-create the session. If the error occurs on Media Controller, stop sending query or control commands to the session. - - (2) If the error occurs on the session service, query the current session record and pass the correct session ID when creating the controller. - -3. Session Not Activated -- Symptoms - - A control command or event is sent to the session when it is not activated. The error message "The session not active" is displayed. - -- Possible causes - - The session is in the inactive state. - -- Solution - - Stop sending the command or event. Subscribe to the session activation status, and resume the sending when the session is activated. - -## Development for the Session Control End (Media Controller) - -### Basic Concepts -- Remote projection: A local media session is projected to a remote device. The local controller sends commands to control media playback on the remote device. -- Sending key events: The controller controls media playback by sending key events. -- Sending control commands: The controller controls media playback by sending control commands. -- Sending system key events: A system application calls APIs to send system key events to control media playback. -- Sending system control commands: A system application calls APIs to send system control commands to control media playback. - -### Available APIs - -The table below lists the APIs available for the development of the session control end. The APIs use either a callback or promise to return the result. The APIs listed below use a callback, which provide the same functions as their counterparts that use a promise. For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). - -Table 2 Common APIs for session control end development - -| API | Description | -| ------------------------------------------------------------------------------------------------ | ----------------- | -| getAllSessionDescriptors(callback: AsyncCallback\>>): void | Obtains the descriptors of all sessions. | -| createController(sessionId: string, callback: AsyncCallback\): void | Creates a controller. | -| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback\): void | Sends a key event. | -| getLaunchAbility(callback: AsyncCallback\): void | Obtains the launcher ability. | -| sendControlCommand(command: AVControlCommand, callback: AsyncCallback\): void | Sends a control command. | -| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback\): void | Send a system key event. | -| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback\): void | Sends a system control command. | -| castAudio(session: SessionToken \| 'all', audioDevices: Array\, callback: AsyncCallback\): void | Casts the media session to a remote device.| - -### How to Develop -1. Import the modules. -```js -import avSession from '@ohos.multimedia.avsession'; -import {Action, KeyEvent} from '@ohos.multimodalInput.KeyEvent'; -import wantAgent from '@ohos.app.ability.wantAgent'; -import audio from '@ohos.multimedia.audio'; -``` - -2. Obtain the session descriptors and create a controller. -```js -// Define global variables. -let g_controller = new Array(); -let g_centerSupportCmd:Set = new Set(['play', 'pause', 'playNext', 'playPrevious', 'fastForward', 'rewind', 'seek','setSpeed', 'setLoopMode', 'toggleFavorite']); -let g_validCmd:Set; - -// Obtain the session descriptors and create a controller. -avSession.getAllSessionDescriptors().then((descriptors) => { - descriptors.forEach((descriptor) => { - avSession.createController(descriptor.sessionId).then((controller) => { - g_controller.push(controller); - }).catch((err) => { - console.error('createController error'); - }); - }); -}).catch((err) => { - console.error('getAllSessionDescriptors error'); -}); - -// Subscribe to the 'sessionCreate' event and create a controller. -avSession.on('sessionCreate', (session) => { - // After a session is added, you must create a controller. - avSession.createController(session.sessionId).then((controller) => { - g_controller.push(controller); - }).catch((err) => { - console.info(`createController : ERROR : ${err.message}`); - }); -}); -``` - -3. Subscribe to the session state and service changes. -```js -// Subscribe to the 'activeStateChange' event. -controller.on('activeStateChange', (isActive) => { - if (isActive) { - console.log ("The widget corresponding to the controller is highlighted."); - } else { - console.log("The widget corresponding to the controller is invalid."); - } -}); - -// Subscribe to the 'sessionDestroy' event to enable Media Controller to get notified when the session dies. -controller.on('sessionDestroy', () => { - console.info('on sessionDestroy : SUCCESS '); - controller.destroy().then(() => { - console.info('destroy : SUCCESS '); - }).catch((err) => { - console.info(`destroy : ERROR :${err.message}`); - }); -}); - -// Subscribe to the 'sessionDestroy' event to enable the application to get notified when the session dies. -avSession.on('sessionDestroy', (session) => { - let index = g_controller.findIndex((controller) => { - return controller.sessionId == session.sessionId; - }); - if (index != 0) { - g_controller[index].destroy(); - g_controller.splice(index, 1); - } -}); - -// Subscribe to the 'topSessionChange' event. -avSession.on('topSessionChange', (session) => { - let index = g_controller.findIndex((controller) => { - return controller.sessionId == session.sessionId; - }); - // Place the session on the top. - if (index != 0) { - g_controller.sort((a, b) => { - return a.sessionId == session.sessionId ? -1 : 0; - }); - } -}); - -// Subscribe to the 'sessionServiceDie' event. -avSession.on('sessionServiceDie', () => { - // The server is abnormal, and the application clears resources. - console.log("Server exception"); -}) -``` - -4. Subscribe to media session information changes. -```js -// Subscribe to metadata changes. -let metaFilter = ['assetId', 'title', 'description']; -controller.on('metadataChange', metaFilter, (metadata) => { - console.info(`on metadataChange assetId : ${metadata.assetId}`); -}); - -// Subscribe to playback state changes. -let playbackFilter = ['state', 'speed', 'loopMode']; -controller.on('playbackStateChange', playbackFilter, (playbackState) => { - console.info(`on playbackStateChange state : ${playbackState.state}`); -}); - -// Subscribe to supported command changes. -controller.on('validCommandChange', (cmds) => { - console.info(`validCommandChange : SUCCESS : size : ${cmds.size}`); - console.info(`validCommandChange : SUCCESS : cmds : ${cmds.values()}`); - g_validCmd.clear(); - for (let c of g_centerSupportCmd) { - if (cmds.has(c)) { - g_validCmd.add(c); - } - } -}); - -// Subscribe to output device changes. -controller.on('outputDeviceChange', (device) => { - console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`); -}); -``` - -5. Control the session behavior. -```js -// When the user touches the play button, the control command 'play' is sent to the session. -if (g_validCmd.has('play')) { - controller.sendControlCommand({command:'play'}).then(() => { - console.info('sendControlCommand successfully'); - }).catch((err) => { - console.info(`sendControlCommand : ERROR : ${err.message}`); - }); -} - -// When the user selects the single loop mode, the corresponding control command is sent to the session. -if (g_validCmd.has('setLoopMode')) { - controller.sendControlCommand({command: 'setLoopMode', parameter: avSession.LoopMode.LOOP_MODE_SINGLE}).then(() => { - console.info('sendControlCommand successfully'); - }).catch((err) => { - console.info(`sendControlCommand : ERROR : ${err.message}`); - }); -} - -// Send a key event. -let keyItem = {code: 0x49, pressedTime: 123456789, deviceId: 0}; -let event = {action: 2, key: keyItem, keys: [keyItem]}; -controller.sendAVKeyEvent(event).then(() => { - console.info('sendAVKeyEvent Successfully'); -}).catch((err) => { - console.info(`sendAVKeyEvent : ERROR : ${err.message}`); -}); - -// The user touches the blank area on the widget to start the application. -controller.getLaunchAbility().then((want) => { - console.log("Starting the application in the foreground"); -}).catch((err) => { - console.info(`getLaunchAbility : ERROR : ${err.message}`); -}); - -// Send the system key event. -let keyItem = {code: 0x49, pressedTime: 123456789, deviceId: 0}; -let event = {action: 2, key: keyItem, keys: [keyItem]}; -avSession.sendSystemAVKeyEvent(event).then(() => { - console.info('sendSystemAVKeyEvent Successfully'); -}).catch((err) => { - console.info(`sendSystemAVKeyEvent : ERROR : ${err.message}`); -}); - -// Send a system control command to the top session. -let avcommand = {command: 'toggleFavorite', parameter: "false"}; -avSession.sendSystemControlCommand(avcommand).then(() => { - console.info('sendSystemControlCommand successfully'); -}).catch((err) => { - console.info(`sendSystemControlCommand : ERROR : ${err.message}`); -}); - -// Cast the session to another device. -let audioManager = audio.getAudioManager(); -let audioDevices; -await audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - audioDevices = data; - console.info('Promise returned to indicate that the device list is obtained.'); -}).catch((err) => { - console.info(`getDevices : ERROR : ${err.message}`); -}); - -avSession.castAudio('all', audioDevices).then(() => { - console.info('createController : SUCCESS'); -}).catch((err) => { - console.info(`createController : ERROR : ${err.message}`); -}); -``` - -6. Release resources. -```js -// Unsubscribe from the events. - controller.off('metadataChange'); - controller.off('playbackStateChange'); - controller.off('sessionDestroy'); - controller.off('activeStateChange'); - controller.off('validCommandChange'); - controller.off('outputDeviceChange'); - - // Destroy the controller. - controller.destroy().then(() => { - console.info('destroy : SUCCESS '); - }).catch((err) => { - console.info(`destroy : ERROR : ${err.message}`); - }); -``` - -### Verification -When you touch the play, pause, or next button in Media Controller, the playback state of the application changes accordingly. - -### FAQs -1. Controller Does Not Exist -- Symptoms - - A control command or an event is sent to the controller that does not exist. The error message "The session controller does not exist" is displayed. - -- Possible causes - - The controller has been destroyed. - -- Solution - - Query the session record and create the corresponding controller. - -2. Remote Session Connection Failure -- Symptoms - - The communication between the local session and the remote session fails. The error information "The remote session connection failed" is displayed. - -- Possible causes - - The communication between devices is interrupted. - -- Solution - - Stop sending control commands to the session. Subscribe to output device changes, and resume the sending when the output device is changed. - -3. Invalid Session Command -- Symptoms - - The control command or event sent to the session is not supported. The error message "Invalid session command" is displayed. - -- Possible causes - - The session does not support this command. - -- Solution - - Stop sending the command or event. Query the commands supported by the session, and send a command supported. - -4. Too Many Commands or Events -- Symptoms - - The session client sends too many messages or commands to the server in a period of time, causing the server to be overloaded. The error message "Command or event overload" is displayed. - -- Possible causes - - The server is overloaded with messages or events. - -- Solution - - Control the frequency of sending commands or events. diff --git a/en/application-dev/media/avsession-overview.md b/en/application-dev/media/avsession-overview.md index c46211765644330ac26c1154f181904c2db4c3d0..766e642eebc2ba861bf6aceca5f9ea702f99d74f 100644 --- a/en/application-dev/media/avsession-overview.md +++ b/en/application-dev/media/avsession-overview.md @@ -1,56 +1,50 @@ # AVSession Overview -> **NOTE** -> -> All APIs of the **AVSession** module are system APIs and can be called only by system applications. +The Audio and Video Session (AVSession) service is used to manage the playback behavior of all audio and video applications in the system in a unified manner. For example, it allows only one audio application in the playing state. -## Overview +Audio and video applications access the AVSession service and send application data (for example, a song that is being played and playback state) to it. Through a controller, the user can choose another application or device to continue the playback. If an application does not access the AVSession service, its playback will be forcibly interrupted when it switches to the background. - AVSession, short for audio and video session, is also known as media session. - - Application developers can use the APIs provided by the **AVSession** module to connect their audio and video applications to the system's Media Controller. - - System developers can use the APIs provided by the **AVSession** module to display media information of system audio and video applications and carry out unified playback control. +To implement background playback, you must request a continuous task to prevent the task from being suspended. For details, see [Continuous Task Development](../task-management/continuous-task-dev-guide.md). - You can implement the following features through the **AVSession** module: +## Basic Concepts - 1. Unified playback control entry +Be familiar with the following basic concepts before development: - If there are multiple audio and video applications on the device, users need to switch to and access different applications to control media playback. With AVSession, a unified playback control entry of the system (such as Media Controller) is used for playback control of these audio and video applications. No more switching is required. +- AVSession - 2. Better background application management + For AVSession, one end is the audio and video applications under control, and the other end is a controller (for example, Media Controller or AI Voice). AVSession provides a channel for information exchange between the application and controller. - When an application running in the background automatically starts audio playback, it is difficult for users to locate the application. With AVSession, users can quickly find the application that plays the audio clip in Media Controller. +- Provider -## Basic Concepts + An audio and video application that accesses the AVSession service. After accessing AVSession, the audio and video application must provide the media information, for example, the name of the item to play and the playback state, to AVSession. Through AVSession, the application also receives control commands from the controller and responds accordingly. -- AVSession +- Controller + + A system application that accesses AVSession to provide global control on audio and video playback behavior. Typical controllers on OpenHarmony devices are Media Controller and AI Voice. The following sections use Media Controller as an example of the controller. After accessing AVSession, the controller obtains the latest media information and sends control commands to the audio and video applications through AVSession. - A channel used for information exchange between applications and Media Controller. For AVSession, one end is the media application under control, and the other end is Media Controller. Through AVSession, an application can transfer the media playback information to Media Controller and receive control commands from Media Controller. - - AVSessionController - Object that controls media sessions and thereby controls the playback behavior of applications. Through AVSessionController, Media Controller can control the playback behavior of applications, obtain playback information, and send control commands. It can also monitor the playback state of applications to ensure synchronization of the media session information. + An object that controls the playback behavior of the provider. It obtains the playback information of the audio and video application and listens for the application playback changes to synchronize the AVSession information between the application and controller. The controller is the holder of an **AVSessionController** object. + +- AVSessionManager + + An object that provides the capability of managing sessions. It can create an **AVSession** object, create an **AVSessionController** object, send control commands, and listen for session state changes. + -- Media Controller - - Holder of AVSessionController. Through AVSessionController, Media Controller sends commands to control media playback of applications. +## AVSession Interaction Process -## Implementation Principle +AVSessions are classified into local AVSessions and distributed AVSessions. -The **AVSession** module provides two classes: **AVSession** and **AVSessionController**. +![AVSession Interaction Process](figures/avsession-interaction-process.png) -**Figure 1** AVSession interaction +- Local AVSession -![en-us_image_avsession](figures/en-us_image_avsession.png) + Local AVSession establishes a connection between the provider and controller in the local device, so as to implement unified playback control and media information display for audio and video applications in the system. -- Interaction between the application and Media Controller: First, an audio application creates an **AVSession** object and sets session information, including media metadata, launcher ability, and playback state information. Then, Media Controller creates an **AVSessionController** object to obtain session-related information and send the 'play' command to the audio application. Finally, the audio application responds to the command and updates the playback state. +- Distributed AVSession -- Distributed projection: When a connected device creates a local session, Media Controller or the audio application can select another device to be projected based on the device list, synchronize the local session to the remote device, and generate a controllable remote session. The remote session is controlled by sending control commands to the remote device's application through its AVSessionController. + Distributed AVSession establishes a connection between the provider and controller in the cross-device scenario, so as to implement cross-device playback control and media information display for audio and video applications in the system. For example, you can project the content played on device A to device B and perform playback control on device B. ## Constraints -- The playback information displayed in Media Controller is the media information proactively written by the media application to AVSession. -- Media Controller controls the playback of a media application based on the responses of the media application to control commands. -- AVSession can transmit media playback information and control commands. It does not display information or execute control commands. -- Do not develop Media Controller for common applications. For common audio and video applications running on OpenHarmony, the default control end is Media Controller, which is a system application. You do not need to carry out additional development for Media Controller. -- If you want to develop your own system running OpenHarmony, you can develop your own Media Controller. -- For better background management of audio and video applications, the **AVSession** module enforces background control for applications. Only applications that have accessed AVSession can play audio in the background. Otherwise, the system forcibly pauses the playback when an application switches to the background. +The AVSession service manages the playback behavior of all audio and video applications in the system. To continue the playback after switching to the background, the audio and video applications must access the AVSession service. diff --git a/en/application-dev/media/camera-device-input.md b/en/application-dev/media/camera-device-input.md new file mode 100644 index 0000000000000000000000000000000000000000..3702e16760c002010c50da236d4ef9c2af079e5e --- /dev/null +++ b/en/application-dev/media/camera-device-input.md @@ -0,0 +1,82 @@ +# Device Input Management + +Before developing a camera application, you must create an independent camera object. The application invokes and controls the camera object to perform basic operations such as preview, photographing, and video recording. + +## How to Develop + +Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. + +1. Import the camera module, which provides camera-related attributes and methods. + + ```ts + import camera from '@ohos.multimedia.camera'; + ``` + +2. Call **getCameraManager()** to obtain a **CameraManager** object. + + ```ts + let cameraManager; + let context: any = getContext(this); + cameraManager = camera.getCameraManager(context) + ``` + + > **NOTE** + > + > If obtaining the object fails, the camera hardware may be occupied or unusable. If it is occupied, wait until it is released. + +3. Call **getSupportedCameras()** in the **CameraManager** class to obtain the list of cameras supported by the current device. The list stores the IDs of all cameras supported. If the list is not empty, each ID in the list can be used to create an independent camera object. Otherwise, no camera is available for the current device and subsequent operations cannot be performed. + + ```ts + let cameraArray = cameraManager.getSupportedCameras(); + if (cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error"); + return; + } + + for (let index = 0; index < cameraArray.length; index++) { + console.info('cameraId : ' + cameraArray[index].cameraId); // Obtain the camera ID. + console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // Obtain the camera position. + console.info('cameraType : ' + cameraArray[index].cameraType); // Obtain the camera type. + console.info('connectionType : ' + cameraArray[index].connectionType); // Obtain the camera connection type. + } + ``` + +4. Call **getSupportedOutputCapability()** to obtain all output streams supported by the current device, such as preview streams and photo streams. The output stream is in each **profile** field under **CameraOutputCapability**. + + ```ts + // Create a camera input stream. + let cameraInput; + try { + cameraInput = cameraManager.createCameraInput(cameraArray[0]); + } catch (error) { + console.error('Failed to createCameraInput errorCode = ' + error.code); + } + // Listen for CameraInput errors. + let cameraDevice = cameraArray[0]; + cameraInput.on('error', cameraDevice, (error) => { + console.info(`Camera input error code: ${error.code}`); + }) + // Open the camera. + await cameraInput.open(); + // Obtain the output stream capabilities supported by the camera. + let cameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); + if (!cameraOutputCapability) { + console.error("cameraManager.getSupportedOutputCapability error"); + return; + } + console.info("outputCapability: " + JSON.stringify(cameraOutputCapability)); + ``` + + +## Status Listening + +During camera application development, you can listen for the camera status, including the appearance of a new camera, removal of a camera, and availability of a camera. The camera ID and camera status are used in the callback function. When a new camera appears, the new camera can be added to the supported camera list. + +Register the 'cameraStatus' event and return the listening result through a callback, which carries the **CameraStatusInfo** parameter. For details about the parameter, see [CameraStatusInfo](../reference/apis/js-apis-camera.md#camerastatusinfo). + +```ts +cameraManager.on('cameraStatus', (cameraStatusInfo) => { + console.info(`camera: ${cameraStatusInfo.camera.cameraId}`); + console.info(`status: ${cameraStatusInfo.status}`); +}) +``` diff --git a/en/application-dev/media/camera-metadata.md b/en/application-dev/media/camera-metadata.md new file mode 100644 index 0000000000000000000000000000000000000000..8fdeff1df08f624374f2a2a5cee32b99b2c41e03 --- /dev/null +++ b/en/application-dev/media/camera-metadata.md @@ -0,0 +1,66 @@ +# Camera Metadata + +Metadata is the description and context of image information returned by the camera application. It provides detailed data for the image information, for example, coordinates of a viewfinder frame for identifying a portrait in a photo or a video. + +Metadata uses a tag (key) to find the corresponding data during the transfer of parameters and configurations, reducing memory copy operations. + +## How to Develop + +Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. + +1. Obtain the metadata types supported by the current device from **supportedMetadataObjectTypes** in **CameraOutputCapability**, and then use **createMetadataOutput()** to create a metadata output stream. + + ```ts + let metadataObjectTypes = cameraOutputCapability.supportedMetadataObjectTypes; + let metadataOutput; + try { + metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes); + } catch (error) { + // If the operation fails, error.code is returned and processed. + console.info(error.code); + } + ``` + +2. Call **start()** to start outputting metadata. If the call fails, an error code is returned. For details, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + metadataOutput.start().then(() => { + console.info('Callback returned with metadataOutput started.'); + }).catch((err) => { + console.info('Failed to metadataOutput start '+ err.code); + }); + ``` + +3. Call **stop()** to stop outputting metadata. If the call fails, an error code is returned. For details, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + metadataOutput.stop().then(() => { + console.info('Callback returned with metadataOutput stopped.'); + }).catch((err) => { + console.info('Failed to metadataOutput stop '+ err.code); + }); + ``` + +## Status Listening + +During camera application development, you can listen for the status of metadata objects and output stream. + +- Register the 'metadataObjectsAvailable' event to listen for metadata objects that are available. When a valid metadata object is detected, the callback function returns the metadata. This event can be registered when a **MetadataOutput** object is created. + + ```ts + metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => { + console.info(`metadata output metadataObjectsAvailable`); + }) + ``` + + > **NOTE** + > + > Currently, only **FACE_DETECTION** is available for the metadata type. The metadata object is the rectangle of the recognized face, including the x-axis coordinate and y-axis coordinate of the upper left corner of the rectangle as well as the width and height of the rectangle. + +- Register the 'error' event to listen for metadata stream errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + metadataOutput.on('error', (metadataOutputError) => { + console.info(`Metadata output error code: ${metadataOutputError.code}`); + }) + ``` diff --git a/en/application-dev/media/camera-overview.md b/en/application-dev/media/camera-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..03445ee6979c28fb4084a2f3c8186d77f14e5b89 --- /dev/null +++ b/en/application-dev/media/camera-overview.md @@ -0,0 +1,27 @@ +# Camera Overview + +With the APIs provided by the camera module of the multimedia subsystem, you can develop a camera application. The application accesses and operates the camera hardware to implement basic operations, such as preview, photographing, and video recording. It can also perform more operations, for example, controlling the flash and exposure time, and focusing or adjusting the focus. + +## Development Model + +The camera application invokes the camera hardware to collect and process image and video data, and output images and videos. It can be used when there are multiple lenses (such as wide-angle lens, long-focus lens, and ToF lens) in various service scenarios (such as different requirements on the resolution, format, and effect). + +The figure below illustrates the working process of the camera module. The working process can be summarized into three parts: input device management, session management, and output management. + +- During input device management, the camera application invokes the camera hardware to collect data and uses the data as an input stream. + +- During session management, you can configure an input stream to determine the camera to be used. You can also set parameters, such as the flash, exposure time, focus, and focus adjustment, to implement different shooting effects in various service scenarios. The application can switch between sessions to meet service requirements in different scenarios. + +- During output management, you can configure an output stream, which can be a preview stream, photo stream, or video stream. + +**Figure 1** Camera working process +![Camera Workflow](figures/camera-workflow.png) + +For better application development, you are also advised understanding the camera development model. + +**Figure 2** Camera development model +![Camera Development Model](figures/camera-development-model.png) + +The camera application controls the camera hardware to implement basic operations such as image display (preview), photo saving (photographing), and video recording. During the implementation, the camera service controls the camera hardware to collect and output data, and transmits the data to a specific module for processing through a BufferQueue at the bottom camera device hardware interface (HDI) layer. You can ignore the BufferQueue during application development. It is used to send the data processed by the bottom layer to the upper layer for image display. + +For example, in a video recording scenario, the recording service creates a video surface and provides it to the camera service for data transmission. The camera service controls the camera device to collect video data and generate a video stream. After processing the collected data at the HDI layer, the camera service transmits the video stream to the recording service through the surface. The recording service processes the video stream and saves it as a video file. Now video recording is complete. diff --git a/en/application-dev/media/camera-preparation.md b/en/application-dev/media/camera-preparation.md new file mode 100644 index 0000000000000000000000000000000000000000..eb504af9a69f65473f27de59a45a17891357be7f --- /dev/null +++ b/en/application-dev/media/camera-preparation.md @@ -0,0 +1,25 @@ +# Camera Development Preparations + +The main process of camera application development includes development preparations, device input management, session management, preview, photographing, and video recording. + +Before developing a camera application, you must request camera-related permissions (as described in the table below) to ensure that the application has the permission to access the camera hardware and other services. Before requesting the permission, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met. + + +| Permission| Description| Authorization Mode| +| -------- | -------- | -------- | +| ohos.permission.CAMERA | Allows an application to use the camera to take photos and record videos.| user_grant | +| ohos.permission.MICROPHONE | Allows an application to access the microphone.
This permission is required only if the application is used to record audio.| user_grant | +| ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage. This permission is optional.| user_grant | +| ohos.permission.READ_MEDIA | Allows an application to read media files from the user's external storage. This permission is optional.| user_grant | +| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file. This permission is optional.| user_grant | + + +After configuring the permissions in the **module.json5** file, the application must call [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the required permissions are granted. If not, request the permissions from the user by displaying a dialog box. + + +For details about how to request and verify the permissions, see [Permission Application Guide](../security/accesstoken-guidelines.md). + + +> **NOTE** +> +> Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**. diff --git a/en/application-dev/media/camera-preview.md b/en/application-dev/media/camera-preview.md new file mode 100644 index 0000000000000000000000000000000000000000..e65f5dac8c96737b81b20703ce6ffa6fe7daa54b --- /dev/null +++ b/en/application-dev/media/camera-preview.md @@ -0,0 +1,87 @@ +# Camera Preview + +Preview is the image you see after you start the camera application but before you take photos or record videos. + +## How to Develop + +Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. + +1. Create a surface. + + The XComponent, the capabilities of which are provided by the UI, offers the surface for preview streams. For details, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md). + + ```ts + // Create an XComponentController object. + mXComponentController: XComponentController = new XComponentController; + build() { + Flex() { + // Create an XComponent. + XComponent({ + id: '', + type: 'surface', + libraryname: '', + controller: this.mXComponentController + }) + .onLoad(() => { + // Set the surface width and height (1920 x 1080). For details about how to set the preview size, see the preview resolutions supported by the current device, which are obtained from previewProfilesArray. + this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); + // Obtain the surface ID. + globalThis.surfaceId = this.mXComponentController.getXComponentSurfaceId(); + }) + .width('1920px') + .height('1080px') + } + } + ``` + +2. Call **previewProfiles()** in the **CameraOutputCapability** class to obtain the preview capabilities, in the format of an **previewProfilesArray** array, supported by the current device. Then call **createPreviewOutput()** to create a preview output stream, with the first parameter set to the first item in the **previewProfilesArray** array and the second parameter set to the surface ID obtained in step 1. + + ```ts + let previewProfilesArray = cameraOutputCapability.previewProfiles; + let previewOutput; + try { + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); + } + catch (error) { + console.error("Failed to create the PreviewOutput instance." + error); + } + ``` + +3. Call **start()** to start outputting the preview stream. If the call fails, an error code is returned. For details, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + previewOutput.start().then(() => { + console.info('Callback returned with previewOutput started.'); + }).catch((err) => { + console.info('Failed to previewOutput start '+ err.code); + }); + ``` + + +## Status Listening + +During camera application development, you can listen for the preview output stream status, including preview stream start, preview stream end, and preview stream output errors. + +- Register the 'frameStart' event to listen for preview start events This event can be registered when a **PreviewOutput** object is created and is triggered when the bottom layer starts exposure for the first time. The preview stream is started as long as a result is returned. + + ```ts + previewOutput.on('frameStart', () => { + console.info('Preview frame started'); + }) + ``` + +- Register the 'frameEnd' event to listen for preview end events. This event can be registered when a **PreviewOutput** object is created and is triggered when the last frame of preview ends. The preview stream ends as long as a result is returned. + + ```ts + previewOutput.on('frameEnd', () => { + console.info('Preview frame ended'); + }) + ``` + +- Register the 'error' event to listen for preview output errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + previewOutput.on('error', (previewOutputError) => { + console.info(`Preview output error code: ${previewOutputError.code}`); + }) + ``` diff --git a/en/application-dev/media/camera-recording-case.md b/en/application-dev/media/camera-recording-case.md new file mode 100644 index 0000000000000000000000000000000000000000..4d284f7e675fe0693240bbb678391147926652e7 --- /dev/null +++ b/en/application-dev/media/camera-recording-case.md @@ -0,0 +1,247 @@ +# Video Recording Sample + +## Development Process + +After obtaining the output stream capabilities supported by the camera, create a video stream. The development process is as follows: + +![Recording Development Process](figures/recording-development-process.png) + + +## Sample Code + +```ts +import camera from '@ohos.multimedia.camera' +import media from '@ohos.multimedia.media' + +// Create a CameraManager instance. +context: any = getContext(this) +let cameraManager = camera.getCameraManager(this.context) +if (!cameraManager) { + console.error("camera.getCameraManager error") + return; +} + +// Listen for camera status changes. +cameraManager.on('cameraStatus', (cameraStatusInfo) => { + console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.log(`status: ${cameraStatusInfo.status}`); +}) + +// Obtain the output stream capabilities supported by the camera. +let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]); +if (!cameraOutputCap) { + console.error("cameraManager.getSupportedOutputCapability error") + return; +} +console.log("outputCapability: " + JSON.stringify(cameraOutputCap)); + +let previewProfilesArray = cameraOutputCap.previewProfiles; +if (!previewProfilesArray) { + console.error("createOutput previewProfilesArray == null || undefined") +} + +let photoProfilesArray = cameraOutputCap.photoProfiles; +if (!photoProfilesArray) { + console.error("createOutput photoProfilesArray == null || undefined") +} + +let videoProfilesArray = cameraOutputCap.videoProfiles; +if (!videoProfilesArray) { + console.error("createOutput videoProfilesArray == null || undefined") +} + +let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; +if (!metadataObjectTypesArray) { + console.error("createOutput metadataObjectTypesArray == null || undefined") +} + +// Configure the parameters based on those supported by the hardware device. +let AVRecorderProfile = { + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 2000000, + 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 a file descriptor to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45--file:///data/media/01.mp4. + 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 } +} + +let avRecorder +media.createAVRecorder((error, recorder) => { + if (recorder != null) { + avRecorder = recorder; + console.log('createAVRecorder success'); + } else { + console.log(`createAVRecorder fail, error:${error}`); + } +}); + +avRecorder.prepare(AVRecorderConfig, (err) => { + if (err == null) { + console.log('prepare success'); + } else { + console.log('prepare failed and error is ' + err.message); + } +}) + +let videoSurfaceId = null; // The surfaceID is passed in to the camera API to create a VideoOutput instance. +avRecorder.getInputSurface((err, surfaceId) => { + if (err == null) { + console.log('getInputSurface success'); + videoSurfaceId = surfaceId; + } else { + console.log('getInputSurface failed and error is ' + err.message); + } +}); + +// Create a VideoOutput instance. +let videoOutput +try { + videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) +} catch (error) { + console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); +} + +// Listen for video output errors. +videoOutput.on('error', (error) => { + console.log(`Preview output error code: ${error.code}`); +}) + +// Create a session. +let captureSession +try { + captureSession = cameraManager.createCaptureSession() +} catch (error) { + console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); +} + +// Listen for session errors. +captureSession.on('error', (error) => { + console.log(`Capture session error code: ${error.code}`); +}) + +// Start configuration for the session. +try { + captureSession.beginConfig() +} catch (error) { + console.error('Failed to beginConfig. errorCode = ' + error.code); +} + +// Obtain the camera list. +let cameraArray = cameraManager.getSupportedCameras(); +if (cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error") + return; +} + +// Create a camera input stream. +let cameraInput +try { + cameraInput = cameraManager.createCameraInput(cameraArray[0]); +} catch (error) { + console.error('Failed to createCameraInput errorCode = ' + error.code); +} + +// Listen for camera input errors. +let cameraDevice = cameraArray[0]; +cameraInput.on('error', cameraDevice, (error) => { + console.log(`Camera input error code: ${error.code}`); +}) + +// Open the camera. +await cameraInput.open(); + +// Add the camera input stream to the session. +try { + captureSession.addInput(cameraInput) +} catch (error) { + console.error('Failed to addInput. errorCode = ' + error.code); +} + +// Create a preview output stream. For details about the surfaceId parameter, see the XComponent. The preview stream is the surface provided by the XComponent. +let previewOutput +try { + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) +} catch (error) { + console.error("Failed to create the PreviewOutput instance.") +} + +// Add the preview input stream to the session. +try { + captureSession.addOutput(previewOutput) +} catch (error) { + console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); +} + +// Add a video output stream to the session. +try { + captureSession.addOutput(videoOutput) +} catch (error) { + console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); +} + +// Commit the session configuration. +await captureSession.commitConfig() + +// Start the session. +await captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); +}) + +// Start the video output stream. +videoOutput.start(async (err) => { + if (err) { + console.error('Failed to start the video output ${err.message}'); + return; + } + console.log('Callback invoked to indicate the video output start success.'); +}); + +// Start video recording. +avRecorder.start().then(() => { + console.log('videoRecorder start success'); +}) + +// Stop the video output stream. +videoOutput.stop((err) => { + if (err) { + console.error('Failed to stop the video output ${err.message}'); + return; + } + console.log('Callback invoked to indicate the video output stop success.'); +}); + +// Stop video recording. +avRecorder.stop().then(() => { + console.log('stop success'); +}) + +// Stop the session. +captureSession.stop() + +// Release the camera input stream. +cameraInput.close() + +// Release the preview output stream. +previewOutput.release() + +// Release the video output stream. +videoOutput.release() + +// Release the session. +captureSession.release() + +// Set the session to null. +captureSession = null +``` diff --git a/en/application-dev/media/camera-recording.md b/en/application-dev/media/camera-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..421ff990bf45b372dd39cd3346e29b636f292762 --- /dev/null +++ b/en/application-dev/media/camera-recording.md @@ -0,0 +1,155 @@ +# Video Recording + +Video recording is also an important function of the camera application. Video recording is the process of cyclic capturing of frames. To smooth videos, you can follow step 4 in [Camera Photographing](camera-shooting.md) to set the resolution, flash, focal length, photo quality, and rotation angle. + +## How to Develop + +Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. + +1. Import the media module. The [APIs](../reference/apis/js-apis-media.md) provided by this module are used to obtain the surface ID and create a photo output stream. + + ```ts + import media from '@ohos.multimedia.media'; + ``` + +2. Create a surface. + + Call **createAVRecorder()** of the media module to create an **AVRecorder** instance, and call **getInputSurface()** of the instance to obtain the surface ID, which is associated with the view output stream to process the data output by the stream. + + ```ts + let AVRecorder; + media.createAVRecorder((error, recorder) => { + if (recorder != null) { + AVRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info(`createAVRecorder fail, error:${error}`); + } + }); + // For details about AVRecorderConfig, see the next section. + AVRecorder.prepare(AVRecorderConfig, (err) => { + if (err == null) { + console.log('prepare success'); + } else { + console.log('prepare failed and error is ' + err.message); + } + }) + + let videoSurfaceId = null; + AVRecorder.getInputSurface().then((surfaceId) => { + console.info('getInputSurface success'); + videoSurfaceId = surfaceId; + }).catch((err) => { + console.info('getInputSurface failed and catch error is ' + err.message); + }); + ``` + +3. Create a video output stream. + + Obtain the video output streams supported by the current device from **videoProfiles** in the **CameraOutputCapability** class. Then, define video recording parameters and use **createVideoOutput()** to create a video output stream. + + ```ts + let videoProfilesArray = cameraOutputCapability.videoProfiles; + if (!videoProfilesArray) { + console.error("createOutput videoProfilesArray == null || undefined"); + } + + // Define video recording parameters. + let videoConfig = { + videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile: { + fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. + videoBitrate: 100000, // Video bit rate. + videoCodec: media.CodecMimeType.VIDEO_MPEG4, // Video file encoding format. Both MPEG-4 and AVC are supported. + videoFrameWidth: 640, // Video frame width. + videoFrameHeight: 480, // Video frame height. + videoFrameRate: 30 // Video frame rate. + }, + url: 'fd://35', + rotation: 0 + } + // Create an AVRecorder instance. + let avRecorder; + media.createAVRecorder((error, recorder) => { + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.info(`createAVRecorder fail, error:${error}`); + } + }); + // Set video recording parameters. + avRecorder.prepare(videoConfig); + // Create a VideoOutput instance. + let videoOutput; + try { + videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId); + } catch (error) { + console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); + } + ``` + +4. Start video recording. + + Call **start()** of the **VideoOutput** instance to start the video output stream, and then call **start()** of the **AVRecorder** instance to start recording. + + ``` + videoOutput.start(async (err) => { + if (err) { + console.error('Failed to start the video output ${err.message}'); + return; + } + console.info('Callback invoked to indicate the video output start success.'); + }); + + avRecorder.start().then(() => { + console.info('avRecorder start success'); + } + ``` + +5. Stop video recording. + + Call **stop()** of the **AVRecorder** instance to stop recording, and then call **stop()** of the **VideoOutput** instance to stop the video output stream. + + ```ts + videoRecorder.stop().then(() => { + console.info('stop success'); + } + + videoOutput.stop((err) => { + if (err) { + console.error('Failed to stop the video output ${err.message}'); + return; + } + console.info('Callback invoked to indicate the video output stop success.'); + }); + ``` + + +## Status Listening + +During camera application development, you can listen for the status of the video output stream, including recording start, recording end, and recording stream output errors. + +- Register the 'frameStart' event to listen for recording start events. This event can be registered when a **VideoOutput** object is created and is triggered when the bottom layer starts exposure for recording for the first time. Video recording is started as long as a result is returned. + + ```ts + videoOutput.on('frameStart', () => { + console.info('Video frame started'); + }) + ``` + +- Register the 'frameEnd' event to listen for recording end events. This event can be registered when a **VideoOutput** object is created and is triggered when the last frame of recording ends. Video recording ends as long as a result is returned. + + ```ts + videoOutput.on('frameEnd', () => { + console.info('Video frame ended'); + }) + ``` + +- Register the 'error' event to listen for video output errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + videoOutput.on('error', (error) => { + console.info(`Video output error code: ${error.code}`); + }) + ``` diff --git a/en/application-dev/media/camera-session-management.md b/en/application-dev/media/camera-session-management.md new file mode 100644 index 0000000000000000000000000000000000000000..1d0d2fcfe20428d33d72569cbf2212b830ad42e2 --- /dev/null +++ b/en/application-dev/media/camera-session-management.md @@ -0,0 +1,86 @@ +# Camera Session Management + +Before using the camera application for preview, photographing, video recording, and metadata, you must create a camera session. + +You can implement the following functions in the session: + +- Configure the camera input and output streams. This is mandatory for photographing. + Configuring an input stream is to add a device input, which means that the user selects a camera for photographing. Configuring an output stream is to select a data output mode. For example, to implement photographing, you must configure both the preview stream and photo stream as the output stream. The data of the preview stream is displayed on the XComponent, and that of the photo stream is saved to the Gallery application through the **ImageReceiver** API. + +- Perform more operations on the camera hardware. For example, add the flash and adjust the focal length. For details about the supported configurations and APIs, see [Camera API Reference](../reference/apis/js-apis-camera.md). + +- Control session switching. The application can switch the camera mode by removing and adding output streams. For example, to switch from photographing to video recording, the application must remove the photo output stream and add the video output stream. + +After the session configuration is complete, the application must commit the configuration and start the session before using the camera functionalities. + +## How to Develop + +1. Call **createCaptureSession()** in the **CameraManager** class to create a session. + + ```ts + let captureSession; + try { + captureSession = cameraManager.createCaptureSession(); + } catch (error) { + console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); + } + ``` + +2. Call **beginConfig()** in the **CaptureSession** class to start configuration for the session. + + ```ts + try { + captureSession.beginConfig(); + } catch (error) { + console.error('Failed to beginConfig. errorCode = ' + error.code); + } + ``` + +3. Configure the session. You can call **addInput()** and **addOutput()** in the **CaptureSession** class to add the input and output streams to the session, respectively. The code snippet below uses adding the preview stream **previewOutput** and photo stream **photoOutput** as an example to implement the photographing and preview mode. + + After the configuration, call **commitConfig()** and **start()** in the **CaptureSession** class in sequence to commit the configuration and start the session. + + ```ts + try { + captureSession.addInput(cameraInput); + } catch (error) { + console.error('Failed to addInput. errorCode = ' + error.code); + } + try { + captureSession.addOutput(previewOutput); + } catch (error) { + console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); + } + try { + captureSession.addOutput(photoOutput); + } catch (error) { + console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); + } + await captureSession.commitConfig() ; + await captureSession.start().then(() => { + console.info('Promise returned to indicate the session start success.'); + }) + ``` + +4. Control the session. You can call **stop()** in the **CaptureSession** class to stop the session, and call **removeOutput()** and **addOutput()** in this class to switch to another session. The code snippet below uses removing the photo stream **photoOutput** and adding the video stream **videoOutput** as an example to complete the switching from photographing to recording. + + ```ts + await captureSession.stop(); + try { + captureSession.beginConfig(); + } catch (error) { + console.error('Failed to beginConfig. errorCode = ' + error.code); + } + // Remove the photo output stream from the session. + try { + captureSession.removeOutput(photoOutput); + } catch (error) { + console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code); + } + // Add the video output stream to the session. + try { + captureSession.addOutput(videoOutput); + } catch (error) { + console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); + } + ``` diff --git a/en/application-dev/media/camera-shooting-case.md b/en/application-dev/media/camera-shooting-case.md new file mode 100644 index 0000000000000000000000000000000000000000..da2588b10b844fd2a9432da909d1d387b8193d9f --- /dev/null +++ b/en/application-dev/media/camera-shooting-case.md @@ -0,0 +1,239 @@ +# Camera Photographing Sample + +## Development Process + +After obtaining the output stream capabilities supported by the camera, create a photo stream. The development process is as follows: + +![Photographing Development Process](figures/photographing-development-process.png) + +## Sample Code + +```ts +import camera from '@ohos.multimedia.camera' +import image from '@ohos.multimedia.image' +import media from '@ohos.multimedia.media' + +// Create a CameraManager instance. +context: any = getContext(this) +let cameraManager = camera.getCameraManager(this.context) +if (!cameraManager) { + console.error("camera.getCameraManager error") + return; +} +// Listen for camera status changes. +cameraManager.on('cameraStatus', (cameraStatusInfo) => { + console.info(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.info(`status: ${cameraStatusInfo.status}`); +}) + +// Obtain the camera list. +let cameraArray = cameraManager.getSupportedCameras(); +if (cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error") + return; +} + +for (let index = 0; index < cameraArray.length; index++) { + console.info('cameraId : ' + cameraArray[index].cameraId); // Obtain the camera ID. + console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // Obtain the camera position. + console.info('cameraType : ' + cameraArray[index].cameraType); // Obtain the camera type. + console.info('connectionType : ' + cameraArray[index].connectionType); // Obtain the camera connection type. +} + +// Create a camera input stream. +let cameraInput +try { + cameraInput = cameraManager.createCameraInput(cameraArray[0]); +} catch (error) { + console.error('Failed to createCameraInput errorCode = ' + error.code); +} + +// Listen for camera input errors. +let cameraDevice = cameraArray[0]; +cameraInput.on('error', cameraDevice, (error) => { + console.info(`Camera input error code: ${error.code}`); +}) + +// Open the camera. +await cameraInput.open(); + +// Obtain the output stream capabilities supported by the camera. +let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]); +if (!cameraOutputCap) { + console.error("cameraManager.getSupportedOutputCapability error") + return; +} +console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); + +let previewProfilesArray = cameraOutputCap.previewProfiles; +if (!previewProfilesArray) { + console.error("createOutput previewProfilesArray == null || undefined") +} + +let photoProfilesArray = cameraOutputCap.photoProfiles; +if (!photoProfilesArray) { + console.error("createOutput photoProfilesArray == null || undefined") +} + +// Create a preview output stream. For details about the surfaceId parameter, see the XComponent. The preview stream is the surface provided by the XComponent. +let previewOutput +try { + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) +} catch (error) { + console.error("Failed to create the PreviewOutput instance.") +} + +// Listen for preview output errors. +previewOutput.on('error', (error) => { + console.info(`Preview output error code: ${error.code}`); +}) + +// Create an ImageReceiver instance and set photographing parameters. Wherein, the resolution must be one of the photographing resolutions supported by the current device, which are obtained by photoProfilesArray. +let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) +// Obtain the surface ID for displaying the photos. +let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() +// Create a photo output stream. +let photoOutput +try { + photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) +} catch (error) { + console.error('Failed to createPhotoOutput errorCode = ' + error.code); +} +// Create a session. +let captureSession +try { + captureSession = cameraManager.createCaptureSession() +} catch (error) { + console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); +} + +// Listen for session errors. +captureSession.on('error', (error) => { + console.info(`Capture session error code: ${error.code}`); +}) + +// Start configuration for the session. +try { + captureSession.beginConfig() +} catch (error) { + console.error('Failed to beginConfig. errorCode = ' + error.code); +} + +// Add the camera input stream to the session. +try { + captureSession.addInput(cameraInput) +} catch (error) { + console.error('Failed to addInput. errorCode = ' + error.code); +} + +// Add the preview output stream to the session. +try { + captureSession.addOutput(previewOutput) +} catch (error) { + console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); +} + +// Add the photo output stream to the session. +try { + captureSession.addOutput(photoOutput) +} catch (error) { + console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); +} + +// Commit the session configuration. +await captureSession.commitConfig() + +// Start the session. +await captureSession.start().then(() => { + console.info('Promise returned to indicate the session start success.'); +}) +// Check whether the camera has flash. +let flashStatus +try { + flashStatus = captureSession.hasFlash() +} catch (error) { + console.error('Failed to hasFlash. errorCode = ' + error.code); +} +console.info('Promise returned with the flash light support status:' + flashStatus); + +if (flashStatus) { + // Check whether the auto flash mode is supported. + let flashModeStatus + try { + let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO) + flashModeStatus = status + } catch (error) { + console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); + } + if(flashModeStatus) { + // Set the flash mode to auto. + try { + captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO) + } catch (error) { + console.error('Failed to set the flash mode. errorCode = ' + error.code); + } + } +} + +// Check whether the continuous auto focus is supported. +let focusModeStatus +try { + let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO) + focusModeStatus = status +} catch (error) { + console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); +} + +if (focusModeStatus) { + // Set the focus mode to continuous auto focus. + try { + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO) + } catch (error) { + console.error('Failed to set the focus mode. errorCode = ' + error.code); + } +} + +// Obtain the zoom ratio range supported by the camera. +let zoomRatioRange +try { + zoomRatioRange = captureSession.getZoomRatioRange() +} catch (error) { + console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); +} + +// Set a zoom ratio. +try { + captureSession.setZoomRatio(zoomRatioRange[0]) +} catch (error) { + console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); +} +let settings = { + quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the photo quality to high. + rotation: camera.ImageRotation.ROTATION_0 // Set the rotation angle of the photo to 0. +} +// Use the current photographing settings to take photos. +photoOutput.capture(settings, async (err) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.info('Callback invoked to indicate the photo capture request success.'); +}); +// Stop the session. +captureSession.stop() + +// Release the camera input stream. +cameraInput.close() + +// Release the preview output stream. +previewOutput.release() + +// Release the photo output stream. +photoOutput.release() + +// Release the session. +captureSession.release() + +// Set the session to null. +captureSession = null +``` diff --git a/en/application-dev/media/camera-shooting.md b/en/application-dev/media/camera-shooting.md new file mode 100644 index 0000000000000000000000000000000000000000..9026267ebc0a6950ced6b5092ce88e8ed31d2e24 --- /dev/null +++ b/en/application-dev/media/camera-shooting.md @@ -0,0 +1,159 @@ +# Camera Photographing + +Photographing is an important function of the camera application. Based on the complex logic of the camera hardware, the camera module provides APIs for you to set information such as resolution, flash, focal length, photo quality, and rotation angle. + +## How to Develop + +Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. + +1. Import the image module. The APIs provided by this module are used to obtain the surface ID and create a photo output stream. + + ```ts + import image from '@ohos.multimedia.image'; + ``` + +2. Obtain the surface ID. + + Call **createImageReceiver()** of the image module to create an **ImageReceiver** instance, and use **getReceivingSurfaceId()** of the instance to obtain the surface ID, which is associated with the photo output stream to process the data output by the stream. + + ```ts + function getImageReceiverSurfaceId() { + let receiver = image.createImageReceiver(640, 480, 4, 8); + console.info('before ImageReceiver check'); + if (receiver !== undefined) { + console.info('ImageReceiver is ok'); + let photoSurfaceId = receiver.getReceivingSurfaceId(); + console.info('ImageReceived id: ' + JSON.stringify(photoSurfaceId)); + } else { + console.info('ImageReceiver is not ok'); + } + } + ``` + +3. Create a photo output stream. + + Obtain the photo output streams supported by the current device from **photoProfiles** in **CameraOutputCapability**, and then call **createPhotoOutput()** to pass in a supported output stream and the surface ID obtained in step 1 to create a photo output stream. + + ```ts + let photoProfilesArray = cameraOutputCapability.photoProfiles; + if (!photoProfilesArray) { + console.error("createOutput photoProfilesArray == null || undefined"); + } + let photoOutput; + try { + photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); + } catch (error) { + console.error('Failed to createPhotoOutput errorCode = ' + error.code); + } + ``` + +4. Set camera parameters. + + You can set camera parameters to adjust photographing functions, including the flash, zoom ratio, and focal length. + + ```ts + // Check whether the camera has flash. + let flashStatus; + try { + flashStatus = captureSession.hasFlash(); + } catch (error) { + console.error('Failed to hasFlash. errorCode = ' + error.code); + } + console.info('Promise returned with the flash light support status:' + flashStatus); + if (flashStatus) { + // Check whether the auto flash mode is supported. + let flashModeStatus; + try { + let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); + flashModeStatus = status; + } catch (error) { + console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); + } + if(flashModeStatus) { + // Set the flash mode to auto. + try { + captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); + } catch (error) { + console.error('Failed to set the flash mode. errorCode = ' + error.code); + } + } + } + // Check whether the continuous auto focus is supported. + let focusModeStatus; + try { + let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); + focusModeStatus = status; + } catch (error) { + console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); + } + if (focusModeStatus) { + // Set the focus mode to continuous auto focus. + try { + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); + } catch (error) { + console.error('Failed to set the focus mode. errorCode = ' + error.code); + } + } + // Obtain the zoom ratio range supported by the camera. + let zoomRatioRange; + try { + zoomRatioRange = captureSession.getZoomRatioRange(); + } catch (error) { + console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); + } + // Set a zoom ratio. + try { + captureSession.setZoomRatio(zoomRatioRange[0]); + } catch (error) { + console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); + } + ``` + +5. Trigger photographing. + + Call **capture()** in the **PhotoOutput** class to capture a photo. In this API, the first parameter specifies the settings (for example, photo quality and rotation angle) for photographing, and the second parameter is a callback function. + + ```ts + let settings = { + quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the photo quality to high. + rotation: camera.ImageRotation.ROTATION_0, // Set the rotation angle of the photo to 0. + location: captureLocation, // Set the geolocation information of the photo. + mirror: false // Disable mirroring (disabled by default). + }; + photoOutput.capture(settings, async (err) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.info('Callback invoked to indicate the photo capture request success.'); + }); + ``` + +## Status Listening + +During camera application development, you can listen for the status of the photo output stream, including the start of the photo stream, the start and end of the photo frame, and the errors of the photo output stream. + +- Register the 'captureStart' event to listen for photographing start events. This event can be registered when a **PhotoOutput** object is created and is triggered when the bottom layer starts exposure for photographing for the first time. The capture ID is returned. + + ```ts + photoOutput.on('captureStart', (captureId) => { + console.info(`photo capture stated, captureId : ${captureId}`); + }) + ``` + +- Register the 'captureEnd' event to listen for photographing end events. This event can be registered when a **PhotoOutput** object is created and is triggered when the photographing is complete. [CaptureEndInfo](../reference/apis/js-apis-camera.md#captureendinfo) is returned. + + ```ts + photoOutput.on('captureEnd', (captureEndInfo) => { + console.info(`photo capture end, captureId : ${captureEndInfo.captureId}`); + console.info(`frameCount : ${captureEndInfo.frameCount}`); + }) + ``` + +- Register the 'error' event to listen for photo output errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode). + + ```ts + photoOutput.on('error', (error) => { + console.info(`Photo output error code: ${error.code}`); + }) + ``` diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md deleted file mode 100644 index 0622db9c3ce6d962001b47ca6d2e6d1bc2aaff7c..0000000000000000000000000000000000000000 --- a/en/application-dev/media/camera.md +++ /dev/null @@ -1,511 +0,0 @@ -# Camera Development - -## When to Use - -With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zoom control, and much more. - -Before calling camera APIs, be familiar with the following concepts: - -- **Static camera capabilities**: A series of parameters used to describe inherent capabilities of a camera, such as orientation and supported resolution. -- **Physical camera**: An independent camera device. The physical camera ID is a string that uniquely identifies a physical camera. -- **Asynchronous operation**: A non-blocking operation that allows other operations to execute before it completes. To prevent the UI thread from being blocked, some **Camera** calls are asynchronous. Each asynchronous API provides the callback and promise functions. - -## How to Develop - -### Available APIs - -For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). - -### Full-Process Scenario - -The full process includes applying for permissions, creating an instance, setting parameters, managing sessions, taking photos, recording videos, and releasing resources. - -#### Applying for Permissions - -You must apply for the permissions for your application to access the camera device and other functions. The following table lists camera-related permissions. - -| Permission| Attribute Value | -| -------- | ------------------------------ | -| Camera| ohos.permission.CAMERA | -| Call recording| ohos.permission.MICROPHONE | -| Storage| ohos.permission.WRITE_MEDIA | -| Read| ohos.permission.READ_MEDIA | -| Location| ohos.permission.MEDIA_LOCATION | - -The code snippet is as follows: - -```typescript -const PERMISSIONS: Array = [ - 'ohos.permission.CAMERA', - 'ohos.permission.MICROPHONE', - 'ohos.permission.MEDIA_LOCATION', - 'ohos.permission.READ_MEDIA', - 'ohos.permission.WRITE_MEDIA' -] - -function applyPermission() { - console.info('[permission] get permission'); - globalThis.abilityContext.requestPermissionFromUser(PERMISSIONS) - } -``` - -#### Creating an Instance - -You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. Each of these IDs can be used to create an independent **CameraManager** instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata output streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows: - -```typescript -import camera from '@ohos.multimedia.camera' -import image from '@ohos.multimedia.image' -import media from '@ohos.multimedia.media' - -// Create a CameraManager instance. -context: any = getContext(this) -let cameraManager = camera.getCameraManager(this.context) -if (!cameraManager) { - console.error("camera.getCameraManager error") - return; -} -// Listen for camera state changes. -cameraManager.on('cameraStatus', (cameraStatusInfo) => { - console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); - console.log(`status: ${cameraStatusInfo.status}`); -}) - -// Obtain the camera list. -let cameraArray = cameraManager.getSupportedCameras(); -if (cameraArray.length <= 0) { - console.error("cameraManager.getSupportedCameras error") - return; -} - -for (let index = 0; index < cameraArray.length; index++) { - console.log('cameraId : ' + cameraArray[index].cameraId); // Obtain the camera ID. - console.log('cameraPosition : ' + cameraArray[index].cameraPosition); // Obtain the camera position. - console.log('cameraType : ' + cameraArray[index].cameraType); // Obtain the camera type. - console.log('connectionType : ' + cameraArray[index].connectionType); // Obtain the camera connection type. -} - -// Create a camera input stream. -let cameraInput -try { - cameraInput = cameraManager.createCameraInput(cameraArray[0]); -} catch () { - console.error('Failed to createCameraInput errorCode = ' + error.code); -} - -// Listen for CameraInput errors. -let cameraDevice = cameraArray[0]; -cameraInput.on('error', cameraDevice, (error) => { - console.log(`Camera input error code: ${error.code}`); -}) - -// Open the camera. -await cameraInput.open(); - -// Obtain the output stream capabilities supported by the camera. -let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]); -if (!cameraOutputCap) { - console.error("cameraManager.getSupportedOutputCapability error") - return; -} -console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); - -let previewProfilesArray = cameraOutputCap.previewProfiles; -if (!previewProfilesArray) { - console.error("createOutput previewProfilesArray == null || undefined") -} - -let photoProfilesArray = cameraOutputCap.photoProfiles; -if (!photoProfilesArray) { - console.error("createOutput photoProfilesArray == null || undefined") -} - -let videoProfilesArray = cameraOutputCap.videoProfiles; -if (!videoProfilesArray) { - console.error("createOutput videoProfilesArray == null || undefined") -} - -let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; -if (!metadataObjectTypesArray) { - console.error("createOutput metadataObjectTypesArray == null || undefined") -} - -// Create a preview stream. For details about the surfaceId parameter, see the XComponent section. The preview stream is the surface provided by the XComponent. -let previewOutput -try { - previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) -} catch (error) { - console.error("Failed to create the PreviewOutput instance.") -} - -// Listen for PreviewOutput errors. -previewOutput.on('error', (error) => { - console.log(`Preview output error code: ${error.code}`); -}) - -// Create an ImageReceiver instance and set photo parameters. Wherein, the resolution must be one of the photographing resolutions supported by the current device, which are obtained by photoProfilesArray. -let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) -// Obtain the surface ID for displaying the photos. -let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() -// Create a photographing output stream. -let photoOutput -try { - photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) -} catch (error) { - console.error('Failed to createPhotoOutput errorCode = ' + error.code); -} - -// Define video recording parameters. -let videoConfig = { - audioSourceType: 1, - videoSourceType: 1, - profile: { - audioBitrate: 48000, - audioChannels: 2, - audioCodec: 'audio/mp4v-es', - audioSampleRate: 48000, - durationTime: 1000, - fileFormat: 'mp4', - videoBitrate: 48000, - videoCodec: 'video/mp4v-es', - videoFrameWidth: 640, - videoFrameHeight: 480, - videoFrameRate: 30 - }, - url: 'file:///data/media/01.mp4', - orientationHint: 0, - maxSize: 100, - maxDuration: 500, - rotation: 0 -} - -// Create a video recording output stream. -let videoRecorder -media.createVideoRecorder().then((recorder) => { - console.log('createVideoRecorder called') - videoRecorder = recorder -}) -// Set video recording parameters. -videoRecorder.prepare(videoConfig) -// Obtain the surface ID for video recording. -let videoSurfaceId -videoRecorder.getInputSurface().then((id) => { - console.log('getInputSurface called') - videoSurfaceId = id -}) - -// Create a VideoOutput instance. -let videoOutput -try { - videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) -} catch (error) { - console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); -} - -// Listen for VideoOutput errors. -videoOutput.on('error', (error) => { - console.log(`Preview output error code: ${error.code}`); -}) -``` -Surfaces must be created in advance for the preview, shooting, and video recording stream. The preview stream is the surface provided by the **XComponent**, the shooting stream is the surface provided by **ImageReceiver**, and the video recording stream is the surface provided by **VideoRecorder**. - -**XComponent** - -```typescript -mXComponentController: XComponentController = new XComponentController // Create an XComponentController. - -build() { - Flex() { - XComponent({ // Create an XComponent. - id: '', - type: 'surface', - libraryname: '', - controller: this.mXComponentController - }) - .onload(() => { // Set the onload callback. - // Set the surface width and height (1920 x 1080). For details about how to set the preview size, see the preview resolutions supported by the current device, which are obtained by previewProfilesArray. - this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) - // Obtain the surface ID. - globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() - }) - .width('1920px') // Set the width of the XComponent. - .height('1080px') // Set the height of the XComponent. - } -} -``` - -**ImageReceiver** - -```typescript -function getImageReceiverSurfaceId() { - let receiver = image.createImageReceiver(640, 480, 4, 8) - console.log(TAG + 'before ImageReceiver check') - if (receiver !== undefined) { - console.log('ImageReceiver is ok') - surfaceId1 = receiver.getReceivingSurfaceId() - console.log('ImageReceived id: ' + JSON.stringify(surfaceId1)) - } else { - console.log('ImageReceiver is not ok') - } - } -``` - -**VideoRecorder** - -```typescript -function getVideoRecorderSurface() { - await getFd('CameraManager.mp4'); - mVideoConfig.url = mFdPath; - media.createVideoRecorder((err, recorder) => { - console.info('Entering create video receiver') - mVideoRecorder = recorder - console.info('videoRecorder is :' + JSON.stringify(mVideoRecorder)) - console.info('videoRecorder.prepare called.') - mVideoRecorder.prepare(mVideoConfig, (err) => { - console.info('videoRecorder.prepare success.') - mVideoRecorder.getInputSurface((err, id) => { - console.info('getInputSurface called') - mVideoSurface = id - console.info('getInputSurface surfaceId: ' + JSON.stringify(mVideoSurface)) - }) - }) - }) - } -``` - -#### Managing Sessions - -##### Creating a Session - -```typescript -// Create a session. -let captureSession -try { - captureSession = cameraManager.createCaptureSession() -} catch (error) { - console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); -} - -// Listen for session errors. -captureSession.on('error', (error) => { - console.log(`Capture session error code: ${error.code}`); -}) - -// Start configuration for the session. -try { - captureSession.beginConfig() -} catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); -} - -// Add the camera input stream to the session. -try { - captureSession.addInput(cameraInput) -} catch (error) { - console.error('Failed to addInput. errorCode = ' + error.code); -} - -// Add the preview input stream to the session. -try { - captureSession.addOutput(previewOutput) -} catch (error) { - console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); -} - -// Add the photographing output stream to the session. -try { - captureSession.addOutput(photoOutput) -} catch (error) { - console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); -} - -// Commit the session configuration. -await captureSession.commitConfig() - -// Start the session. -await captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); -}) -``` - -##### Switching a Session - -```typescript -// Stop the session. -await captureSession.stop() - -// Start configuration for the session. -try { - captureSession.beginConfig() -} catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); -} - -// Remove the photographing output stream from the session. -try { - captureSession.removeOutput(photoOutput) -} catch (error) { - console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code); -} - -// Add a video recording output stream to the session. -try { - captureSession.addOutput(videoOutput) -} catch (error) { - console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); -} - -// Commit the session configuration. -await captureSession.commitConfig() - -// Start the session. -await captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); -}) -``` - -#### Setting Parameters - -```typescript -// Check whether the camera has flash. -let flashStatus -try { - flashStatus = captureSession.hasFlash() -} catch (error) { - console.error('Failed to hasFlash. errorCode = ' + error.code); -} -console.log('Promise returned with the flash light support status:' + flashStatus); - -if (flashStatus) { - // Check whether the auto flash mode is supported. - let flashModeStatus - try { - let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO) - flashModeStatus = status - } catch (error) { - console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); - } - if(flashModeStatus) { - // Set the flash mode to auto. - try { - captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO) - } catch (error) { - console.error('Failed to set the flash mode. errorCode = ' + error.code); - } - } -} - -// Check whether the continuous auto focus is supported. -let focusModeStatus -try { - let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO) - focusModeStatus = status -} catch (error) { - console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); -} - -if (focusModeStatus) { - // Set the focus mode to continuous auto focus. - try { - captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO) - } catch (error) { - console.error('Failed to set the focus mode. errorCode = ' + error.code); - } -} - -// Obtain the zoom ratio range supported by the camera. -let zoomRatioRange -try { - zoomRatioRange = captureSession.getZoomRatioRange() -} catch (error) { - console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); -} - -// Set a zoom ratio. -try { - captureSession.setZoomRatio(zoomRatioRange[0]) -} catch (error) { - console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); -} -``` - -#### Taking Photos - -```typescript -let settings = { - quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the image quality to high. - rotation: camera.ImageRotation.ROTATION_0 // Set the image rotation angle to 0. -} -// Use the current photographing settings to take photos. -photoOutput.capture(settings, async (err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` - -#### Recording Videos - -```typescript -// Start the video recording output stream. -videoOutput.start(async (err) => { - if (err) { - console.error('Failed to start the video output ${err.message}'); - return; - } - console.log('Callback invoked to indicate the video output start success.'); -}); - -// Start video recording. -videoRecorder.start().then(() => { - console.info('videoRecorder start success'); -} - -// Stop video recording. -videoRecorder.stop().then(() => { - console.info('stop success'); -} - -// Stop the video recording output stream. -videoOutput.stop((err) => { - if (err) { - console.error('Failed to stop the video output ${err.message}'); - return; - } - console.log('Callback invoked to indicate the video output stop success.'); -}); -``` - -For details about the APIs used for saving photos, see [Image Processing](image.md#using-imagereceiver). - -#### Releasing Resources - -```typescript -// Stop the session. -captureSession.stop() - -// Release the camera input stream. -cameraInput.close() - -// Release the preview output stream. -previewOutput.release() - -// Release the photographing output stream. -photoOutput.release() - -// Release the video recording output stream. -videoOutput.release() - -// Release the session. -captureSession.release() - -// Set the session to null. -captureSession = null -``` - -## Process Flowchart - -The following figure shows the process of using the camera. -![camera_framework process](figures/camera_framework_process.png) diff --git a/en/application-dev/media/distributed-audio-playback.md b/en/application-dev/media/distributed-audio-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..c56420de740e545168d009b5c743f2790146c475 --- /dev/null +++ b/en/application-dev/media/distributed-audio-playback.md @@ -0,0 +1,101 @@ +# Distributed Audio Playback (for System Applications Only) + +Distributed audio playback enables an application to continue audio playback on another device in the same network. + +You can use distributed audio playback to transfer all audio streams or the specified audio stream being played on the current device to a remote device. + +## How to Develop + +Before continuing audio playback on another device in the same network, you must obtain the device list on the network and listen for device connection state changes. For details, see [Audio Output Device Management](audio-output-device-management.md). + +When obtaining the device list on the network, you can specify **DeviceFlag** to filter out the required devices. + +| Name| Description| +| -------- | -------- | +| NONE_DEVICES_FLAG9+ | None. This is a system API.| +| OUTPUT_DEVICES_FLAG | Local output device.| +| INPUT_DEVICES_FLAG | Local input device.| +| ALL_DEVICES_FLAG | Local input and output device.| +| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | Remote output device. This is a system API.| +| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | Remote input device. This is a system API.| +| ALL_DISTRIBUTED_DEVICES_FLAG9+ | Remote input and output device. This is a system API.| + +For details about the API reference, see [AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9). + +### Continuing the Playing of All Audio Streams + +1. [Obtain the output device information](audio-output-device-management.md#obtaining-output-device-information). + +2. Create an **AudioDeviceDescriptor** instance to describe an audio output device. + +3. Call **selectOutputDevice** to select a remote device, on which all the audio streams will continue playing. + +```ts +let outputAudioDeviceDescriptor = [{ + deviceRole: audio.DeviceRole.OUTPUT_DEVICE, + deviceType: audio.DeviceType.SPEAKER, + id: 1, + name: "", + address: "", + sampleRates: [44100], + channelCounts: [2], + channelMasks: [0], + networkId: audio.LOCAL_NETWORK_ID, + interruptGroupId: 1, + volumeGroupId: 1, +}]; + +async function selectOutputDevice() { + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Invoke selectOutputDevice failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Invoke selectOutputDevice succeeded.'); + } + }); +} +``` + +### Continuing the Playing of the Specified Audio Stream + +1. [Obtain the output device information](audio-output-device-management.md#obtaining-output-device-information). + +2. Create an **AudioRendererFilter** instance, with **uid** to specify an application and **rendererId** to specify an audio stream. + +3. Create an **AudioDeviceDescriptor** instance to describe an audio output device. + +4. Call **selectOutputDeviceByFilter** to select a remote device, on which the specified audio stream will continue playing. + +```ts +let outputAudioRendererFilter = { + uid: 20010041, + rendererInfo: { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 }, + rendererId: 0 }; + +let outputAudioDeviceDescriptor = [{ + deviceRole: audio.DeviceRole.OUTPUT_DEVICE, + deviceType: audio.DeviceType.SPEAKER, + id: 1, + name: "", + address: "", + sampleRates: [44100], + channelCounts: [2], + channelMasks: [0], + networkId: audio.LOCAL_NETWORK_ID, + interruptGroupId: 1, + volumeGroupId: 1, +}]; + +async function selectOutputDeviceByFilter() { + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Invoke selectOutputDeviceByFilter failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Invoke selectOutputDeviceByFilter succeeded.'); + } + }); +} +``` diff --git a/en/application-dev/media/distributed-avsession-overview.md b/en/application-dev/media/distributed-avsession-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..ff293ed7332d0a9c5e66632f91c943af42d28030 --- /dev/null +++ b/en/application-dev/media/distributed-avsession-overview.md @@ -0,0 +1,54 @@ +# Distributed AVSession Overview + +With distributed AVSession, OpenHarmony allows users to project locally played media to a distributed device for a better playback effect. For example, users can project audio played on a tablet to a smart speaker. + +After the user initiates a projection, the media information is synchronized to the distributed device in real time, and the user can control the playback (for example, previous, next, play, and pause) on the distributed device. From the perspective of the user, the playback control operation on the distributed device is the same as that on the local device. + + +## Interaction Process + +After the local device is paired with a distributed device, the controller on the local device projects media to the distributed device through AVSessionManager, thereby implementing a distributed AVSession. The interaction process is shown below. + +![Distributed AVSession Interaction Process](figures/distributed-avsession-interaction-process.png) + +The AVSession service on the distributed device automatically creates an **AVSession** object for information synchronization with the local device. The information to synchronize includes the session information, control commands, and events. + +## Distributed AVSession Process + +After the user triggers a projection, the remote device automatically creates an **AVSession** object to associate it with that on the local device. The detailed process is as follows: + +1. After receiving an audio device switching command, the AVSession service on the local device synchronizes the session information to the distributed device. + +2. The controller (for example, Media Controller) on the distributed device detects the new **AVSession** object and creates an **AVSessionController** object for it. + +3. Through the **AVSessionController** object, the controller on the distributed device sends a control command to the **AVSession** object on the local device. + +4. Upon the receipt of the control command, the **AVSession** object on the local device triggers a callback to the local audio application. + +5. The **AVSession** object on the local device synchronizes the new session information to the controller on the distributed device in real time. + +6. When the remote device is disconnected, the audio stream is switched back to the local device and the playback is paused. (The audio module completes the switchback, and the AVSession service instructs the application to pause the playback.) + +## Distributed AVSession Scenarios + +There are two scenarios for projection implemented using the distributed AVSession: + +- System projection: The controller (for example, Media Controller) initiates a projection. + +This type of projection takes effect for all applications. After a system projection, all audios on the local device are played from the distributed device by default. + +- Application projection: An audio and video application integrates the projection component to initiate a projection. (This scenario is not supported yet.) + + This type of projection takes effect for a single application. After an application projection, audio of the application on the local device is played from the distributed device, and audio of other applications is still played from the local device. + +Projection preemption is supported. If application A initiates a projection to a remote device and then application B initiates a projection to the same device, then audio of application B is played on the remote device. + +## Relationship Between Distributed AVSession and Distributed Audio Playback + +The internal logic for the distributed AVSession to implement projection is as follows: + +- API related to [distributed audio playback](distributed-audio-playback.md) are called to project audio streams to the distributed device. + +- The distributed capability is used to project the session metadata to the distributed device for display. + +Projection implemented by using the distributed AVSession not only enables audio to be played on the distributed device, but also enables media information to be displayed on the distributed device. It also allows the user to perform playback control on the distributed device. diff --git a/en/application-dev/media/figures/audio-capturer-state.png b/en/application-dev/media/figures/audio-capturer-state.png deleted file mode 100644 index 52b5556260dbf78c5e816b37013248a07e8dbbc6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/audio-capturer-state.png and /dev/null differ diff --git a/en/application-dev/media/figures/audio-playback-interaction-diagram.png b/en/application-dev/media/figures/audio-playback-interaction-diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..b96179b6b610463bc34d2515b145a57b29e574cb Binary files /dev/null and b/en/application-dev/media/figures/audio-playback-interaction-diagram.png differ diff --git a/en/application-dev/media/figures/audio-renderer-state.png b/en/application-dev/media/figures/audio-renderer-state.png deleted file mode 100644 index 9ae30c2a9306dc85662405c36da9e11d07ed9a2a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/audio-renderer-state.png and /dev/null differ diff --git a/en/application-dev/media/figures/audio-stream-mgmt-invoking-relationship.png b/en/application-dev/media/figures/audio-stream-mgmt-invoking-relationship.png new file mode 100644 index 0000000000000000000000000000000000000000..50ad902dd8b55a91a220e2705fea5674cd855ae6 Binary files /dev/null and b/en/application-dev/media/figures/audio-stream-mgmt-invoking-relationship.png differ diff --git a/en/application-dev/media/figures/audiocapturer-status-change.png b/en/application-dev/media/figures/audiocapturer-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..aadbc4fb6470b7cdc0f399ee5954a96c01a7f7c3 Binary files /dev/null and b/en/application-dev/media/figures/audiocapturer-status-change.png differ diff --git a/en/application-dev/media/figures/audiorenderer-status-change.png b/en/application-dev/media/figures/audiorenderer-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..a721044f7aeccfed0260176963d192cac40dd8a6 Binary files /dev/null and b/en/application-dev/media/figures/audiorenderer-status-change.png differ diff --git a/en/application-dev/media/figures/avsession-interaction-process.png b/en/application-dev/media/figures/avsession-interaction-process.png new file mode 100644 index 0000000000000000000000000000000000000000..2347599b7d118c45c2d2eb58708729f91c4dc801 Binary files /dev/null and b/en/application-dev/media/figures/avsession-interaction-process.png differ diff --git a/en/application-dev/media/figures/bitmap-operation.png b/en/application-dev/media/figures/bitmap-operation.png new file mode 100644 index 0000000000000000000000000000000000000000..c5107dbabd86fdc29863d5f25947b447d9c1deeb Binary files /dev/null and b/en/application-dev/media/figures/bitmap-operation.png differ diff --git a/en/application-dev/media/figures/camera-development-model.png b/en/application-dev/media/figures/camera-development-model.png new file mode 100644 index 0000000000000000000000000000000000000000..fa97f369dda840cb474bc8fffbb7396b8a7b6508 Binary files /dev/null and b/en/application-dev/media/figures/camera-development-model.png differ diff --git a/en/application-dev/media/figures/camera-workflow.png b/en/application-dev/media/figures/camera-workflow.png new file mode 100644 index 0000000000000000000000000000000000000000..31a7e814724cf97a80a5cc8b88778334ccb352fb Binary files /dev/null and b/en/application-dev/media/figures/camera-workflow.png differ diff --git a/en/application-dev/media/figures/camera_framework_process.png b/en/application-dev/media/figures/camera_framework_process.png deleted file mode 100644 index bf4b6806fb19e087318306dbc7f9a4b0576273cd..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/camera_framework_process.png and /dev/null differ diff --git a/en/application-dev/media/figures/cropping.jpeg b/en/application-dev/media/figures/cropping.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..a564818815eb3fde13a40ef02d0811bd56803fb9 Binary files /dev/null and b/en/application-dev/media/figures/cropping.jpeg differ diff --git a/en/application-dev/media/figures/distributed-avsession-interaction-process.png b/en/application-dev/media/figures/distributed-avsession-interaction-process.png new file mode 100644 index 0000000000000000000000000000000000000000..d16e362db22857b2ddba3cdbf2142c3759f73fc8 Binary files /dev/null and b/en/application-dev/media/figures/distributed-avsession-interaction-process.png differ diff --git a/en/application-dev/media/figures/en-us_image_audio_player.png b/en/application-dev/media/figures/en-us_image_audio_player.png deleted file mode 100644 index 4edcec759e7b8507d605823f157ba9c6c1108fcd..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_player.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_audio_recorder_state_machine.png b/en/application-dev/media/figures/en-us_image_audio_recorder_state_machine.png deleted file mode 100644 index 8cd657cf19c48da5e52809bad387984f50d5a3c7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_recorder_state_machine.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_audio_recorder_zero.png b/en/application-dev/media/figures/en-us_image_audio_recorder_zero.png deleted file mode 100644 index 7c33fcc1723fcdcc468bd3a6004de8b03b20100b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_recorder_zero.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_audio_routing_manager.png b/en/application-dev/media/figures/en-us_image_audio_routing_manager.png deleted file mode 100644 index 710679f6cac0c30d06dffa97b0e80b3cebe80f79..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_routing_manager.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_audio_state_machine.png b/en/application-dev/media/figures/en-us_image_audio_state_machine.png deleted file mode 100644 index 22b7aeaa1db5b369d3daf44854d7f7f9a00f775b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_state_machine.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_audio_stream_manager.png b/en/application-dev/media/figures/en-us_image_audio_stream_manager.png deleted file mode 100644 index 1f326d4bd0798dd5ecc0b55130904cbf87d2ea1f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_stream_manager.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_audio_volume_manager.png b/en/application-dev/media/figures/en-us_image_audio_volume_manager.png deleted file mode 100644 index 0d47fbfacce9c1ff48811e1cf5d764231bdb596b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_audio_volume_manager.png and /dev/null differ 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 deleted file mode 100644 index b5eb9b02a977d0e4551a236c7cc8a154710f5517..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_avplayer_audio.png and /dev/null 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 deleted file mode 100644 index aa8afdbcbf142fd745cee03fc422caec51cfe41b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png and /dev/null 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 deleted file mode 100644 index 54525ebed1d1792f43156ffbeb1ffa37f56d8237..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_avplayer_video.png and /dev/null 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 deleted file mode 100644 index 7d5da3bdc91fe8fb7be9f0b4054f934ec054b8e6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png and /dev/null 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 deleted file mode 100644 index 7ffcb21f09365e9b072bdaf48f8b98d7d45a8aaa..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_avsession.png b/en/application-dev/media/figures/en-us_image_avsession.png deleted file mode 100644 index 3289bc4ca3c54eb3e99c9230c821380f8f7c0c5b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_avsession.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_video_player.png b/en/application-dev/media/figures/en-us_image_video_player.png deleted file mode 100644 index f9b4aabdc7215f22788d92c68ef353fafffda1c3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_video_player.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_video_recorder_state_machine.png b/en/application-dev/media/figures/en-us_image_video_recorder_state_machine.png deleted file mode 100644 index 3e81dcc18d1f47b6de087a7a88fd75b308ea51a0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_video_recorder_state_machine.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_video_recorder_zero.png b/en/application-dev/media/figures/en-us_image_video_recorder_zero.png deleted file mode 100644 index a7f7fa09392eb916132d891a84d62f31f0f27782..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_video_recorder_zero.png and /dev/null differ diff --git a/en/application-dev/media/figures/en-us_image_video_state_machine.png b/en/application-dev/media/figures/en-us_image_video_state_machine.png deleted file mode 100644 index c0595ed5120b632142d6da8841c9e45277b10f55..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/en-us_image_video_state_machine.png and /dev/null differ diff --git a/en/application-dev/media/figures/horizontal-flip.jpeg b/en/application-dev/media/figures/horizontal-flip.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f43e4f6ab2adc68bf0f90eaf8177d36ee91f32ac Binary files /dev/null and b/en/application-dev/media/figures/horizontal-flip.jpeg differ diff --git a/en/application-dev/media/figures/image-development-process.png b/en/application-dev/media/figures/image-development-process.png new file mode 100644 index 0000000000000000000000000000000000000000..47db9d3faf7f8bffc80f63995dc73d0ad32799e5 Binary files /dev/null and b/en/application-dev/media/figures/image-development-process.png differ diff --git a/en/application-dev/media/figures/invoking-relationship-recording-stream-mgmt.png b/en/application-dev/media/figures/invoking-relationship-recording-stream-mgmt.png new file mode 100644 index 0000000000000000000000000000000000000000..a1f404f67bf18d91c2cc42ab65d8c7c5f01518a8 Binary files /dev/null and b/en/application-dev/media/figures/invoking-relationship-recording-stream-mgmt.png differ diff --git a/en/application-dev/media/figures/local-avsession-interaction-process.png b/en/application-dev/media/figures/local-avsession-interaction-process.png new file mode 100644 index 0000000000000000000000000000000000000000..dfccf9c6874f26a7e030189191f34248b7230b1a Binary files /dev/null and b/en/application-dev/media/figures/local-avsession-interaction-process.png differ diff --git a/en/application-dev/media/figures/media-system-framework.png b/en/application-dev/media/figures/media-system-framework.png new file mode 100644 index 0000000000000000000000000000000000000000..f1b92795c05db2caa6869acfba865f585a947c19 Binary files /dev/null and b/en/application-dev/media/figures/media-system-framework.png differ diff --git a/en/application-dev/media/figures/offsets.jpeg b/en/application-dev/media/figures/offsets.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ab4c87a69bae55a62feddc0ca61a0ef1081bf199 Binary files /dev/null and b/en/application-dev/media/figures/offsets.jpeg differ diff --git a/en/application-dev/media/figures/original-drawing.jpeg b/en/application-dev/media/figures/original-drawing.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..01a0b0d7022dfc0130029154fec7321bc62dfe36 Binary files /dev/null and b/en/application-dev/media/figures/original-drawing.jpeg differ diff --git a/en/application-dev/media/figures/photographing-development-process.png b/en/application-dev/media/figures/photographing-development-process.png new file mode 100644 index 0000000000000000000000000000000000000000..b7ee61acfa63da55ef1389212e090da14a091a68 Binary files /dev/null and b/en/application-dev/media/figures/photographing-development-process.png differ diff --git a/en/application-dev/media/figures/playback-status-change.png b/en/application-dev/media/figures/playback-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..860764d3d15b93e544a6f27316584963acba2f0f Binary files /dev/null and b/en/application-dev/media/figures/playback-status-change.png differ diff --git a/en/application-dev/media/figures/recording-development-process.png b/en/application-dev/media/figures/recording-development-process.png new file mode 100644 index 0000000000000000000000000000000000000000..c29043a1f8b9255664969b4e0b0a1ca971d4e1f7 Binary files /dev/null and b/en/application-dev/media/figures/recording-development-process.png differ diff --git a/en/application-dev/media/figures/recording-status-change.png b/en/application-dev/media/figures/recording-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..9f15af9c1992e34fa7d750d08fd0245b6cb3ba67 Binary files /dev/null and b/en/application-dev/media/figures/recording-status-change.png differ diff --git a/en/application-dev/media/figures/rotate.jpeg b/en/application-dev/media/figures/rotate.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..5965abb46dc9648a3dfd9136e7cc0b5c5203e6a7 Binary files /dev/null and b/en/application-dev/media/figures/rotate.jpeg differ diff --git a/en/application-dev/media/figures/transparency.png b/en/application-dev/media/figures/transparency.png new file mode 100644 index 0000000000000000000000000000000000000000..b9b43939f0dad8ee40bf0b6b7e40ddf49d141c66 Binary files /dev/null and b/en/application-dev/media/figures/transparency.png differ diff --git a/en/application-dev/media/figures/vertical-flip.jpeg b/en/application-dev/media/figures/vertical-flip.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..8ef368d6bb914815a90c8d82352cbd6fd9ab505c Binary files /dev/null and b/en/application-dev/media/figures/vertical-flip.jpeg differ diff --git a/en/application-dev/media/figures/video-playback-interaction-diagram.png b/en/application-dev/media/figures/video-playback-interaction-diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..93778e5fd397820e92b03f60a01076f251348ee6 Binary files /dev/null and b/en/application-dev/media/figures/video-playback-interaction-diagram.png differ diff --git a/en/application-dev/media/figures/video-playback-status-change.png b/en/application-dev/media/figures/video-playback-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..860764d3d15b93e544a6f27316584963acba2f0f Binary files /dev/null and b/en/application-dev/media/figures/video-playback-status-change.png differ diff --git a/en/application-dev/media/figures/video-recording-interaction-diagram.png b/en/application-dev/media/figures/video-recording-interaction-diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..3fbbffe30f5ab06ba0f0a9e6487c76cecd5546c4 Binary files /dev/null and b/en/application-dev/media/figures/video-recording-interaction-diagram.png differ diff --git a/en/application-dev/media/figures/video-recording-status-change.png b/en/application-dev/media/figures/video-recording-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..9f15af9c1992e34fa7d750d08fd0245b6cb3ba67 Binary files /dev/null and b/en/application-dev/media/figures/video-recording-status-change.png differ diff --git a/en/application-dev/media/figures/zoom.jpeg b/en/application-dev/media/figures/zoom.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..977db6cfbc5b81f5396e4d81f8954a9f7d4168e4 Binary files /dev/null and b/en/application-dev/media/figures/zoom.jpeg differ diff --git a/en/application-dev/media/image-decoding.md b/en/application-dev/media/image-decoding.md new file mode 100644 index 0000000000000000000000000000000000000000..00665aa430fb0d2ab95007f29d39b8adc5c5433c --- /dev/null +++ b/en/application-dev/media/image-decoding.md @@ -0,0 +1,143 @@ +# Image Decoding + +Image decoding refers to the process of decoding an archived image in a supported format into a [pixel map](image-overview.md) for image display or [processing](image-transformation.md). Currently, the following image formats are supported: JPEG, PNG, GIF, RAW, WebP, BMP, and SVG. + +## How to Develop + +Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to image decoding. + +1. Import the image module. + + ```ts + import image from '@ohos.multimedia.image'; + ``` + +2. Obtain an image. + - Method 1: Obtain the sandbox path. For details about how to obtain the sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). + + ```ts + // Code on the stage model + const context = getContext(this); + const filePath = context.cacheDir + '/test.jpg'; + ``` + + ```ts + // Code on the FA model + import featureAbility from '@ohos.ability.featureAbility'; + + const context = featureAbility.getContext(); + const filePath = context.getCacheDir() + "/test.jpg"; + ``` + - Method 2: Obtain the file descriptor of the image through the sandbox path. For details, see [file.fs API Reference] (../reference/apis/js-apis-file-fs.md). + To use this method, you must import the \@ohos.file.fs module first. + + ```ts + import fs from '@ohos.file.fs'; + ``` + + Then call **fs.openSync()** to obtain the file descriptor. + + ```ts + // Code on the stage model + const context = getContext(this); + const filePath = context.cacheDir + '/test.jpg'; + const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + const fd = file?.fd; + ``` + + ```ts + // Code on the FA model + import featureAbility from '@ohos.ability.featureAbility'; + + const context = featureAbility.getContext(); + const filePath = context.getCacheDir() + "/test.jpg"; + const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + const fd = file?.fd; + ``` + - Method 3: Obtain the array buffer of the resource file through the resource manager. For details, see [ResourceManager API Reference](../reference/apis/js-apis-resource-manager.md#getrawfilecontent9-1). + + ```ts + // Code on the stage model + const context = getContext(this); + // Obtain a resource manager. + const resourceMgr = context.resourceManager; + ``` + + ```ts + // Code on the FA model + // Import the resourceManager module. + import resourceManager from '@ohos.resourceManager'; + const resourceMgr = await resourceManager.getResourceManager(); + ``` + + The method of obtaining the resource manager varies according to the application model. After obtaining the resource manager, call **resourceMgr.getRawFileContent()** to obtain the array buffer of the resource file. + + ```ts + const fileData = await resourceMgr.getRawFileContent('test.jpg'); + // Obtain the array buffer of the image. + const buffer = fileData.buffer; + ``` + +3. Create an **ImageSource** instance. + - Method 1: Create an **ImageSource** instance using the sandbox path. The sandbox path can be obtained by using method 1 in step 2. + + ```ts + // path indicates the obtained sandbox path. + const imageSource = image.createImageSource(filePath); + ``` + - Method 2: Create an **ImageSource** instance using the file descriptor. The file descriptor can be obtained by using method 2 in step 2. + + ```ts + // fd is the obtained file descriptor. + const imageSource = image.createImageSource(fd); + ``` + - Method 3: Create an **ImageSource** instance using a buffer array. The buffer array can be obtained by using method 3 in step 2. + + ```ts + const imageSource = image.createImageSource(buffer); + ``` + +4. Set **DecodingOptions** and decode the image to obtain a pixel map. + + ```ts + let decodingOptions = { + editable: true, + desiredPixelFormat: 3, + } + // Create a pixel map and perform rotation and scaling on it. + const pixelMap = await imageSource.createPixelMap(decodingOptions); + ``` + + After the decoding is complete and the pixel map is obtained, you can perform subsequent [image processing](image-transformation.md). + +## Sample Code - Decoding an Image in Resource Files + +1. Obtain a resource manager. + + ```ts + const context = getContext(this); + // Obtain a resourceManager instance. + const resourceMgr = context.resourceManager; + ``` + +2. Obtain the array buffer of the **test.jpg** file in the **rawfile** folder. + + ```ts + const fileData = await resourceMgr.getRawFileContent('test.jpg'); + // Obtain the array buffer of the image. + const buffer = fileData.buffer; + ``` + +3. Create an **ImageSource** instance. + + ```ts + const imageSource = image.createImageSource(buffer); + ``` + +4. Create a **PixelMap** instance. + + ```ts + const pixelMap = await imageSource.createPixelMap(); + ``` + + \ No newline at end of file diff --git a/en/application-dev/media/image-encoding.md b/en/application-dev/media/image-encoding.md new file mode 100644 index 0000000000000000000000000000000000000000..96e23b6ba16c63bdaf282dbaf9abc01d95dd6221 --- /dev/null +++ b/en/application-dev/media/image-encoding.md @@ -0,0 +1,48 @@ +# Image Encoding + +Image encoding refers to the process of encoding a pixel map into an archived image in different formats (only in JPEG and WebP currently) for subsequent processing, such as storage and transmission. + +## How to Develop + +Read [Image](../reference/apis/js-apis-image.md#imagepacker) for APIs related to image encoding. + +1. Create an **ImagePacker** object. + + ```ts + // Import the required module. + import image from '@ohos.multimedia.image'; + + const imagePackerApi = image.createImagePacker(); + ``` + +2. Set the encoding output stream and encoding parameters. + + **format** indicates the image encoding format, and **quality** indicates the image quality. The value ranges from 0 to 100, and the value 100 indicates the optimal quality. + + ```ts + let packOpts = { format:"image/jpeg", quality:98 }; + ``` + +3. [Create a PixelMap object or an ImageSource object](image-decoding.md). + +4. Encode the image and save the encoded image. + + Method 1: Use the **PixelMap** object for encoding. + + ```ts + imagePackerApi.packing(pixelMap, packOpts).then( data => { + // data is the file stream obtained after packing. You can write the file and save it to obtain an image. + }).catch(error => { + console.error('Failed to pack the image. And the error is: ' + error); + }) + ``` + + Method 2: Use the **ImageSource** object for encoding. + + ```ts + imagePackerApi.packing(imageSource, packOpts).then( data => { + // data is the file stream obtained after packing. You can write the file and save it to obtain an image. + }).catch(error => { + console.error('Failed to pack the image. And the error is: ' + error); + }) + ``` diff --git a/en/application-dev/media/image-overview.md b/en/application-dev/media/image-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..a88eb049166b845068a67eecec5a613435d124ab --- /dev/null +++ b/en/application-dev/media/image-overview.md @@ -0,0 +1,40 @@ +# Image Overview + +Image development is the process of parsing, processing, and constructing image pixel data to achieve the required image effect. Image development mainly involves image decoding, processing, and encoding. + +Before image development, be familiar with the following basic concepts: + +- Image decoding + + The operation of decoding an archived image in a supported format into a pixel map for image display or processing. Currently, the following image formats are supported: JPEG, PNG, GIF, RAW, WebP, BMP, and SVG. + +- Pixel map + + A bitmap that is not compressed after being decoded. It is used for image display or processing. + +- Image processing + + A series of operations on the pixel map, such as rotation, scaling, opacity setting, image information obtaining, and pixel data reading and writing. + +- Image encoding + + The operation of encoding a pixel map into an archived image in different formats (only in JPEG and WebP currently) for subsequent processing, such as storage and transmission. + +The figure below illustrates the image development process. + +**Figure 1** Image development process +![Image development process](figures/image-development-process.png) + +1. Image retrieval: Obtain a raw image through the application sandbox. + +2. Instance creation: Create an **ImageSource** instance, which is the source class of decoded images and is used to obtain or modify image information. + +3. [Image decoding](image-decoding.md): Decode the image source to generate a pixel map. + +4. [Image processing](image-transformation.md): Process the pixel map by modifying the image attributes to implement image rotation, scaling, and cropping, and then use the [Image component](../ui/arkts-graphics-display.md) to display the image. + +5. [Image encoding](image-encoding.md): Use the **ImagePacker** class to compress and encode the pixel map or image source to generate a new image. + +In addition to the preceding basic image development capabilities, OpenHarmony provides the [image tool](image-tool.md) to ease your development. + + \ No newline at end of file diff --git a/en/application-dev/media/image-pixelmap-operation.md b/en/application-dev/media/image-pixelmap-operation.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b17b2c4dc5e5911e921d19a46d1b3066af5100 --- /dev/null +++ b/en/application-dev/media/image-pixelmap-operation.md @@ -0,0 +1,60 @@ +# Pixel Map Operation + +To process a certain area in an image, you can perform pixel map operations, which are usually used to beautify the image. + +As shown in the figure below, the pixel data of a rectangle in an image is read, modified, and then written back to the corresponding area of the original image. + +**Figure 1** Pixel map operation +![Pixel map operation](figures/bitmap-operation.png) + +## How to Develop + +Read [Image](../reference/apis/js-apis-image.md#pixelmap7) for APIs related to pixel map operations. + +1. Complete [image decoding](image-decoding.md#how-to-develop) and obtain a **PixelMap** object. + +2. Obtain information from the **PixelMap** object. + + ```ts + // Obtain the total number of bytes of this pixel map. + let pixelBytesNumber = pixelMap.getPixelBytesNumber(); + // Obtain the number of bytes per row of this pixel map. + let rowCount = pixelMap.getBytesNumberPerRow(); + // Obtain the pixel density of the image. Pixel density refers to the number of pixels per inch of an image. A larger value of the pixel density indicates a finer image. + let getDensity = pixelMap.getDensity(); + ``` + +3. Read and modify the pixel data of the target area, and write the modified data back to the original image. + + ```ts + // Scenario 1: Read the pixel data of the entire image and write the modified data to an array buffer. + const readBuffer = new ArrayBuffer(pixelBytesNumber); + pixelMap.readPixelsToBuffer(readBuffer).then(() => { + console.info('Succeeded in reading image pixel data.'); + }).catch(error => { + console.error('Failed to read image pixel data. And the error is: ' + error); + }) + + // Scenario 2: Read the pixel data in a specified area and write the modified data to area.pixels. + const area = { + pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 } + } + pixelMap.readPixels(area).then(() => { + console.info('Succeeded in reading the image data in the area.'); + }).catch(error => { + console.error('Failed to read the image data in the area. And the error is: ' + error); + }) + + // The read image data can be used independently (by creating a pixel map) or modified as required. + // Write area.pixels to the specified area. + pixelMap.writePixels(area).then(() => { + console.info('Succeeded to write pixelMap into the specified area.'); + }) + + // Write the image data result to a pixel map. + const writeColor = new ArrayBuffer(96); + pixelMap.writeBufferToPixels(writeColor, () => {}); + ``` diff --git a/en/application-dev/media/image-tool.md b/en/application-dev/media/image-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..16748ff0b56557005793cdbe2798477995412cdf --- /dev/null +++ b/en/application-dev/media/image-tool.md @@ -0,0 +1,43 @@ +# Image Tool + +The image tool provides the capabilities of reading and editing Exchangeable Image File Format (EXIF) data of an image. + +EXIF is a file format dedicated for photos taken by digital cameras and is used to record attributes and shooting data of the photos. Currently, the image tool supports images in JPEG format only. + +Users may need to view or modify the EXIF data of photos in the Gallery application, for example, when the manual lens parameters of the camera are not automatically written as part of the EXIF data or the shooting time is incorrect due to camera power-off. + +Currently, OpenHarmony allows you to view and modify part of EXIF data. For details, see [EIXF](../reference/apis/js-apis-image.md#propertykey7). + +## How to Develop + +Read [Image](../reference/apis/js-apis-image.md#getimageproperty7) for APIs used to read and edit EXIF data. + +1. Obtain the image and create an **ImageSource** object. + + ```ts + // Import the required module. + import image from '@ohos.multimedia.image'; + + // Obtain the sandbox path and create an ImageSource object. + const fd =...; //Obtain the file descriptor of the image to be processed. + const imageSource = image.createImageSource(fd); + ``` + +2. Read and edit EXIF data. + + ```ts + // Read the EXIF data, where BitsPerSample indicates the number of bits per pixel. + imageSource.getImageProperty('BitsPerSample', (error, data) => { + if (error) { + console.error('Failed to get the value of the specified attribute key of the image.And the error is: ' + error); + } else { + console.info('Succeeded in getting the value of the specified attribute key of the image ' + data); + } + }) + + // Edit the EXIF data. + imageSource.modifyImageProperty('ImageWidth', '120').then(() => { + const width = imageSource.getImageProperty("ImageWidth"); + console.info('The new imageWidth is ' + width); + }) + ``` diff --git a/en/application-dev/media/image-transformation.md b/en/application-dev/media/image-transformation.md new file mode 100644 index 0000000000000000000000000000000000000000..8965d409dda0fa9271feebb34b3b936c4b624bc6 --- /dev/null +++ b/en/application-dev/media/image-transformation.md @@ -0,0 +1,93 @@ +# Image Transformation + +Image processing refers to a series of operations performed on the pixel map, such as obtaining image information, cropping, scaling, translating, rotating, flipping, setting opacity, and reading and writing pixel data. These operations can be classified into image transformation and [pixel map operation](image-pixelmap-operation.md). This topic describes the image transformation operations that you can perform. + +## How to Develop + +Read [Image](../reference/apis/js-apis-image.md#pixelmap7) for APIs related to image transformation. + +1. Complete [image decoding](image-decoding.md#how-to-develop) and obtain a **PixelMap** object. + +2. Obtain image information. + + ``` + // Obtain the image size. + pixelMap.getImageInfo().then( info => { + console.info('info.width = ' + info.size.width); + console.info('info.height = ' + info.size.height); + }).catch((err) => { + console.error("Failed to obtain the image pixel map information.And the error is: " + err); + }); + ``` + +3. Perform image transformation. + + Original image: + + ![Original drawing](figures/original-drawing.jpeg) + - Crop the image. + + ``` + // x: x-axis coordinate of the start point for cropping (0). + // y: y-axis coordinate of the start point for cropping (0). + // height: height after cropping (400), cropping from top to bottom. + // width: width after cropping (400), cropping from left to right. + pixelMap.crop({x: 0, y: 0, size: { height: 400, width: 400 } }); + ``` + + ![cropping](figures/cropping.jpeg) + + - Scale the image. + + ``` + // The width of the image after scaling is 0.5 of the original width. + // The height of the image after scaling is 0.5 of the original height. + pixelMap.scale(0.5, 0.5); + ``` + + ![zoom](figures/zoom.jpeg) + + - Translate the image. + + ``` + // Translate the image by 100 units downwards. + // Translate the image by 100 units to the right. + pixelMap.translate(100, 100); + ``` + + ![offsets](figures/offsets.jpeg) + + - Rotate the image. + + ``` + // Rate the image clockwise by 90°. + pixelMap.rotate(90); + ``` + + ![rotate](figures/rotate.jpeg) + + - Flip the image. + + ``` + // Flip the image vertically. + pixelMap.flip(false, true); + ``` + + ![Vertical Flip](figures/vertical-flip.jpeg) + + + ``` + // Flip the image horizontally. + pixelMap.flip(true, false); + ``` + + ![Horizontal Flip](figures/horizontal-flip.jpeg) + + - Set the opacity of the image. + + ``` + // Set the opacity to 0.5. + pixelMap.opacity(0.5); + ``` + + ![Transparency](figures/transparency.png) diff --git a/en/application-dev/media/image.md b/en/application-dev/media/image.md deleted file mode 100644 index fb4e648b56839ef76cb0e5277443605734d7ab6f..0000000000000000000000000000000000000000 --- a/en/application-dev/media/image.md +++ /dev/null @@ -1,283 +0,0 @@ -# Image Development - -## When to Use - -You can use image development APIs to decode images into pixel maps and encode the pixel maps into a supported format. - -## Available APIs - -For details about the APIs, see [Image Processing](../reference/apis/js-apis-image.md). - -## How to Develop - -### Full-Process Scenario - -The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources. - -```js -const color = new ArrayBuffer(96); // Create a buffer to store image pixel data. -let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data. - -// Create a PixelMap object. -image.createPixelMap(color, opts, (err, pixelmap) => { - console.log('Succeeded in creating pixelmap.'); - // Failed to create the PixelMap object. - if (err) { - console.info('create pixelmap failed, err' + err); - return - } - - // Read pixels. - const area = { - pixels: new ArrayBuffer(8), - offset: 0, - stride: 8, - region: { size: { height: 1, width: 2 }, x: 0, y: 0 } - } - pixelmap.readPixels(area,() => { - let bufferArr = new Uint8Array(area.pixels); - let res = true; - for (let i = 0; i < bufferArr.length; i++) { - console.info(' buffer ' + bufferArr[i]); - if(res) { - if(bufferArr[i] == 0) { - res = false; - console.log('readPixels end.'); - break; - } - } - } - }) - - // Store pixels. - const readBuffer = new ArrayBuffer(96); - pixelmap.readPixelsToBuffer(readBuffer,() => { - let bufferArr = new Uint8Array(readBuffer); - let res = true; - for (let i = 0; i < bufferArr.length; i++) { - if(res) { - if (bufferArr[i] !== 0) { - res = false; - console.log('readPixelsToBuffer end.'); - break; - } - } - } - }) - - // Write pixels. - pixelmap.writePixels(area,() => { - const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} - pixelmap.readPixels(readArea,() => { - let readArr = new Uint8Array(readArea.pixels); - let res = true; - for (let i = 0; i < readArr.length; i++) { - if(res) { - if (readArr[i] !== 0) { - res = false; - console.log('readPixels end.please check buffer'); - break; - } - } - } - }) - }) - - const writeColor = new ArrayBuffer(96); // Pixel data of the image. - // Write pixels to the buffer. - pixelmap.writeBufferToPixels(writeColor).then(() => { - const readBuffer = new ArrayBuffer(96); - pixelmap.readPixelsToBuffer(readBuffer).then (() => { - let bufferArr = new Uint8Array(readBuffer); - let res = true; - for (let i = 0; i < bufferArr.length; i++) { - if(res) { - if (bufferArr[i] !== i) { - res = false; - console.log('readPixels end.please check buffer'); - break; - } - } - } - }) - }) - - // Obtain image information. - pixelmap.getImageInfo((err, imageInfo) => { - // Failed to obtain the image information. - if (err || imageInfo == null) { - console.info('getImageInfo failed, err' + err); - return - } - if (imageInfo !== null) { - console.log('Succeeded in getting imageInfo'); - } - }) - - // Release the PixelMap object. - pixelmap.release(()=>{ - console.log('Succeeded in releasing pixelmap'); - }) -}) - -// Create an image source (uri). -let path = '/data/local/tmp/test.jpg'; -const imageSourceApi1 = image.createImageSource(path); - -// Create an image source (fd). -let fd = 29; -const imageSourceApi2 = image.createImageSource(fd); - -// Create an image source (data). -const data = new ArrayBuffer(96); -const imageSourceApi3 = image.createImageSource(data); - -// Release the image source. -imageSourceApi3.release(() => { - console.log('Succeeded in releasing imagesource'); -}) - -// Encode the image. -const imagePackerApi = image.createImagePacker(); -const imageSourceApi = image.createImageSource(0); -let packOpts = { format:"image/jpeg", quality:98 }; -imagePackerApi.packing(imageSourceApi, packOpts, (err, data) => { - if (err) { - console.info('packing from imagePackerApi failed, err' + err); - return - } - console.log('Succeeded in packing'); -}) - -// Release the ImagePacker object. -imagePackerApi.release(); -``` - -### Decoding Scenario - -```js -let path = '/data/local/tmp/test.jpg'; // Set the path for creating an image source. - -// Create an image source using a path. -const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg' - -// Set parameters. -let decodingOptions = { - sampleSize:1, // Sampling size of the thumbnail. - editable: true, // Whether the image can be edited. - desiredSize:{ width:1, height:2}, // Desired output size of the image. - rotateDegrees:10, // Rotation angle of the image. - desiredPixelFormat:2, // Decoded pixel format. - desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 }, // Region of the image to decode. - index:0// Image sequence number. - }; - -// Create a pixel map in callback mode. -imageSourceApi.createPixelMap(decodingOptions, (err, pixelmap) => { - // Failed to create the PixelMap object. - if (err) { - console.info('create pixelmap failed, err' + err); - return - } - console.log('Succeeded in creating pixelmap.'); -}) - -// Create a pixel map in promise mode. -imageSourceApi.createPixelMap().then(pixelmap => { - console.log('Succeeded in creating pixelmap.'); - - // Obtain the number of bytes in each line of pixels. - let num = pixelmap.getBytesNumberPerRow(); - - // Obtain the total number of pixel bytes. - let pixelSize = pixelmap.getPixelBytesNumber(); - - // Obtain the pixel map information. - pixelmap.getImageInfo().then( imageInfo => {}); - - // Release the PixelMap object. - pixelmap.release(()=>{ - console.log('Succeeded in releasing pixelmap'); - }) -}).catch(error => { - console.log('Failed in creating pixelmap.' + error); -}) -``` - -### Encoding Scenario - -```js -let path = '/data/local/tmp/test.png' // Set the path for creating an image source. - -// Set the image source. -const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.png' - -// Print the error message if the image source fails to be created. -if (imageSourceApi == null) { - console.log('Failed in creating imageSource.'); -} - -// Create an image packer if the image source is successfully created. -const imagePackerApi = image.createImagePacker(); - -// Print the error information if the image packer fails to be created. -if (imagePackerApi == null) { - console.log('Failed in creating imagePacker.'); -} - -// Set encoding parameters if the image packer is successfully created. -let packOpts = { format:"image/jpeg", // The supported encoding format is jpg. - quality:98 } // Image quality, which ranges from 0 to 100. - -// Encode the image. -imagePackerApi.packing(imageSourceApi, packOpts) -.then( data => { - console.log('Succeeded in packing'); -}) - -// Release the image packer after the encoding is complete. -imagePackerApi.release(); - -// Obtain the image source information. -imageSourceApi.getImageInfo((err, imageInfo) => { - console.log('Succeeded in getting imageInfo'); -}) - -const array = new ArrayBuffer(100); // Incremental data. -// Update incremental data. -imageSourceApi.updateData(array, false, 0, 10,(error, data)=> {}) - -``` - -### Using ImageReceiver - -Example scenario: The camera functions as the client to transmit image data to the server. - -```js -public async init(surfaceId: any) { - - // (Server code) Create an ImageReceiver object. - let receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1); - - // Obtain the surface ID. - receiver.getReceivingSurfaceId((err, surfaceId) => { - // Failed to obtain the surface ID. - if (err) { - console.info('getReceivingSurfaceId failed, err' + err); - return - } - console.info("receiver getReceivingSurfaceId success"); - }); - // Register a surface listener, which is triggered after the buffer of the surface is ready. - receiver.on('imageArrival', () => { - // Obtain the latest buffer of the surface. - receiver.readNextImage((err, img) => { - img.getComponent(4, (err, component) => { - // Consume component.byteBuffer. For example, save the content in the buffer as an image. - }) - }) - }) - - // Call a Camera API to transfer the surface ID to the camera, which then obtains the surface based on the surface ID and generates a surface buffer. -} -``` diff --git a/en/application-dev/media/local-avsession-overview.md b/en/application-dev/media/local-avsession-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..2ced0a180e3bed3a1adea4e4b3ff196721bc23a8 --- /dev/null +++ b/en/application-dev/media/local-avsession-overview.md @@ -0,0 +1,63 @@ +# Local AVSession Overview + +## Interaction Process + +For a local AVSession, the data sources are on the local device. The figure below illustrates the interaction process. + +![Local AVSession Interaction Process](figures/local-avsession-interaction-process.png) + +This process involves two roles: provider and controller. + +In the local AVSession, the provider exchanges information with the controller through AVSessionManager. + +1. The provider creates an **AVSession** object through AVSessionManager. + +2. Through the **AVSession** object, the provider sets session metadata (such as the asset ID, title, and duration) and playback attributes (such as the playback state, speed, and position). + +3. The controller creates an **AVSessionController** object through AVSessionManager. + +4. Through the **AVSessionController** object, the controller listens for changes of the session metadata and playback attributes. + +5. Through the **AVSessionController** object, the controller sends control commands to the **AVSession** object. + +6. Through the **AVSession** object, the provider listens for the control commands, for example, play, playNext, fastForward, and setSpeed, from the controller. + +## AVSessionManager + +AVSessionManager provides the capability of managing sessions. It can create an **AVSession** object, create an **AVSessionController** object, send control commands, and listen for session state changes. + +Unlike the **AVSession** and **AVSessionController** objects, AVSessionManager is not a specific object, but the root namespace of AVSessions. You can import AVSessionManager as follows: + +```ts +import AVSessionManager from '@ohos.multimedia.avsession'; +``` + +All the APIs in the root namespace can be used as APIs of AVSessionManager. + +The code snippet below shows how the provider creates an **AVSession** object by using AVSessionManager: + +```ts +// Create an AVSession object. +async createSession() { + let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(this.context, 'SESSION_NAME', 'audio'); + console.info(`session create done : sessionId : ${session.sessionId}`); +} +``` + +The code snippet below shows how the controller creates an **AVSessionController** object by using AVSessionManager: + +```ts +// Create an AVSessionController object. +async createController() { + // Obtain the descriptors of all live AVSession objects. + let descriptorsArray: Array> = await AVSessionManager.getAllSessionDescriptors(); + if (descriptorsArray.length > 0) { + // For demonstration, the session ID of the first descriptor is used to create the AVSessionController object. + let sessionId: string = descriptorsArray[0].sessionId; + let avSessionController: AVSessionManager.AVSessionController = await AVSessionManager.createController(sessionId); + console.info(`controller create done : sessionId : ${avSessionController.sessionId}`); + } +} +``` + +For more information about AVSessionManager APIs, see [API Reference](../reference/apis/js-apis-avsession.md). diff --git a/en/application-dev/media/media-application-overview.md b/en/application-dev/media/media-application-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d350482e61e7bc9659054b0426c10ce07da88045 --- /dev/null +++ b/en/application-dev/media/media-application-overview.md @@ -0,0 +1,19 @@ +# Media Application Development Overview + +## Multimedia Subsystem Architecture + +The multimedia subsystem provides the capability of processing users' visual and auditory information. For example, it can be used to collect, compress, store, decompress, and play audio and video information. Based on the type of media information to process, the media system is usually divided into four modules: audio, media, camera, and image. + +As shown in the figure below, the multimedia subsystem provides APIs for developing audio/video, camera, and gallery applications, and provides adaptation and acceleration for different hardware chips. In the middle part, it provides core media functionalities and management mechanisms in the form of services. + +**Figure 1** Overall framework of the multimedia subsystem + +![Multimedia subsystem framework](figures/media-system-framework.png) + +- Audio module: provides interfaces and services for volume management, audio route management, and audio mixing management. + +- Media module: provides interfaces and services for audio and video decompression, playback, compression, and recording. + +- Camera module: provides interfaces and services for accurately controlling camera lenses and collecting visual information. + +- Image module: provides interfaces and services for image encoding, decoding, and processing. diff --git a/en/application-dev/media/mic-management.md b/en/application-dev/media/mic-management.md new file mode 100644 index 0000000000000000000000000000000000000000..952aeef3f3c607d3a2132eb6d1e0ab6bdd4490c9 --- /dev/null +++ b/en/application-dev/media/mic-management.md @@ -0,0 +1,114 @@ +# Microphone Management + +The microphone is used to record audio data. To deliver an optimal recording effect, you are advised to query the microphone state before starting recording and listen for state changes during recording. + +If the user mutes the microphone during audio recording, the recording process is normal, the size of the recorded file increases with the recording duration, but the data volume written into the file is 0. + +## How to Develop + +The **AudioVolumeGroupManager** class provides APIs for managing the microphone state. For details, see [API Reference](../reference/apis/js-apis-audio.md#audiovolumegroupmanager9). + +1. Create an **audioVolumeGroupManager** object. + + ```ts + import audio from '@ohos.multimedia.audio'; + + let audioVolumeGroupManager; + async function loadVolumeGroupManager() { // Create an audioVolumeGroupManager object. + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + ``` + +2. Call **on('micStateChange')** to listen for microphone state changes. When the microphone state changes, the application will be notified of the change. + + Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + + + ```ts + async function on() { // Subscribe to microphone state changes. + audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); + }); + } + ``` + +3. Call **isMicrophoneMute** to check whether the microphone is muted. If the returned value is **true**, the microphone is muted; otherwise, the microphone is not muted. + + ```ts + async function isMicrophoneMute() { // Check whether the microphone is muted. + await audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`isMicrophoneMute is: ${value}.`); + }); + } + ``` + +4. Call **setMicrophoneMute** to mute or unmute the microphone. To mute the microphone, pass in **true**. To unmute the microphone, pass in **false**. + + ```ts + async function setMicrophoneMuteTrue() { // Pass in true to mute the microphone. + await audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('setMicrophoneMute to mute.'); + }); + } + async function setMicrophoneMuteFalse() { // Pass in false to unmute the microphone. + await audioVolumeGroupManager.setMicrophoneMute(false).then(() => { + console.info('setMicrophoneMute to not mute.'); + }); + } + ``` + +## Sample Code + +Refer to the sample code below to complete the process of muting and unmuting the microphone. + +```ts +import audio from '@ohos.multimedia.audio'; + +@Entry +@Component +struct AudioVolumeGroup { + private audioVolumeGroupManager: audio.AudioVolumeGroupManager; + + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + this.audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager------create-------success.'); + } + + async on() { // Subscribe to microphone state changes. + await this.loadVolumeGroupManager(); + this.audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); + }); + } + async isMicrophoneMute() { // Check whether the microphone is muted. + await this.audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`isMicrophoneMute is: ${value}.`); + }); + } + async setMicrophoneMuteTrue() { // Mute the microphone. + await this.loadVolumeGroupManager(); + await this.audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('setMicrophoneMute to mute.'); + }); + } + async setMicrophoneMuteFalse() { // Unmute the microphone. + await this.loadVolumeGroupManager(); + await this.audioVolumeGroupManager.setMicrophoneMute(false).then(() => { + console.info('setMicrophoneMute to not mute.'); + }); + } + async test(){ + await this.on(); + await this.isMicrophoneMute(); + await this.setMicrophoneMuteTrue(); + await this.isMicrophoneMute(); + await this.setMicrophoneMuteFalse(); + await this.isMicrophoneMute(); + await this.setMicrophoneMuteTrue(); + await this.isMicrophoneMute(); + } +} +``` diff --git a/en/application-dev/media/opensles-capture.md b/en/application-dev/media/opensles-capture.md deleted file mode 100644 index 3c33b37076ac14d98b550ba7b1a7e36bfe1cb048..0000000000000000000000000000000000000000 --- a/en/application-dev/media/opensles-capture.md +++ /dev/null @@ -1,151 +0,0 @@ -# OpenSL ES Audio Recording Development - -## Introduction - -You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. - -## How to Develop - -To use OpenSL ES to develop the audio recording function in OpenHarmony, perform the following steps: - -1. Add the header files. - - ```c++ - #include - #include - #include - ``` - -2. Use the **slCreateEngine** API to create and instantiate the **engine** instance. - - ```c++ - SLObjectItf engineObject = nullptr; - slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr); - (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); - ``` - -3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. - - ```c++ - SLEngineItf engineItf = nullptr; - result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf); - ``` - -4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance. - - ```c++ - SLDataLocator_IODevice io_device = { - SL_DATALOCATOR_IODEVICE, - SL_IODEVICE_AUDIOINPUT, - SL_DEFAULTDEVICEID_AUDIOINPUT, - NULL - }; - - SLDataSource audioSource = { - &io_device, - NULL - }; - - SLDataLocator_BufferQueue buffer_queue = { - SL_DATALOCATOR_BUFFERQUEUE, - 3 - }; - - // Configure the parameters based on the audio file format. - SLDataFormat_PCM format_pcm = { - SL_DATAFORMAT_PCM, // Input audio format. - 1, // Mono channel. - SL_SAMPLINGRATE_44_1, // Sampling rate, 44100 Hz. - SL_PCMSAMPLEFORMAT_FIXED_16, // Audio sampling format, a signed 16-bit integer in little-endian format. - 0, - 0, - 0 - }; - - SLDataSink audioSink = { - &buffer_queue, - &format_pcm - }; - - SLObjectItf pcmCapturerObject = nullptr; - result = (*engineItf)->CreateAudioRecorder(engineItf, &pcmCapturerObject, - &audioSource, &audioSink, 0, nullptr, nullptr); - (*pcmCapturerObject)->Realize(pcmCapturerObject, SL_BOOLEAN_FALSE); - ``` - -5. Obtain the **recordItf** instance of the **SL_IID_RECORD** interface. - - ```c++ - SLRecordItf recordItf; - (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf); - ``` - -6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. - - ```c++ - SLOHBufferQueueItf bufferQueueItf; - (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); - ``` - -7. Register the **BufferQueueCallback** function. - - ```c++ - static void BufferQueueCallback(SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) - { - AUDIO_INFO_LOG("BufferQueueCallback"); - FILE *wavFile = (FILE *)pContext; - if (wavFile != nullptr) { - SLuint8 *buffer = nullptr; - SLuint32 pSize = 0; - (*bufferQueueItf)->GetBuffer(bufferQueueItf, &buffer, pSize); - if (buffer != nullptr) { - fwrite(buffer, 1, pSize, wavFile); - (*bufferQueueItf)->Enqueue(bufferQueueItf, buffer, size); - } - } - - return; - } - - // Set wavFile_ to the descriptor of the file to be recorded. - (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); - ``` - -8. Start audio recording. - - ```c++ - static void CaptureStart(SLRecordItf recordItf, SLOHBufferQueueItf bufferQueueItf, FILE *wavFile) - { - AUDIO_INFO_LOG("CaptureStart"); - (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_RECORDING); - if (wavFile != nullptr) { - SLuint8* buffer = nullptr; - SLuint32 pSize = 0; - (*bufferQueueItf)->GetBuffer(bufferQueueItf, &buffer, pSize); - if (buffer != nullptr) { - AUDIO_INFO_LOG("CaptureStart, enqueue buffer length: %{public}lu.", pSize); - fwrite(buffer, 1, pSize, wavFile); - (*bufferQueueItf)->Enqueue(bufferQueueItf, buffer, pSize); - } else { - AUDIO_INFO_LOG("CaptureStart, buffer is null or pSize: %{public}lu.", pSize); - } - } - - return; - } - ``` - -9. Stop audio recording. - - ```c++ - static void CaptureStop(SLRecordItf recordItf) - { - AUDIO_INFO_LOG("Enter CaptureStop"); - fflush(wavFile_); - (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED); - (*pcmCapturerObject)->Destroy(pcmCapturerObject); - fclose(wavFile_); - wavFile_ = nullptr; - return; - } - ``` diff --git a/en/application-dev/media/opensles-playback.md b/en/application-dev/media/opensles-playback.md deleted file mode 100644 index fe89bc9553da3163e1e18ca43922ff99e13c1307..0000000000000000000000000000000000000000 --- a/en/application-dev/media/opensles-playback.md +++ /dev/null @@ -1,104 +0,0 @@ -# OpenSL ES Audio Playback Development - -## Introduction - -You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. - -## How to Develop - -To use OpenSL ES to develop the audio playback function in OpenHarmony, perform the following steps: - -1. Add the header files. - - ```c++ - #include - #include - #include - ``` - -2. Use the **slCreateEngine** API to obtain an **engine** instance. - - ```c++ - SLObjectItf engineObject = nullptr; - slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr); - (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); - ``` - -3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. - - ```c++ - SLEngineItf engineEngine = nullptr; - (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); - ``` - -4. Configure the player and create an **AudioPlayer** instance. - - ```c++ - SLDataLocator_BufferQueue slBufferQueue = { - SL_DATALOCATOR_BUFFERQUEUE, - 0 - }; - - // Configure the parameters based on the audio file format. - SLDataFormat_PCM pcmFormat = { - SL_DATAFORMAT_PCM, - 2, - 48000, - 16, - 0, - 0, - 0 - }; - SLDataSource slSource = {&slBufferQueue, &pcmFormat}; - - SLObjectItf pcmPlayerObject = nullptr; - (*engineEngine)->CreateAudioPlayer(engineEngine, &pcmPlayerObject, &slSource, null, 0, nullptr, nullptr); - (*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE); - ``` - -5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. - - ```c++ - SLOHBufferQueueItf bufferQueueItf; - (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); - ``` - -6. Open an audio file and register the **BufferQueueCallback** function. - - ```c++ - FILE *wavFile_ = nullptr; - - static void BufferQueueCallback (SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) - { - FILE *wavFile = (FILE *)pContext; - if (!feof(wavFile)) { - SLuint8 *buffer = nullptr; - SLuint32 pSize = 0; - (*bufferQueueItf)->GetBuffer(bufferQueueItf, &buffer, pSize); - // Read data from the file. - fread(buffer, 1, size, wavFile); - (*bufferQueueItf)->Enqueue(bufferQueueItf, buffer, size); - } - return; - } - - // Set wavFile_ to the descriptor of the file to be played. - wavFile_ = fopen(path, "rb"); - (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); - ``` - -7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback. - - ```c++ - SLPlayItf playItf = nullptr; - (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_PLAY, &playItf); - (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); - ``` - -8. Stop audio playback. - - ```c++ - (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); - (*pcmPlayerObject)->Destroy(pcmPlayerObject); - (*engineObject)->Destroy(engineObject); - ``` diff --git a/en/application-dev/media/remote-camera.md b/en/application-dev/media/remote-camera.md deleted file mode 100644 index d7bf710279c1504cd9703eca9af7cf5433cb3dac..0000000000000000000000000000000000000000 --- a/en/application-dev/media/remote-camera.md +++ /dev/null @@ -1,65 +0,0 @@ -# Distributed Camera Development - -## When to Use - -You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording. - -## How to Develop -Connect your calculator to a distributed device. Your calculator will call **getSupportedCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **cameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). - -For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). - -### Connecting to a Distributed Camera - -Connect the calculator and the distributed device to the same LAN. - -Open the calculator and click the arrow icon in the upper right corner. A new window is displayed. Enter the verification code as prompted, and the calculator will be connected to the distributed device. - -### Creating an Instance - -```js -import camera from '@ohos.multimedia.camera' -import image from '@ohos.multimedia.image' -import media from '@ohos.multimedia.media' -import featureAbility from '@ohos.ability.featureAbility' - -// Create a CameraManager object. -let cameraManager = camera.getCameraManager(globalThis.Context) -if (!cameraManager) { - console.error("camera.getCameraManager error") - return; -} - -// Register a callback to listen for camera status changes and obtain the updated camera status information. -cameraManager.on('cameraStatus', (cameraStatusInfo) => { - console.log('camera : ' + cameraStatusInfo.camera.cameraId); - console.log('status: ' + cameraStatusInfo.status); -}) - -// Obtain the camera list. -let remoteCamera -let cameraArray = cameraManager.getSupportedCameras(); -if (cameraArray.length <= 0) { - console.error("cameraManager.getSupportedCameras error") - return; -} - -for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { - console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. - console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. - console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. - console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type. - if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) { - remoteCamera = cameraArray[cameraIndex] - } -} - -// Create a camera input stream. -let cameraInput -try { - cameraInput = cameraManager.createCameraInput(remoteCamera); -} catch () { - console.error('Failed to createCameraInput errorCode = ' + error.code); -} -``` -For details about the subsequent steps, see [Camera Development](./camera.md). diff --git a/en/application-dev/media/using-audiocapturer-for-recording.md b/en/application-dev/media/using-audiocapturer-for-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..87d13fa3f749cb18ba1c9d61843b750a36a1bcad --- /dev/null +++ b/en/application-dev/media/using-audiocapturer-for-recording.md @@ -0,0 +1,211 @@ +# Using AudioCapturer for Audio Recording + +The AudioCapturer is used to record Pulse Code Modulation (PCM) audio data. It is suitable if you have extensive audio development experience and want to implement more flexible recording features. + +## Development Guidelines + +The full recording process involves creating an **AudioCapturer** instance, configuring audio recording parameters, starting and stopping recording, and releasing the instance. In this topic, you will learn how to use the AudioCapturer to recording audio data. Before the development, you are advised to read [AudioCapturer](../reference/apis/js-apis-audio.md#audiocapturer8) for the API reference. + +The figure below shows the state changes of the AudioCapturer. After an **AudioCapturer** instance is created, different APIs can be called to switch the AudioCapturer to different states and trigger the required behavior. If an API is called when the AudioCapturer is not in the given state, the system may throw an exception or generate other undefined behavior. Therefore, you are advised to check the AudioCapturer state before triggering state transition. + +**Figure 1** AudioCapturer state transition +![AudioCapturer state change](figures/audiocapturer-status-change.png) + +You can call **on('stateChange')** to listen for state changes. For details about each state, see [AudioState](../reference/apis/js-apis-audio.md#audiostate8). + +### How to Develop + +1. Set audio recording parameters and create an **AudioCapturer** instance. For details about the parameters, see [AudioCapturerOptions](../reference/apis/js-apis-audio.md#audiocaptureroptions8). + + ```ts + import audio from '@ohos.multimedia.audio'; + + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + }; + + let audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 + }; + + let audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + }; + + audio.createAudioCapturer(audioCapturerOptions, (err, data) => { + if (err) { + console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Invoke createAudioCapturer succeeded.'); + let audioCapturer = data; + } + }); + ``` + +2. Call **start()** to switch the AudioCapturer to the **running** state and start recording. + + ```ts + audioCapturer.start((err) => { + if (err) { + console.error(`Capturer start failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Capturer start success.'); + } + }); + ``` + +3. Specify the recording file path and call **read()** to read the data in the buffer. + + ```ts + let file = fs.openSync(path, 0o2 | 0o100); + let bufferSize = await audioCapturer.getBufferSize(); + let buffer = await audioCapturer.read(bufferSize, true); + fs.writeSync(file.fd, buffer); + ``` + +4. Call **stop()** to stop recording. + + ```ts + audioCapturer.stop((err) => { + if (err) { + console.error(`Capturer stop failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Capturer stopped.'); + } + }); + ``` + +5. Call **release()** to release the instance. + + ```ts + audioCapturer.release((err) => { + if (err) { + console.error(`capturer release failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('capturer released.'); + } + }); + ``` + + +### Sample Code + +Refer to the sample code below to record audio using AudioCapturer. + +```ts +import audio from '@ohos.multimedia.audio'; +import fs from '@ohos.file.fs'; + +const TAG = 'AudioCapturerDemo'; + +export default class AudioCapturerDemo { + private audioCapturer = undefined; + private audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + private audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type. + capturerFlags: 0 // Flag indicating an AudioCapturer. + } + private audioCapturerOptions = { + streamInfo: this.audioStreamInfo, + capturerInfo: this.audioCapturerInfo + } + + // Create an AudioCapturer instance, and set the events to listen for. + init() { + audio.createAudioCapturer(this.audioCapturerOptions, (err, capturer) => { // Create an AudioCapturer instance. + if (err) { + console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`); + return; + } + + console.info(`${TAG}: create AudioCapturer success`); + this.audioCapturer = capturer; + this.audioCapturer.on('markReach', 1000, (position) => { // Subscribe to the markReach event. A callback is triggered when the number of captured frames reaches 1000. + if (position === 1000) { + console.info('ON Triggered successfully'); + } + }); + this.audioCapturer.on('periodReach', 2000, (position) => { // Subscribe to the periodReach event. A callback is triggered when the number of captured frames reaches 2000. + if (position === 2000) { + console.info('ON Triggered successfully'); + } + }); + + }); + } + + // Start audio recording. + async start() { + let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; + if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // Recording can be started only when the AudioCapturer is in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state. + console.error(`${TAG}: start failed`); + return; + } + await this.audioCapturer.start(); // Start recording. + + let context = getContext(this); + const path = context.filesDir + '/test.wav'; // Path for storing the recorded audio file. + + let file = fs.openSync(path, 0o2 | 0o100); // Create the file if it does not exist. + let fd = file.fd; + let numBuffersToCapture = 150; // Write data for 150 times. + let count = 0; + while (numBuffersToCapture) { + let bufferSize = await this.audioCapturer.getBufferSize(); + let buffer = await this.audioCapturer.read(bufferSize, true); + let options = { + offset: count * bufferSize, + length: bufferSize + }; + if (buffer === undefined) { + console.error(`${TAG}: read buffer failed`); + } else { + let number = fs.writeSync(fd, buffer, options); + console.info(`${TAG}: write date: ${number}`); + } + numBuffersToCapture--; + count++; + } + } + + // Stop recording. + async stop() { + // The AudioCapturer can be stopped only when it is in the STATE_RUNNING or STATE_PAUSED state. + if (this.audioCapturer.state !== audio.AudioState.STATE_RUNNING && this.audioCapturer.state !== audio.AudioState.STATE_PAUSED) { + console.info('Capturer is not running or paused'); + return; + } + await this.audioCapturer.stop(); // Stop recording. + if (this.audioCapturer.state === audio.AudioState.STATE_STOPPED) { + console.info('Capturer stopped'); + } else { + console.error('Capturer stop failed'); + } + } + + // Release the instance. + async release() { + // The AudioCapturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. + if (this.audioCapturer.state === audio.AudioState.STATE_RELEASED || this.audioCapturer.state === audio.AudioState.STATE_NEW) { + console.info('Capturer already released'); + return; + } + await this.audioCapturer.release(); // Release the instance. + if (this.audioCapturer.state == audio.AudioState.STATE_RELEASED) { + console.info('Capturer released'); + } else { + console.error('Capturer release failed'); + } + } +} +``` diff --git a/en/application-dev/media/using-audiorenderer-for-playback.md b/en/application-dev/media/using-audiorenderer-for-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..11934e669813fa7a89ceef43bd2c3795db6bad75 --- /dev/null +++ b/en/application-dev/media/using-audiorenderer-for-playback.md @@ -0,0 +1,268 @@ +# Using AudioRenderer for Audio Playback + +The AudioRenderer is used to play Pulse Code Modulation (PCM) audio data. Unlike the AVPlayer, the AudioRenderer can perform data preprocessing before audio input. Therefore, the AudioRenderer is more suitable if you have extensive audio development experience and want to implement more flexible playback features. + +## Development Guidelines + +The full rendering process involves creating an **AudioRenderer** instance, configuring audio rendering parameters, starting and stopping rendering, and releasing the instance. In this topic, you will learn how to use the AudioRenderer to render audio data. Before the development, you are advised to read [AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8) for the API reference. + +The figure below shows the state changes of the AudioRenderer. After an **AudioRenderer** instance is created, different APIs can be called to switch the AudioRenderer to different states and trigger the required behavior. If an API is called when the AudioRenderer is not in the given state, the system may throw an exception or generate other undefined behavior. Therefore, you are advised to check the AudioRenderer state before triggering state transition. + +To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the callback functions. + +**Figure 1** AudioRenderer state transition + +![AudioRenderer state transition](figures/audiorenderer-status-change.png) + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the AudioRenderer. This is because some operations can be performed only when the AudioRenderer is in a given state. If the application performs an operation when the AudioRenderer is not in the given state, the system may throw an exception or generate other undefined behavior. + +- **prepared**: The AudioRenderer enters this state by calling **createAudioRenderer()**. + +- **running**: The AudioRenderer enters this state by calling **start()** when it is in the **prepared**, **paused**, or **stopped** state. + +- **paused**: The AudioRenderer enters this state by calling **pause()** when it is in the **running** state. When the audio playback is paused, it can call **start()** to resume the playback. + +- **stopped**: The AudioRenderer enters this state by calling **stop()** when it is in the **paused** or **running** state + +- **released**: The AudioRenderer enters this state by calling **release()** when it is in the **prepared**, **paused**, or **stopped** state. In this state, the AudioRenderer releases all occupied hardware and software resources and will not transit to any other state. + +### How to Develop + +1. Set audio rendering parameters and create an **AudioRenderer** instance. For details about the parameters, see [AudioRendererOptions](../reference/apis/js-apis-audio.md#audiorendereroptions8). + + ```ts + import audio from '@ohos.multimedia.audio'; + + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + }; + + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 0 + }; + + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + }; + + audio.createAudioRenderer(audioRendererOptions, (err, data) => { + if (err) { + console.error(`Invoke createAudioRenderer failed, code is ${err.code}, message is ${err.message}`); + return; + } else { + console.info('Invoke createAudioRenderer succeeded.'); + let audioRenderer = data; + } + }); + ``` + +2. Call **start()** to switch the AudioRenderer to the **running** state and start rendering. + + ```ts + audioRenderer.start((err) => { + if (err) { + console.error(`Renderer start failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Renderer start success.'); + } + }); + ``` + +3. Specify the address of the file to render. Open the file and call **write()** to continuously write audio data to the buffer for rendering and playing. To implement personalized playback, process the audio data before writing it. + + ```ts + const bufferSize = await audioRenderer.getBufferSize(); + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + let buf = new ArrayBuffer(bufferSize); + let readsize = await fs.read(file.fd, buf); + let writeSize = await new Promise((resolve, reject) => { + audioRenderer.write(buf, (err, writeSize) => { + if (err) { + reject(err); + } else { + resolve(writeSize); + } + }); + }); + ``` + +4. Call **stop()** to stop rendering. + + ```ts + audioRenderer.stop((err) => { + if (err) { + console.error(`Renderer stop failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Renderer stopped.'); + } + }); + ``` + +5. Call **release()** to release the instance. + + ```ts + audioRenderer.release((err) => { + if (err) { + console.error(`Renderer release failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info('Renderer released.'); + } + }); + ``` + +### Sample Code + +Refer to the sample code below to render an audio file using AudioRenderer. + +```ts +import audio from '@ohos.multimedia.audio'; +import fs from '@ohos.file.fs'; + +const TAG = 'AudioRendererDemo'; + +export default class AudioRendererDemo { + private renderModel = undefined; + private audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. + channels: audio.AudioChannel.CHANNEL_2, // Channel. + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. + } + private audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, // Media type. + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, // Audio stream usage type. + rendererFlags: 0 // AudioRenderer flag. + } + private audioRendererOptions = { + streamInfo: this.audioStreamInfo, + rendererInfo: this.audioRendererInfo + } + + // Create an AudioRenderer instance, and set the events to listen for. + init() { + audio.createAudioRenderer(this.audioRendererOptions, (err, renderer) => { // Create an AudioRenderer instance. + if (!err) { + console.info(`${TAG}: creating AudioRenderer success`); + this.renderModel = renderer; + this.renderModel.on('stateChange', (state) => { // Set the events to listen for. A callback is invoked when the AudioRenderer is switched to the specified state. + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); + } + }); + this.renderModel.on('markReach', 1000, (position) => { // Subscribe to the markReach event. A callback is triggered when the number of rendered frames reaches 1000. + if (position == 1000) { + console.info('ON Triggered successfully'); + } + }); + } else { + console.info(`${TAG}: creating AudioRenderer failed, error: ${err.message}`); + } + }); + } + + // Start audio rendering. + async start() { + let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; + if (stateGroup.indexOf(this.renderModel.state) === -1) { // Rendering can be started only when the AudioRenderer is in the prepared, paused, or stopped state. + console.error(TAG + 'start failed'); + return; + } + await this.renderModel.start(); // Start rendering. + + const bufferSize = await this.renderModel.getBufferSize(); + let context = getContext(this); + let path = context.filesDir; + const filePath = path + '/test.wav'; // Use the sandbox path to obtain the file. The actual file path is /data/storage/el2/base/haps/entry/files/test.wav. + + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + let stat = await fs.stat(filePath); + let buf = new ArrayBuffer(bufferSize); + let len = stat.size % bufferSize === 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); + for (let i = 0; i < len; i++) { + let options = { + offset: i * bufferSize, + length: bufferSize + }; + let readsize = await fs.read(file.fd, buf, options); + + // buf indicates the audio data to be written to the buffer. Before calling AudioRenderer.write(), you can preprocess the audio data for personalized playback. The AudioRenderer reads the audio data written to the buffer for rendering. + + let writeSize = await new Promise((resolve, reject) => { + this.renderModel.write(buf, (err, writeSize) => { + if (err) { + reject(err); + } else { + resolve(writeSize); + } + }); + }); + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { // The rendering stops if the AudioRenderer is in the released state. + fs.close(file); + await this.renderModel.stop(); + } + if (this.renderModel.state === audio.AudioState.STATE_RUNNING) { + if (i === len - 1) { // The rendering stops if the file finishes reading. + fs.close(file); + await this.renderModel.stop(); + } + } + } + } + + // Pause the rendering. + async pause() { + // Rendering can be paused only when the AudioRenderer is in the running state. + if (this.renderModel.state !== audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + await this.renderModel.pause(); // Pause rendering. + if (this.renderModel.state === audio.AudioState.STATE_PAUSED) { + console.info('Renderer is paused.'); + } else { + console.error('Pausing renderer failed.'); + } + } + + // Stop rendering. + async stop() { + // Rendering can be stopped only when the AudioRenderer is in the running or paused state. + if (this.renderModel.state !== audio.AudioState.STATE_RUNNING && this.renderModel.state !== audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused.'); + return; + } + await this.renderModel.stop(); // Stop rendering. + if (this.renderModel.state === audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped.'); + } else { + console.error('Stopping renderer failed.'); + } + } + + // Release the instance. + async release() { + // The AudioRenderer can be released only when it is not in the released state. + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { + console.info('Renderer already released'); + return; + } + await this.renderModel.release(); // Release the instance. + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.error('Renderer release failed.'); + } + } +} +``` + +When audio streams with the same or higher priority need to use the output device, the current audio playback will be interrupted. The application can respond to and handle the interruption event. For details about how to process concurrent audio playback, see [Audio Playback Concurrency Policies](audio-playback-concurrency.md). diff --git a/en/application-dev/media/using-avplayer-for-playback.md b/en/application-dev/media/using-avplayer-for-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..6cb6ab1e67ef0ae8a44e04fa915ad87bcc9ed024 --- /dev/null +++ b/en/application-dev/media/using-avplayer-for-playback.md @@ -0,0 +1,167 @@ +# Using AVPlayer for Audio Playback + +The AVPlayer is used to play raw media assets in an end-to-end manner. In this topic, you will learn how to use the AVPlayer to play a complete piece of music. + +If you want the application to continue playing the music in the background or when the screen is off, you must use the [AVSession](avsession-overview.md) and [continuous task](../task-management/continuous-task-dev-guide.md) to prevent the playback from being forcibly interrupted by the system. + + +The full playback process includes creating an **AVPlayer** instance, setting the media asset to play, setting playback parameters (volume, speed, and focus mode), controlling playback (play, pause, seek, and stop), resetting the playback configuration, and releasing the instance. + + +During application development, you can use the **state** attribute of the AVPlayer to obtain the AVPlayer state or call **on('stateChange')** to listen for state changes. If the application performs an operation when the AVPlayer is not in the given state, the system may throw an exception or generate other undefined behavior. + + +**Figure 1** Playback state transition +![Playback state change](figures/playback-status-change.png) + +For details about the state, see [AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9). When the AVPlayer is in the **prepared**, **playing**, **paused**, or **completed** state, the playback engine is working and a large amount of RAM is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the instance. + +## How to Develop + +Read [AVPlayer](../reference/apis/js-apis-media.md#avplayer9) for the API reference. + +1. Call **createAVPlayer()** to create an **AVPlayer** instance. The AVPlayer is the **idle** state. + +2. Set the events to listen for, which will be used in the full-process scenario. The table below lists the supported events. + | Event Type| Description| + | -------- | -------- | + | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVPlayer.| + | error | Mandatory; used to listen for AVPlayer errors.| + | durationUpdate | Used to listen for progress bar updates to refresh the media asset 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.
This event is reported when the AVPlayer seeks to the playback position specified in **seek()**.| + | speedDone | Used to listen for the completion status of the **setSpeed()** request.
This event is reported when the AVPlayer plays music at the speed specified in **setSpeed()**.| + | volumeChange | Used to listen for the completion status of the **setVolume()** request.
This event is reported when the AVPlayer plays music at the volume specified in **setVolume()**.| + | bufferingUpdate | Used to listen for network playback buffer information. This event reports the buffer percentage and playback progress.| + | audioInterrupt | Used to listen for audio interruption. This event is used together with the **audioInterruptMode** attribute.
This event is reported when the current audio playback is interrupted by another (for example, when a call is coming), so the application can process the event in time.| + +3. Set the media asset URL. The AVPlayer enters the **initialized** state. + > **NOTE** + > + > The URL in the code snippet below is for reference only. You need to check the media asset validity and set the URL based on service requirements. + > + > - If local files are used for playback, ensure that the files are available and the application sandbox path is used for access. For details about how to obtain the application sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). + > + > - If a network playback path is used, you must request the ohos.permission.INTERNET [permission](../security/accesstoken-guidelines.md). + > + > - You can also use **ResourceManager.getRawFd** to obtain the file descriptor of a file packed in the HAP file. For details, see [ResourceManager API Reference](../reference/apis/js-apis-resource-manager.md#getrawfd9). + > + > - The [playback formats and protocols](avplayer-avrecorder-overview.md#supported-formats-and-protocols) in use must be those supported by the system. + +4. Call **prepare()** to switch the AVPlayer to the **prepared** state. In this state, you can obtain the duration of the media asset to play and set the volume. + +5. Call **play()**, **pause()**, **seek()**, and **stop()** to perform audio playback control as required. + +6. (Optional) Call **reset()** to reset the AVPlayer. The AVPlayer enters the **idle** state again and you can change the media asset URL. + +7. Call **release()** to switch the AVPlayer to the **released** state. Now your application exits the playback. + +## Sample Code + +Refer to the sample code below to play a complete piece of music. + +```ts +import media from '@ohos.multimedia.media'; +import fs from '@ohos.file.fs'; +import common from '@ohos.app.ability.common'; + +export class AVPlayerDemo { + private avPlayer; + private count: number = 0; + + // Set AVPlayer callback functions. + setAVPlayerCallback() { + // Callback function for the seek operation. + this.avPlayer.on('seekDone', (seekDoneTime) => { + console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`); + }) + // Callback function for errors. If an error occurs during the operation on the AVPlayer, reset() is called to reset the AVPlayer. + this.avPlayer.on('error', (err) => { + console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); + this.avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. + }) + // 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('AVPlayer state idle called.'); + this.avPlayer.release(); // Call release() to release the instance. + break; + case 'initialized': // This state is reported when the AVPlayer sets the playback source. + console.info('AVPlayerstate initialized called.'); + this.avPlayer.prepare().then(() => { + console.info('AVPlayer prepare succeeded.'); + }, (err) => { + console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); + }); + break; + case 'prepared': // This state is reported upon a successful callback of prepare(). + console.info('AVPlayer 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('AVPlayer state playing called.'); + if (this.count !== 0) { + console.info('AVPlayer start to seek.'); + this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the audio clip. + } else { + this.avPlayer.pause(); // Call pause() to pause the playback. + } + this.count++; + break; + case 'paused': // This state is reported upon a successful callback of pause(). + console.info('AVPlayer state paused called.'); + this.avPlayer.play(); // Call play() again to start playback. + break; + case 'completed': // This state is reported upon the completion of the playback. + console.info('AVPlayer 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('AVPlayer state stopped called.'); + this.avPlayer.reset(); // Call reset() to reset the AVPlayer state. + break; + case 'released': + console.info('AVPlayer state released called.'); + break; + default: + console.info('AVPlayer state unknown called.'); + break; + } + }) + } + + // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file using the URL attribute. + async avPlayerUrlDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + let fdPath = 'fd://'; + // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. + let context = getContext(this) as common.UIAbilityContext; + let pathDir = context.filesDir; + let path = pathDir + '/01.mp3'; + // Open the corresponding file address to obtain the file descriptor and assign a value to the URL to trigger the reporting of the initialized state. + let file = await fs.open(path); + fdPath = fdPath + '' + file.fd; + this.avPlayer.url = fdPath; + } + + // The following demo shows how to use resourceManager to obtain the media file packed in the HAP file and play the media file by using the fdSrc attribute. + async avPlayerFdSrcDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. + // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. + let context = getContext(this) as common.UIAbilityContext; + let fileDescriptor = await context.resourceManager.getRawFd('01.mp3'); + // Assign a value to fdSrc to trigger the reporting of the initialized state. + this.avPlayer.fdSrc = fileDescriptor; + } +} +``` + + \ No newline at end of file diff --git a/en/application-dev/media/using-avrecorder-for-recording.md b/en/application-dev/media/using-avrecorder-for-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..71ab8557df470671088adfaa0473a6448d935881 --- /dev/null +++ b/en/application-dev/media/using-avrecorder-for-recording.md @@ -0,0 +1,182 @@ +# Using AVRecorder for Audio Recording + +You will learn how to use the AVRecorder to develop audio recording functionalities including starting, pausing, resuming, and stopping recording. + +During application development, you can use the **state** attribute of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state. + +**Figure 1** Recording state transition + +![Recording state change](figures/recording-status-change.png) + +For details about the state, see [AVRecorderState](../reference/apis/js-apis-media.md#avrecorderstate9). + + +## How to Develop + +Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API reference. + +1. Create an **AVRecorder** instance. The AVRecorder is the **idle** state. + + ```ts + import media from '@ohos.multimedia.media'; + + let avRecorder = undefined; + media.createAVRecorder().then((recorder) => { + avRecorder = recorder; + }, (err) => { + console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`); + }) + ``` + +2. Set the events to listen for. + | Event Type| Description| + | -------- | -------- | + | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.| + | error | Mandatory; used to listen for AVRecorder errors.| + + + ```ts + // Callback function for state changes. + avRecorder.on('stateChange', (state, reason) => { + console.log(`current state is ${state}`); + // You can add the action to be performed after the state is switched. + }) + + // Callback function for errors. + avRecorder.on('error', (err) => { + console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`); + }) + ``` + +3. Set audio recording parameters and call **prepare()**. The AVRecorder enters the **prepared** state. + > **NOTE** + > + > Pay attention to the following when configuring parameters: + > + > - In pure audio recording scenarios, set only audio-related parameters in **avConfig** of **prepare()**. + > If video-related parameters are configured, an error will be reported in subsequent steps. If video recording is required, follow the instructions provided in [Video Recording Development](video-recording.md). + > + > - The [recording formats](avplayer-avrecorder-overview.md#supported-formats) in use must be those supported by the system. + > + > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md). + + + ```ts + let avProfile = { + audioBitrate: 100000, // Audio bit rate. + audioChannels: 2, // Number of audio channels. + audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. + audioSampleRate: 48000, // Audio sampling rate. + fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. + } + let avConfig = { + audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. + profile: avProfile, + url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management. + } + avRecorder.prepare(avConfig).then(() => { + console.log('Invoke prepare succeeded.'); + }, (err) => { + console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); + }) + ``` + +4. Call **start()** to start recording. The AVRecorder enters the **started** state. + +5. Call **pause()** to pause recording. The AVRecorder enters the **paused** state. + +6. Call **resume()** to resume recording. The AVRecorder enters the **started** state again. + +7. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state. + +8. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. + +9. Call **release()** to switch the AVRecorder to the **released** state. Now your application exits the recording. + + +## Sample Code + + Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording. + +```ts +import media from '@ohos.multimedia.media'; + +export class AudioRecorderDemo { + private avRecorder; + private avProfile = { + audioBitrate: 100000, // Audio bit rate. + audioChannels: 2, // Number of audio channels. + audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. + audioSampleRate: 48000, // Audio sampling rate. + fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. + }; + private avConfig = { + audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. + profile: this.avProfile, + url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. + }; + + // Set AVRecorder callback functions. + setAudioRecorderCallback() { + // Callback function for state changes. + this.avRecorder.on('stateChange', (state, reason) => { + console.log(`AudioRecorder current state is ${state}`); + }) + // Callback function for errors. + this.avRecorder.on('error', (err) => { + console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`); + }) + } + + // Process of starting recording. + async startRecordingProcess() { + // 1. Create an AVRecorder instance. + this.avRecorder = await media.createAVRecorder(); + this.setAudioRecorderCallback(); + // 2. Obtain the file descriptor of the recording file and assign it to the URL in avConfig. For details, see FilePicker. + // 3. Set recording parameters to complete the preparations. + await this.avRecorder.prepare(this.avConfig); + // 4. Start recording. + await this.avRecorder.start(); + } + + // Process of pausing recording. + async pauseRecordingProcess() { + if (this.avRecorder.state ==='started') { // pause() can be called only when the AVRecorder is in the started state . + await this.avRecorder.pause(); + } + } + + // Process of resuming recording. + async resumeRecordingProcess() { + if (this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state . + await this.avRecorder.resume(); + } + } + + // Process of stopping recording. + async stopRecordingProcess() { + // 1. Stop recording. + if (this.avRecorder.state === 'started' + || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state. + await this.avRecorder.stop(); + } + // 2. Reset the AVRecorder. + await this.avRecorder.reset(); + // 3. Release the AVRecorder instance. + await this.avRecorder.release(); + // 4. Close the file descriptor of the recording file. + } + + // Complete sample code for starting, pausing, resuming, and stopping recording. + async audioRecorderDemo() { + await this.startRecordingProcess(); // Start recording. + // You can set the recording duration. For example, you can set the sleep mode to prevent code execution. + await this.pauseRecordingProcess(); // Pause recording. + await this.resumeRecordingProcess(); // Resume recording. + await this.stopRecordingProcess(); // Stop recording. + } +} +``` + + \ No newline at end of file diff --git a/en/application-dev/media/using-avsession-controller.md b/en/application-dev/media/using-avsession-controller.md new file mode 100644 index 0000000000000000000000000000000000000000..5e4b69d8b48f5acad64f120892062e66d67c6b12 --- /dev/null +++ b/en/application-dev/media/using-avsession-controller.md @@ -0,0 +1,244 @@ +# AVSession Controller + +Media Controller preset in OpenHarmony functions as the controller to interact with audio and video applications, for example, obtaining and displaying media information and delivering control commands. + +You can develop a system application (for example, a new playback control center or voice assistant) as the controller to interact with audio and video applications in the system. + +## Basic Concepts + +- AVSessionDescriptor: session information, including the session ID, session type (audio/video), custom session name (**sessionTag**), information about the corresponding application (**elementName**), and whether the session is pined on top (isTopSession). + +- Top session: session with the highest priority in the system, for example, a session that is being played. Generally, the controller must hold an **AVSessionController** object to communicate with a session. However, the controller can directly communicate with the top session, for example, directly sending a control command or key event, without holding an **AVSessionController** object. + +## Available APIs + +The table below lists the key APIs used by the controller. The APIs use either a callback or promise to return the result. The APIs listed below use a callback. They provide the same functions as their counterparts that use a promise. + +For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). + +| API| Description| +| -------- | -------- | +| getAllSessionDescriptors(callback: AsyncCallback<Array<Readonly<AVSessionDescriptor>>>): void | Obtains the descriptors of all AVSessions in the system.| +| createController(sessionId: string, callback: AsyncCallback<AVSessionController>): void | Creates an AVSessionController.| +| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void | Obtains valid commands supported by the AVSession.
Control commands listened by an audio and video application when it accesses the AVSession are considered as valid commands supported by the AVSession. For details, see [Provider of AVSession](using-avsession-developer.md).| +| getLaunchAbility(callback: AsyncCallback<WantAgent>): void | Obtains the UIAbility that is configured in the AVSession and can be started.
The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller.| +| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to an AVSession through the AVSessionController object.| +| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the top session.| +| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a control command to an AVSession through the AVSessionController object.| +| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a control command to the top session.| + +## How to Develop + +To enable a system application to access the AVSession service as a controller, proceed as follows: + +1. Obtain **AVSessionDescriptor** through AVSessionManager and create an **AVSessionController** object. + The controller may obtain all **AVSessionDescriptor**s in the current system, and create an **AVSessionController** object for each session, so as to perform unified playback control on all the audio and video applications. + + ```ts + // Import the AVSessionManager module. + import AVSessionManager from '@ohos.multimedia.avsession'; + + // Define global variables. + let g_controller = new Array(); + let g_centerSupportCmd:Set = new Set(['play', 'pause', 'playNext', 'playPrevious', 'fastForward', 'rewind', 'seek','setSpeed', 'setLoopMode', 'toggleFavorite']); + let g_validCmd:Set; + // Obtain the session descriptors and create an AVSessionController object. + AVSessionManager.getAllSessionDescriptors().then((descriptors) => { + descriptors.forEach((descriptor) => { + AVSessionManager.createController(descriptor.sessionId).then((controller) => { + g_controller.push(controller); + }).catch((err) => { + console.error(`createController : ERROR : ${err.message}`); + }); + }); + }).catch((err) => { + console.error(`getAllSessionDescriptors : ERROR : ${err.message}`); + }); + + ``` + +2. Listen for the session state and service state events. + + The following session state events are available: + + - **sessionCreate**: triggered when a session is created. + - **sessionDestroy**: triggered when a session is destroyed. + - **topSessionChange**: triggered when the top session is changed. + + The service state event **sessionServiceDie** is reported when the AVSession service is abnormal. + + ```ts + // Subscribe to the 'sessionCreate' event and create an AVSessionController object. + AVSessionManager.on('sessionCreate', (session) => { + // After an AVSession is added, you must create an AVSessionController object. + AVSessionManager.createController(session.sessionId).then((controller) => { + g_controller.push(controller); + }).catch((err) => { + console.info(`createController : ERROR : ${err.message}`); + }); + }); + + // Subscribe to the 'sessionDestroy' event to enable the application to get notified when the session dies. + AVSessionManager.on('sessionDestroy', (session) => { + let index = g_controller.findIndex((controller) => { + return controller.sessionId === session.sessionId; + }); + if (index !== 0) { + g_controller[index].destroy(); + g_controller.splice(index, 1); + } + }); + // Subscribe to the 'topSessionChange' event. + AVSessionManager.on('topSessionChange', (session) => { + let index = g_controller.findIndex((controller) => { + return controller.sessionId === session.sessionId; + }); + // Place the session on the top. + if (index !== 0) { + g_controller.sort((a, b) => { + return a.sessionId === session.sessionId ? -1 : 0; + }); + } + }); + // Subscribe to the 'sessionServiceDie' event. + AVSessionManager.on('sessionServiceDie', () => { + // The server is abnormal, and the application clears resources. + console.info("Server exception."); + }) + ``` + +3. Subscribe to media information changes and other session events. + + The following media information change events are available: + + - **metadataChange**: triggered when the session metadata changes. + - **playbackStateChange**: triggered when the playback state changes. + - **activeStateChange**: triggered when the activation state of the session changes. + - **validCommandChange**: triggered when the valid commands supported by the session changes. + - **outputDeviceChange**: triggered when the output device changes. + - **sessionDestroy**: triggered when a session is destroyed. + + The controller can listen for events as required. + + ```ts + // Subscribe to the 'activeStateChange' event. + controller.on('activeStateChange', (isActive) => { + if (isActive) { + console.info("The widget corresponding to the controller is highlighted."); + } else { + console.info("The widget corresponding to the controller is invalid."); + } + }); + // Subscribe to the 'sessionDestroy' event to enable the controller to get notified when the session dies. + controller.on('sessionDestroy', () => { + console.info('on sessionDestroy : SUCCESS '); + controller.destroy().then(() => { + console.info('destroy : SUCCESS '); + }).catch((err) => { + console.info(`destroy : ERROR :${err.message}`); + }); + }); + + // Subscribe to metadata changes. + let metaFilter = ['assetId', 'title', 'description']; + controller.on('metadataChange', metaFilter, (metadata) => { + console.info(`on metadataChange assetId : ${metadata.assetId}`); + }); + // Subscribe to playback state changes. + let playbackFilter = ['state', 'speed', 'loopMode']; + controller.on('playbackStateChange', playbackFilter, (playbackState) => { + console.info(`on playbackStateChange state : ${playbackState.state}`); + }); + // Subscribe to supported command changes. + controller.on('validCommandChange', (cmds) => { + console.info(`validCommandChange : SUCCESS : size : ${cmds.size}`); + console.info(`validCommandChange : SUCCESS : cmds : ${cmds.values()}`); + g_validCmd.clear(); + for (let c of g_centerSupportCmd) { + if (cmds.has(c)) { + g_validCmd.add(c); + } + } + }); + // Subscribe to output device changes. + controller.on('outputDeviceChange', (device) => { + console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`); + }); + ``` + +4. Obtain the media information transferred by the provider for display on the UI, for example, displaying the track being played and the playback state in Media Controller. + + ```ts + async getInfoFromSessionByController() { + // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. + let controller: AVSessionManager.AVSessionController = ALLREADY_HAVE_A_CONTROLLER; + // Obtain the session ID. + let sessionId: string = controller.sessionId; + console.info(`get sessionId by controller : isActive : ${sessionId}`); + // Obtain the activation state of the session. + let isActive: boolean = await controller.isActive(); + console.info(`get activeState by controller : ${isActive}`); + // Obtain the media information of the session. + let metadata: AVSessionManager.AVMetadata = await controller.getAVMetadata(); + console.info(`get media title by controller : ${metadata.title}`); + console.info(`get media artist by controller : ${metadata.artist}`); + // Obtain the playback information of the session. + let avPlaybackState: AVSessionManager.AVPlaybackState = await controller.getAVPlaybackState(); + console.info(`get playbackState by controller : ${avPlaybackState.state}`); + console.info(`get favoriteState by controller : ${avPlaybackState.isFavorite}`); + } + ``` + +5. Control the playback behavior, for example, sending a command to operate (play/pause/previous/next) the item being played in Media Controller. + + After listening for the control command event, the audio and video application serving as the provider needs to implement the corresponding operation. + + + ```ts + async sendCommandToSessionByController() { + // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. + let controller: AVSessionManager.AVSessionController = ALLREADY_HAVE_A_CONTROLLER; + // Obtain the commands supported by the session. + let validCommandTypeArray: Array = await controller.getValidCommands(); + console.info(`get validCommandArray by controller : length : ${validCommandTypeArray.length}`); + // Deliver the 'play' command. + // If the 'play' command is valid, deliver it. Normal sessions should provide and implement the playback. + if (validCommandTypeArray.indexOf('play') >= 0) { + let avCommand: AVSessionManager.AVControlCommand = {command:'play'}; + controller.sendControlCommand(avCommand); + } + // Deliver the 'pause' command. + if (validCommandTypeArray.indexOf('pause') >= 0) { + let avCommand: AVSessionManager.AVControlCommand = {command:'pause'}; + controller.sendControlCommand(avCommand); + } + // Deliver the 'playPrevious' command. + if (validCommandTypeArray.indexOf('playPrevious') >= 0) { + let avCommand: AVSessionManager.AVControlCommand = {command:'playPrevious'}; + controller.sendControlCommand(avCommand); + } + // Deliver the 'playNext' command. + if (validCommandTypeArray.indexOf('playNext') >= 0) { + let avCommand: AVSessionManager.AVControlCommand = {command:'playNext'}; + controller.sendControlCommand(avCommand); + } + } + ``` + +6. When the audio and video application exits, cancel the listener and release the resources. + + ```ts + async destroyController() { + // It is assumed that an AVSessionController object corresponding to the session already exists. For details about how to create an AVSessionController object, see the code snippet above. + let controller: AVSessionManager.AVSessionController = ALLREADY_HAVE_A_CONTROLLER; + + // Destroy the AVSessionController object. After being destroyed, it is no longer available. + controller.destroy(function (err) { + if (err) { + console.info(`Destroy controller ERROR : code: ${err.code}, message: ${err.message}`); + } else { + console.info('Destroy controller SUCCESS'); + } + }); + } + ``` diff --git a/en/application-dev/media/using-avsession-developer.md b/en/application-dev/media/using-avsession-developer.md new file mode 100644 index 0000000000000000000000000000000000000000..07bd4bf1297f3afc5352d30e9acd674fe056f815 --- /dev/null +++ b/en/application-dev/media/using-avsession-developer.md @@ -0,0 +1,198 @@ +# AVSession Provider + +An audio and video application needs to access the AVSession service as a provider in order to display media information in the controller (for example, Media Controller) and respond to control commands delivered by the controller. + +## Basic Concepts + +- AVMetadata: media data related attributes, including the IDs of the current media asset (assetId), previous media asset (previousAssetId), and next media asset (nextAssetId), title, author, album, writer, and duration. + +- AVPlaybackState: playback state attributes, including the playback state, position, speed, buffered time, loop mode, and whether the media asset is favorited (**isFavorite**). + +## Available APIs + +The table below lists the key APIs used by the provider. The APIs use either a callback or promise to return the result. The APIs listed below use a callback. They provide the same functions as their counterparts that use a promise. + +For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). + +| API| Description| +| -------- | -------- | +| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback<AVSession>): void | Creates an AVSession.
Only one AVSession can be created for a UIAbility.| +| setAVMetadata(data: AVMetadata, callback: AsyncCallback<void>): void | Sets AVSession metadata.| +| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback<void>): void | Sets the AVSession playback state.| +| setLaunchAbility(ability: WantAgent, callback: AsyncCallback<void>): void | Starts a UIAbility.| +| getController(callback: AsyncCallback<AVSessionController>): void | Obtains the controller of the AVSession.| +| activate(callback: AsyncCallback<void>): void | Activates the AVSession.| +| destroy(callback: AsyncCallback<void>): void | Destroys the AVSession.| + +## How to Develop + +To enable an audio and video application to access the AVSession service as a provider, proceed as follows: + +1. Call an API in the **AVSessionManager** class to create and activate an **AVSession** object. + + ```ts + import AVSessionManager from '@ohos.multimedia.avsession'; // Import the AVSessionManager module. + + // Create an AVSession object. + async createSession() { + let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(this.context, 'SESSION_NAME', 'audio'); + session.activate(); + console.info(`session create done : sessionId : ${session.sessionId}`); + } + ``` + +2. Set AVSession information, which includes: + - AVMetadata + - AVPlaybackState + + The controller will call an API in the **AVSessionController** class to obtain the information and display or process the information. + + ```ts + async setSessionInfo() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // The player logic that triggers changes in the session metadata and playback state is omitted here. + // Set necessary session metadata. + let metadata: AVSessionManager.AVMetadata = { + assetId: "0", + title: "TITLE", + artist: "ARTIST" + }; + session.setAVMetadata(metadata).then(() => { + console.info('SetAVMetadata successfully'); + }).catch((err) => { + console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`); + }); + // Set the playback state to paused and set isFavorite to false. + let playbackState: AVSessionManager.AVPlaybackState = { + state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE, + isFavorite:false + }; + session.setAVPlaybackState(playbackState, function (err) { + if (err) { + console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('SetAVPlaybackState successfully'); + } + }); + } + ``` + +3. Set the UIAbility to be started by the controller. The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller. + The UIAbility is set through the **WantAgent** API. For details, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). + + ```ts + import WantAgent from "@ohos.app.ability.wantAgent"; + ``` + + ```ts + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + let wantAgentInfo: { + wants: [ + { + bundleName: "com.example.musicdemo", + abilityName: "com.example.musicdemo.MainAbility" + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags: [WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + } + WantAgent.getWantAgent(wantAgentInfo).then((agent) => { + session.setLaunchAbility(agent) + }) + ``` + +4. Listen for control commands delivered by the controller, for example, Media Controller. + > **NOTE** + > + > After the provider registers a listener for the control command event, the event will be reflected in **getValidCommands()** of the controller. In other words, the controller determines that the command is valid and triggers the corresponding event as required. To ensure that the control commands delivered by the controller can be executed normally, the provider should not use a null implementation for listening. + + ```ts + async setListenerForMesFromController() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // Generally, logic processing on the player is implemented in the listener. + // After the processing is complete, use the setter to synchronize the playback information. For details, see the code snippet above. + session.on('play', () => { + console.info('on play , do play task'); + + // do some tasks ··· + }); + session.on('pause', () => { + console.info('on pause , do pause task'); + // do some tasks ··· + }); + session.on('stop', () => { + console.info('on stop , do stop task'); + // do some tasks ··· + }); + session.on('playNext', () => { + console.info('on playNext , do playNext task'); + // do some tasks ··· + }); + session.on('playPrevious', () => { + console.info('on playPrevious , do playPrevious task'); + // do some tasks ··· + }); + } + ``` + +5. Obtain an **AVSessionController** object for this **AVSession** object for interaction. + + ```ts + async createControllerFromSession() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + + // Obtain an AVSessionController object for this AVSession object. + let controller: AVSessionManager.AVSessionController = await session.getController(); + + // The AVSessionController object can interact with the AVSession object, for example, by delivering a control command. + let avCommand: AVSessionManager.AVControlCommand = {command:'play'}; + controller.sendControlCommand(avCommand); + + // Alternatively, listen for state changes. + controller.on('playbackStateChange', 'all', (state: AVSessionManager.AVPlaybackState) => { + + // do some things + }); + + // The AVSessionController object can perform many operations. For details, see the description of the controller. + } + ``` + +6. When the audio and video application exits and does not need to continue playback, cancel the listener and destroy the **AVSession** object. + The code snippet below is used for canceling the listener for control commands: + + ```ts + async unregisterSessionListener() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + + // Cancel the listener of the AVSession object. + session.off('play'); + session.off('pause'); + session.off('stop'); + session.off('playNext'); + session.off('playPrevious'); + } + ``` + + The code snippet below is used for destroying the AVSession object: + + ```ts + async destroySession() { + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; + // Destroy the AVSession object. + session.destroy(function (err) { + if (err) { + console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + console.info('Destroy : SUCCESS '); + } + }); + } + ``` diff --git a/en/application-dev/media/using-distributed-avsession.md b/en/application-dev/media/using-distributed-avsession.md new file mode 100644 index 0000000000000000000000000000000000000000..c1835d661fdd2b57b7dce0f2507dbea748eaea7e --- /dev/null +++ b/en/application-dev/media/using-distributed-avsession.md @@ -0,0 +1,55 @@ +# Using Distributed AVSession + +## Basic Concepts + +- Remote AVSession: an AVSession automatically created on the remote device by the AVSession service for synchronization with an AVSession on the local device. + +- Remote AVSessionController: AVSessionController automatically created on the remote device after projection. + +## Available APIs + +The table below describes the key APIs used for remote projection with the distributed AVSession. The APIs use either a callback or promise to return the result. The APIs listed below use a callback. They provide the same functions as their counterparts that use a promise. + +For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). + +| API| Description| +| -------- | -------- | +| castAudio(session: SessionToken \| 'all', audioDevices: Array<audio.AudioDeviceDescriptor>, callback: AsyncCallback<void>): void | Casts a session to a list of devices.| + +## How to Develop + +To enable a system application that accesses the AVSession service as the controller to use the distributed AVSession for projection, proceed as follows: + +1. Import the modules. Before projection, you must obtain the AudioDeviceDescriptor from the audio module. Therefore, import the audio module and AVSessionManager module. + + ```ts + import AVSessionManager from '@ohos.multimedia.avsession'; + import audio from '@ohos.multimedia.audio'; + ``` + +2. Use **castAudio** in the **AVSessionManager** class to project all sessions of the local device to another device. + + ```ts + // Cast the sessions to another device. + let audioManager = audio.getAudioManager(); + let audioRoutingManager = audioManager.getRoutingManager(); + let audioDevices; + await audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + audioDevices = data; + console.info('Promise returned to indicate that the device list is obtained.'); + }).catch((err) => { + console.info(`getDevices : ERROR : ${err.message}`); + }); + + AVSessionManager.castAudio('all', audioDevices).then(() => { + console.info('createController : SUCCESS'); + }).catch((err) => { + console.info(`createController : ERROR : ${err.message}`); + }); + ``` + + After the system application on the local service initiates projection to a remote device, the AVSession framework instructs the AVSession service of the remote device to create a remote AVSession. When the AVSession on the local device changes (for example, the media information or playback state changes), the AVSession framework automatically synchronizes the change to the remote device. + + The AVSession processing mechanism on the remote device is consistent with that on the local device. That is, the controller (for example, the Media Controller) on the remote device listens for the AVSession creation event, and creates a remote **AVSessionController** object to manage the remote AVSession. In addition, the control commands are automatically synchronized by the AVSession framework to the local device. + + The provider (for example, an audio and video application) on the local device listens for control command events, so as to respond to the commands from the remote device in time. diff --git a/en/application-dev/media/using-opensl-es-for-playback.md b/en/application-dev/media/using-opensl-es-for-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..c5dedbba659154a1893a471e5e9a3d33d33be20a --- /dev/null +++ b/en/application-dev/media/using-opensl-es-for-playback.md @@ -0,0 +1,131 @@ +# Using OpenSL ES for Audio Playback + +OpenSL ES, short for Open Sound Library for Embedded Systems, is an embedded, cross-platform audio processing library that is free of charge. It provides high-performance and low-latency APIs for you to develop applications running on embedded mobile multimedia devices. OpenHarmony have implemented certain native APIs based on [OpenSL ES](https://www.khronos.org/opensles/) 1.0.1 API specifications developed by the [Khronos Group](https://www.khronos.org/). You can use these APIs through and . + +## OpenSL ES on OpenHarmony + +Currently, OpenHarmony implements parts of [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) to implement basic audio playback functionalities. + +If an API that has not been implemented on OpenHarmony is called, **SL_RESULT_FEATURE_UNSUPPORTED** is returned. + +The following lists the OpenSL ES APIs that have been implemented on OpenHarmony. For details, see the [OpenSL ES](https://www.khronos.org/opensles/) specifications. + +- **Engine APIs implemented on OpenHarmony** + - SLresult (\*CreateAudioPlayer) (SLEngineItf self, SLObjectItf \* pPlayer, SLDataSource \*pAudioSrc, SLDataSink \*pAudioSnk, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) + - SLresult (\*CreateAudioRecorder) (SLEngineItf self, SLObjectItf \* pRecorder, SLDataSource \*pAudioSrc, SLDataSink \*pAudioSnk, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) + - SLresult (\*CreateOutputMix) (SLEngineItf self, SLObjectItf \* pMix, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) + +- **Object APIs implemented on OpenHarmony** + - SLresult (\*Realize) (SLObjectItf self, SLboolean async) + - SLresult (\*GetState) (SLObjectItf self, SLuint32 \* pState) + - SLresult (\*GetInterface) (SLObjectItf self, const SLInterfaceID iid, void \* pInterface) + - void (\*Destroy) (SLObjectItf self) + +- **Playback APIs implemented on OpenHarmony** + - SLresult (\*SetPlayState) (SLPlayItf self, SLuint32 state) + - SLresult (\*GetPlayState) (SLPlayItf self, SLuint32 \*pState) + +- **Volume control APIs implemented on OpenHarmony** + - SLresult (\*SetVolumeLevel) (SLVolumeItf self, SLmillibel level) + - SLresult (\*GetVolumeLevel) (SLVolumeItf self, SLmillibel \*pLevel) + - SLresult (\*GetMaxVolumeLevel) (SLVolumeItf self, SLmillibel \*pMaxLevel) + +- **BufferQueue APIs implemented on OpenHarmony** + + The APIs listed below can be used only after is introduced. + | API| Description| + | -------- | -------- | + | SLresult (\*Enqueue) (SLOHBufferQueueItf self, const void \*buffer, SLuint32 size) | Adds a buffer to the corresponding queue.
For an audio playback operation, this API adds the buffer with audio data to the **filledBufferQ_** queue. For an audio recording operation, this API adds the idle buffer after recording data storage to the **freeBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the pointer to the buffer with audio data or the pointer to the idle buffer after the recording data is stored.
The **size** parameter indicates the size of the buffer.| + | SLresult (\*Clear) (SLOHBufferQueueItf self) | Releases a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.| + | SLresult (\*GetState) (SLOHBufferQueueItf self, SLOHBufferQueueState \*state) | Obtains the state of a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **state** parameter indicates the pointer to the state of the **BufferQueue** object.| + | SLresult (\*RegisterCallback) (SLOHBufferQueueItf self, SlOHBufferQueueCallback callback, void\* pContext) | Registers a callback.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **callback** parameter indicates the callback to be registered for the audio playback or recording operation.
The **pContext** parameter indicates the pointer to the audio file to be played for an audio playback operation or the pointer to the audio file to be recorded for an audio recording operation.| + | SLresult (\*GetBuffer) (SLOHBufferQueueItf self, SLuint8\*\* buffer, SLuint32\* size) | Obtains a buffer.
For an audio playback operation, this API obtains an idle buffer from the **freeBufferQ_** queue. For an audio recording operation, this API obtains the buffer that carries recording data from the **filledBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the double pointer to the idle buffer or the buffer carrying recording data.
The **size** parameter indicates the size of the buffer.| + +## Sample Code + +Refer to the sample code below to play an audio file. + +1. Add the header files. + + ```c++ + #include + #include + #include + ``` + +2. Use the **slCreateEngine** API to obtain an **engine** instance. + + ```c++ + SLObjectItf engineObject = nullptr; + slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr); + (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); + ``` + +3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** API. + + ```c++ + SLEngineItf engineEngine = nullptr; + (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); + ``` + +4. Configure the player and create an **AudioPlayer** instance. + + ```c++ + SLDataLocator_BufferQueue slBufferQueue = { + SL_DATALOCATOR_BUFFERQUEUE, + 0 + }; + + // Configure the parameters based on the audio file format. + SLDataFormat_PCM pcmFormat = { + SL_DATAFORMAT_PCM, + 2, // Number of channels. + SL_SAMPLINGRATE_48, // Sampling rate. + SL_PCMSAMPLEFORMAT_FIXED_16, // Audio sample format. + 0, + 0, + 0 + }; + SLDataSource slSource = {&slBufferQueue, &pcmFormat}; + SLObjectItf pcmPlayerObject = nullptr; + (*engineEngine)->CreateAudioPlayer(engineEngine, &pcmPlayerObject, &slSource, null, 0, nullptr, nullptr); + (*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE); + ``` + +5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** API. + + ```c++ + SLOHBufferQueueItf bufferQueueItf; + (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); + ``` + +6. Open an audio file and register the **BufferQueueCallback** function. + + ```c++ + static void BufferQueueCallback (SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) + { + SLuint8 *buffer = nullptr; + SLuint32 pSize; + (*bufferQueueItf)->GetBuffer(bufferQueueItf, &buffer, &pSize); + // Write the audio data to be played to the buffer. + (*bufferQueueItf)->Enqueue(bufferQueueItf, buffer, size); + } + void *pContext; // This callback can be used to obtain the custom context information passed in. + (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, pContext); + ``` + +7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** API and start playing. + + ```c++ + SLPlayItf playItf = nullptr; + (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_PLAY, &playItf); + (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); + ``` + +8. Stop playing. + + ```c++ + (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); + (*pcmPlayerObject)->Destroy(pcmPlayerObject); + (*engineObject)->Destroy(engineObject); + ``` diff --git a/en/application-dev/media/using-opensl-es-for-recording.md b/en/application-dev/media/using-opensl-es-for-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..55a18fc561c0117d5aff5aaedb22c36f1b7706bf --- /dev/null +++ b/en/application-dev/media/using-opensl-es-for-recording.md @@ -0,0 +1,148 @@ +# Using OpenSL ES for Audio Recording + +OpenSL ES, short for Open Sound Library for Embedded Systems, is an embedded, cross-platform audio processing library that is free of charge. It provides high-performance and low-latency APIs for you to develop applications running on embedded mobile multimedia devices. OpenHarmony have implemented certain native APIs based on [OpenSL ES](https://www.khronos.org/opensles/) 1.0.1 API specifications developed by the [Khronos Group](https://www.khronos.org/). You can use these APIs through and . + +## OpenSL ES on OpenHarmony + +Currently, OpenHarmony implements parts of [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) to implement basic audio recording functionalities. + +If an API that has not been implemented on OpenHarmony is called, **SL_RESULT_FEATURE_UNSUPPORTED** is returned. + +The following lists the OpenSL ES APIs that have been implemented on OpenHarmony. For details, see the [OpenSL ES](https://www.khronos.org/opensles/) specifications. + +- **Engine APIs implemented on OpenHarmony** + - SLresult (\*CreateAudioPlayer) (SLEngineItf self, SLObjectItf \* pPlayer, SLDataSource \*pAudioSrc, SLDataSink \*pAudioSnk, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) + - SLresult (\*CreateAudioRecorder) (SLEngineItf self, SLObjectItf \* pRecorder, SLDataSource \*pAudioSrc, SLDataSink \*pAudioSnk, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) + - SLresult (\*CreateOutputMix) (SLEngineItf self, SLObjectItf \* pMix, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) + +- **Object APIs implemented on OpenHarmony** + - SLresult (\*Realize) (SLObjectItf self, SLboolean async) + - SLresult (\*GetState) (SLObjectItf self, SLuint32 \* pState) + - SLresult (\*GetInterface) (SLObjectItf self, const SLInterfaceID iid, void \* pInterface) + - void (\*Destroy) (SLObjectItf self) + +- **Recorder APIs implemented on OpenHarmony** + - SLresult (\*SetRecordState) (SLRecordItf self, SLuint32 state) + - SLresult (\*GetRecordState) (SLRecordItf self,SLuint32 \*pState) + +- **BufferQueue APIs implemented on OpenHarmony** + + The APIs listed below can be used only after is introduced. + | API| Description| + | -------- | -------- | + | SLresult (\*Enqueue) (SLOHBufferQueueItf self, const void \*buffer, SLuint32 size) | Adds a buffer to the corresponding queue.
For an audio playback operation, this API adds the buffer with audio data to the **filledBufferQ_** queue. For an audio recording operation, this API adds the idle buffer after recording data storage to the **freeBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the pointer to the buffer with audio data or the pointer to the idle buffer after the recording data is stored.
The **size** parameter indicates the size of the buffer.| + | SLresult (\*Clear) (SLOHBufferQueueItf self) | Releases a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.| + | SLresult (\*GetState) (SLOHBufferQueueItf self, SLOHBufferQueueState \*state) | Obtains the state of a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **state** parameter indicates the pointer to the state of the **BufferQueue** object.| + | SLresult (\*RegisterCallback) (SLOHBufferQueueItf self, SlOHBufferQueueCallback callback, void\* pContext) | Registers a callback.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **callback** parameter indicates the callback to be registered for the audio playback or recording operation.
The **pContext** parameter indicates the pointer to the audio file to be played for an audio playback operation or the pointer to the audio file to be recorded for an audio recording operation.| + | SLresult (\*GetBuffer) (SLOHBufferQueueItf self, SLuint8\*\* buffer, SLuint32\* size) | Obtains a buffer.
For an audio playback operation, this API obtains an idle buffer from the **freeBufferQ_** queue. For an audio recording operation, this API obtains the buffer that carries recording data from the **filledBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the double pointer to the idle buffer or the buffer carrying recording data.
The **size** parameter indicates the size of the buffer.| + +## Sample Code + +Refer to the sample code below to record an audio file. + +1. Add the header files. + + ```c++ + #include + #include + #include + ``` + +2. Use the **slCreateEngine** API to create and instantiate an **engine** object. + + ```c++ + SLObjectItf engineObject = nullptr; + slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr); + (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); + ``` + +3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** API. + + ```c++ + SLEngineItf engineItf = nullptr; + (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf); + ``` + +4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance. + + ```c++ + SLDataLocator_IODevice io_device = { + SL_DATALOCATOR_IODEVICE, + SL_IODEVICE_AUDIOINPUT, + SL_DEFAULTDEVICEID_AUDIOINPUT, + NULL + }; + SLDataSource audioSource = { + &io_device, + NULL + }; + SLDataLocator_BufferQueue buffer_queue = { + SL_DATALOCATOR_BUFFERQUEUE, + 3 + }; + // Configure the parameters based on the audio file format. + SLDataFormat_PCM format_pcm = { + SL_DATAFORMAT_PCM, // Input audio format. + 1, // Mono channel. + SL_SAMPLINGRATE_44_1, // Sampling rate, 44100 Hz. + SL_PCMSAMPLEFORMAT_FIXED_16, // Audio sampling format, a signed 16-bit integer in little-endian format. + 0, + 0, + 0 + }; + SLDataSink audioSink = { + &buffer_queue, + &format_pcm + }; + + SLObjectItf pcmCapturerObject = nullptr; + (*engineItf)->CreateAudioRecorder(engineItf, &pcmCapturerObject, + &audioSource, &audioSink, 0, nullptr, nullptr); + (*pcmCapturerObject)->Realize(pcmCapturerObject, SL_BOOLEAN_FALSE); + + ``` + +5. Obtain the **recordItf** instance of the **SL_IID_RECORD** API. + + ```c++ + SLRecordItf recordItf; + (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf); + ``` + +6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** API. + + ```c++ + SLOHBufferQueueItf bufferQueueItf; + (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); + ``` + +7. Register the **BufferQueueCallback** function. + + ```c++ + static void BufferQueueCallback(SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) + { + // Obtain the user information passed in during the registration from pContext. + SLuint8 *buffer = nullptr; + SLuint32 pSize = 0; + (*bufferQueueItf)->GetBuffer(bufferQueueItf, &buffer, &pSize); + if (buffer != nullptr) { + // The recording data can be read from the buffer for subsequent processing. + (*bufferQueueItf)->Enqueue(bufferQueueItf, buffer, size); + } + } + void *pContext; // This callback can be used to obtain the custom context information passed in. + (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, pContext); + ``` + +8. Start audio recording. + + ```c++ + (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_RECORDING); + ``` + +9. Stop audio recording. + + ```c++ + (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED); + (*pcmCapturerObject)->Destroy(pcmCapturerObject); + ``` diff --git a/en/application-dev/media/using-toneplayer-for-playback.md b/en/application-dev/media/using-toneplayer-for-playback.md new file mode 100644 index 0000000000000000000000000000000000000000..11a528786b5bae712d8c4f07b9cad4ee29af2f48 --- /dev/null +++ b/en/application-dev/media/using-toneplayer-for-playback.md @@ -0,0 +1,140 @@ +# Using TonePlayer for Audio Playback (for System Applications Only) + +TonePlayer9+ provides APIs for playing and managing Dual Tone Multi Frequency (DTMF) tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. The main task of the TonePlayer is to generate sine waves of different frequencies by using the built-in algorithm based on the [ToneType](../reference/apis/js-apis-audio.md#tonetype9)s and add the sine waves to create a sound. The sound can then be played by using the [AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8), and the playback task can also be managed by using the [AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8). The full process includes loading the DTMF tone configuration, starting DTMF tone playing, stopping the playback, and releasing the resources associated with the **TonePlayer** object. For details about the APIs, see the [TonePlayer API Reference](../reference/apis/js-apis-audio.md#toneplayer9). + + +## Supported Tone Types + +The table below lists the supported [ToneType](../reference/apis/js-apis-audio.md#tonetype9)s. You can call **load()** with **audio.ToneType.*type*** as a parameter to load the tone resource of the specified type. + +| Tone Type| Value| Description| +| -------- | -------- | -------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0.| +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1.| +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2.| +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3.| +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4.| +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5.| +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6.| +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7.| +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8.| +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9.| +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*).| +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#).| +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A.| +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B.| +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C.| +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D.| +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone.| +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy.| +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion.| +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment.| +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available.| +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone.| +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone.| +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone.| +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK.| +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT.| +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone.| + + +## How to Develop + +To implement audio playback with the TonePlayer, perform the following steps: + +1. Create a **TonePlayer** instance. + + ```ts + import audio from '@ohos.multimedia.audio'; + let audioRendererInfo = { + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 + }; + tonePlayerPromise = audio.createTonePlayer(audioRendererInfo); + ``` + +2. Load the DTMF tone configuration of the specified type. + + ```ts + tonePlayerPromise.load(audio.ToneType.TONE_TYPE_DIAL_0); + ``` + +3. Start DTMF tone playing. + + ```ts + tonePlayerPromise.start(); + ``` + +4. Stop the tone that is being played. + + ```ts + tonePlayerPromise.stop(); + ``` + +5. Release the resources associated with the **TonePlayer** instance. + + ```ts + tonePlayerPromise.release(); + ``` + +If the APIs are not called in the preceding sequence, the error code **6800301 NAPI_ERR_SYSTEM** is returned. + + +## Sample Code + +Refer to the following code to play the DTMF tone when the dial key on the keyboard is pressed. + +To prevent the UI thread from being blocked, most **TonePlayer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [TonePlayer](../reference/apis/js-apis-audio.md#toneplayer9). + + +```ts +import audio from '@ohos.multimedia.audio'; + +export class TonelayerDemo { + private timer : number; + private timerPro : number; + // Promise mode. + async testTonePlayerPromise(type) { + console.info('testTonePlayerPromise start'); + if (this.timerPro) clearTimeout(this.timerPro); + let tonePlayerPromise; + let audioRendererInfo = { + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 + }; + this.timerPro = setTimeout(async () => { + try { + console.info('testTonePlayerPromise: createTonePlayer'); + // Create a DTMF player. + tonePlayerPromise = await audio.createTonePlayer(audioRendererInfo); + console.info('testTonePlayerPromise: createTonePlayer-success'); + console.info(`testTonePlayerPromise: load type: ${type}`); + // Load the tone configuration of the specified type. + await tonePlayerPromise.load(type); + console.info('testTonePlayerPromise: load-success'); + console.info(`testTonePlayerPromise: start type: ${type}`); + // Start DTMF tone playing. + await tonePlayerPromise.start(); + console.info('testTonePlayerPromise: start-success'); + console.info(`testTonePlayerPromise: stop type: ${type}`); + setTimeout(async()=>{ + // Stop the tone that is being played. + await tonePlayerPromise.stop(); + console.info('testTonePlayerPromise: stop-success'); + console.info(`testTonePlayerPromise: release type: ${type}`); + // Release the resources associated with the TonePlayer instance. + await tonePlayerPromise.release(); + console.info('testTonePlayerPromise: release-success'); + }, 30) + } catch(err) { + console.error(`testTonePlayerPromise err : ${err}`); + } + }, 200) + }; + async testTonePlayer() { + this.testTonePlayerPromise(audio.ToneType.TONE_TYPE_DIAL_0); + } +} +``` diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index d4c895b452aa31b28690bd96bd9ef0fac64c4eb4..fff4aa830ddc45e7d20e0fd06655adfdc5243fe5 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -1,419 +1,178 @@ -# Video Playback Development +# Video Playback -## Introduction - -You can use video playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, set the playback speed, and obtain track information. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback. - -## Working Principles - -The following figures show the video playback state transition and the interaction with external modules for video playback. - -**Figure 1** Video playback state transition - -![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png) - -**Figure 2** Interaction with external modules for video playback - -![en-us_image_video_player](figures/en-us_image_video_player.png) - -**NOTE**: When a third-party application calls a JS interface provided by the JS interface layer, the framework layer invokes the audio component through the media service of the native framework to output the audio data decoded by the software to the audio HDI. The graphics subsystem outputs the image data decoded by the codec HDI at the hardware interface layer to the display HDI. In this way, video playback is implemented. - -*Note: Video playback requires hardware capabilities such as display, audio, and codec.* - -1. A third-party application obtains a surface ID from the XComponent. -2. The third-party application transfers the surface ID to the VideoPlayer JS. -3. The media service flushes the frame data to the surface buffer. - -## Compatibility - -Use the mainstream playback formats and resolutions, rather than custom ones to avoid playback failures, frame freezing, and artifacts. The system is not affected by incompatibility issues. If such an issue occurs, you can exit stream playback mode. - -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| - -## How to Develop - -For details about the APIs, see [VideoPlayer in the Media API](../reference/apis/js-apis-media.md#videoplayer8). - -### Full-Process Scenario - -The full video playback process includes creating an instance, setting the URL, setting the surface ID, preparing for video playback, playing video, pausing playback, obtaining track information, seeking to a playback position, setting the volume, setting the playback speed, stopping playback, resetting the playback configuration, and releasing resources. - -For details about the **url** types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes). - -For details about how to create an XComponent, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md). - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' -export class VideoPlayerDemo { - // Report an error in the case of a function invocation failure. - failureCallback(error) { - console.info(`error happened,error Name is ${error.name}`); - console.info(`error happened,error Code is ${error.code}`); - console.info(`error happened,error Message is ${error.message}`); - } - - // Report an error in the case of a function invocation exception. - catchCallback(error) { - console.info(`catch error happened,error Name is ${error.name}`); - console.info(`catch error happened,error Code is ${error.code}`); - console.info(`catch error happened,error Message is ${error.message}`); - } - - // Used to print the video track information. - printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('key is ' + item); - console.info('value is ' + property); - } - } - - async videoPlayerDemo() { - let videoPlayer = undefined; - let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. For details about the document link, see the method of creating the XComponent. - let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - // Call createVideoPlayer to create a VideoPlayer instance. - await media.createVideoPlayer().then((video) => { - if (typeof (video) != 'undefined') { - console.info('createVideoPlayer success!'); - videoPlayer = video; - } else { - console.info('createVideoPlayer fail!'); +OpenHarmony provides two solutions for video playback development: + +- [AVPlayer](using-avplayer-for-playback.md) class: provides ArkTS and JS APIs to implement audio and video playback. It also supports parsing streaming media and local assets, decapsulating media assets, decoding video, and rendering video. It is applicable to end-to-end playback of media assets and can be used to play video files in MP4 and MKV formats. + +- component: encapsulates basic video playback capabilities. It can be used to play video files after the data source and basic information are set. However, its scalability is poor. This component is provided by ArkUI. For details about how to use this component for video playback development, see [Video Component](../ui/arkts-common-components-video-player.md). + +In this topic, you will learn how to use the AVPlayer to develop a video playback service that plays a complete video file. If you want the application to continue playing the video in the background or when the screen is off, you must use the [AVSession](avsession-overview.md) and [continuous task](../task-management/continuous-task-dev-guide.md) to prevent the playback from being forcibly interrupted by the system. + +## Development Guidelines + +The full playback process includes creating an **AVPlayer** instance, setting the media asset to play and the window to display the video, setting playback parameters (volume, speed, and scale type), controlling playback (play, pause, seek, and stop), resetting the playback configuration, and releasing the instance. During application development, you can use the **state** attribute of the AVPlayer to obtain the AVPlayer state or call **on('stateChange')** to listen for state changes. If the application performs an operation when the AudioPlayer is not in the given state, the system may throw an exception or generate other undefined behavior. + +**Figure 1** Playback state transition + +![Playback state change](figures/video-playback-status-change.png) + +For details about the state, see [AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9). When the AVPlayer is in the **prepared**, **playing**, **paused**, or **completed** state, the playback engine is working and a large amount of RAM is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the instance. + +### How to Develop + +Read [AVPlayer](../reference/apis/js-apis-media.md#avplayer9) for the API reference. + +1. Call **createAVPlayer()** to create an **AVPlayer** instance. The AVPlayer is the **idle** state. + +2. Set the events to listen for, which will be used in the full-process scenario. The table below lists the supported events. + | Event Type| Description| + | -------- | -------- | + | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVPlayer.| + | error | Mandatory; used to listen for AVPlayer errors.| + | durationUpdate | Used to listen for progress bar updates to refresh the media asset 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.
This event is reported when the AVPlayer seeks to the playback position specified in **seek()**.| + | speedDone | Used to listen for the completion status of the **setSpeed()** request.
This event is reported when the AVPlayer plays video at the speed specified in **setSpeed()**.| + | volumeChange | Used to listen for the completion status of the **setVolume()** request.
This event is reported when the AVPlayer plays video at the volume specified in **setVolume()**.| + | bitrateDone | Used to listen for the completion status of the **setBitrate()** request, which is used for HTTP Live Streaming (HLS) streams.
This event is reported when the AVPlayer plays video at the bit rate specified in **setBitrate()**.| + | 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. This event is used together with the **audioInterruptMode** attribute.
This event is reported when the current audio playback is interrupted by another (for example, when a call is coming), so the application can process the event in time.| + +3. Set the media asset URL. The AVPlayer enters the **initialized** state. + > **NOTE** + > + > The URL in the code snippet below is for reference only. You need to check the media asset validity and set the URL based on service requirements. + > + > - If local files are used for playback, ensure that the files are available and the application sandbox path is used for access. For details about how to obtain the application sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). + > + > - If a network playback path is used, you must request the ohos.permission.INTERNET [permission](../security/accesstoken-guidelines.md). + > + > - You can also use **ResourceManager.getRawFd** to obtain the file descriptor of a file packed in the HAP file. For details, see [ResourceManager API Reference](../reference/apis/js-apis-resource-manager.md#getrawfd9). + > + > - The [playback formats and protocols](avplayer-avrecorder-overview.md#supported-formats-and-protocols) in use must be those supported by the system. + +4. Obtain and set the surface ID of the window to display the video. + The application obtains the surface ID from the XComponent. For details about the process, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md). + +5. Call **prepare()** to switch the AVPlayer to the **prepared** state. In this state, you can obtain the duration of the media asset to play and set the scale type and volume. + +6. Call **play()**, **pause()**, **seek()**, and **stop()** to perform video playback control as required. + +7. (Optional) Call **reset()** to reset the AVPlayer. The AVPlayer enters the **idle** state again and you can change the media asset URL. + +8. Call **release()** to switch the AVPlayer to the **released** state. Now your application exits the playback. + + +### Sample Code + + +```ts +import media from '@ohos.multimedia.media'; +import fs from '@ohos.file.fs'; +import common from '@ohos.app.ability.common'; + +export class AVPlayerDemo { + private avPlayer; + private count: number = 0; + private surfaceID: string; // The surfaceID parameter specifies the window used to display the video. Its value is obtained through the XComponent. + + // Set AVPlayer callback functions. + setAVPlayerCallback() { + // Callback function for the seek operation. + this.avPlayer.on('seekDone', (seekDoneTime) => { + console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`); + }) + // Callback function for errors. If an error occurs during the operation on the AVPlayer, reset() is called to reset the AVPlayer. + this.avPlayer.on('error', (err) => { + console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); + this.avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. + }) + // 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('AVPlayer state idle called.'); + this.avPlayer.release(); // Call release() to release the instance. + break; + case 'initialized': // This state is reported when the AVPlayer sets the playback source. + console.info('AVPlayerstate initialized called.'); + this.avPlayer.surfaceId = this.surfaceID // Set the window to display the video. This setting is not required when a pure audio asset is to be played. + this.avPlayer.prepare().then(() => { + console.info('AVPlayer prepare succeeded.'); + }, (err) => { + console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); + }); + break; + case 'prepared': // This state is reported upon a successful callback of prepare(). + console.info('AVPlayer 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('AVPlayer state playing called.'); + if (this.count !== 0) { + console.info('AVPlayer start to seek.'); + this.avPlayer.seek (this.avPlayer.duration); // Call seek() to seek to the end of the video clip. + } else { + this.avPlayer.pause(); // Call pause() to pause the playback. + } + this.count++; + break; + case 'paused': // This state is reported upon a successful callback of pause(). + console.info('AVPlayer state paused called.'); + this.avPlayer.play(); // Call play() again to start playback. + break; + case 'completed': // This state is reported upon the completion of the playback. + console.info('AVPlayer 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('AVPlayer state stopped called.'); + this.avPlayer.reset(); // Call reset() to reset the AVPlayer state. + break; + case 'released': + console.info('AVPlayer state released called.'); + break; + default: + console.info('AVPlayer state unknown called.'); + break; } - }, this.failureCallback).catch(this.catchCallback); - // Set the playback source for the player. - videoPlayer.url = fdPath; - - // Set the surface ID to display the video image. - await videoPlayer.setDisplaySurface(surfaceID).then(() => { - console.info('setDisplaySurface success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the prepare API to prepare for playback. - await videoPlayer.prepare().then(() => { - console.info('prepare success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the play API to start playback. - await videoPlayer.play().then(() => { - console.info('play success'); - }, this.failureCallback).catch(this.catchCallback); - - // Pause playback. - await videoPlayer.pause().then(() => { - console.info('pause success'); - }, this.failureCallback).catch(this.catchCallback); - - // Use a promise to obtain the video track information communication_dsoftbus. - let arrayDescription; - await videoPlayer.getTrackDescription().then((arrlist) => { - if (typeof (arrlist) != 'undefined') { - arrayDescription = arrlist; - } else { - console.log('video getTrackDescription fail'); - } - }, this.failureCallback).catch(this.catchCallback); - - for (let i = 0; i < arrayDescription.length; i++) { - this.printfDescription(arrayDescription[i]); - } - - // Seek to the 50s position. For details about the input parameters, see the API document. - let seekTime = 50000; - await videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { - console.info('seek success'); - }, this.failureCallback).catch(this.catchCallback); - - // Set the volume. For details about the input parameters, see the API document. - let volume = 0.5; - await videoPlayer.setVolume(volume).then(() => { - console.info('setVolume success'); - }, this.failureCallback).catch(this.catchCallback); - - // Set the playback speed. For details about the input parameters, see the API document. - let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; - await videoPlayer.setSpeed(speed).then(() => { - console.info('setSpeed success'); - }, this.failureCallback).catch(this.catchCallback); - - // Stop playback. - await videoPlayer.stop().then(() => { - console.info('stop success'); - }, this.failureCallback).catch(this.catchCallback); - - // Reset the playback configuration. - await videoPlayer.reset().then(() => { - console.info('reset success'); - }, this.failureCallback).catch(this.catchCallback); - - // Release playback resources. - await videoPlayer.release().then(() => { - console.info('release success'); - }, this.failureCallback).catch(this.catchCallback); - - // Set the related instances to undefined. - videoPlayer = undefined; - surfaceID = undefined; - } -} -``` - -### Normal Playback Scenario - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' -export class VideoPlayerDemo { - // Report an error in the case of a function invocation failure. - failureCallback(error) { - console.info(`error happened,error Name is ${error.name}`); - console.info(`error happened,error Code is ${error.code}`); - console.info(`error happened,error Message is ${error.message}`); - } - - // Report an error in the case of a function invocation exception. - catchCallback(error) { - console.info(`catch error happened,error Name is ${error.name}`); - console.info(`catch error happened,error Code is ${error.code}`); - console.info(`catch error happened,error Message is ${error.message}`); - } - - // Used to print the video track information. - printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('key is ' + item); - console.info('value is ' + property); - } - } - - async videoPlayerDemo() { - let videoPlayer = undefined; - let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. For details about the document link, see the method of creating the XComponent. - let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; + }) + } + + // The following demo shows how to use the file system to open the sandbox address, obtain the media file address, and play the media file using the URL attribute. + async avPlayerUrlDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + let fdPath = 'fd://'; + let context = getContext(this) as common.UIAbilityContext; + // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. + let pathDir = context.filesDir; + let path = pathDir + '/H264_AAC.mp4'; + // Open the corresponding file address to obtain the file descriptor and assign a value to the URL to trigger the reporting of the initialized state. let file = await fs.open(path); fdPath = fdPath + '' + file.fd; - // Call createVideoPlayer to create a VideoPlayer instance. - await media.createVideoPlayer().then((video) => { - if (typeof (video) != 'undefined') { - console.info('createVideoPlayer success!'); - videoPlayer = video; - } else { - console.info('createVideoPlayer fail!'); - } - }, this.failureCallback).catch(this.catchCallback); - // Set the playback source for the player. - videoPlayer.url = fdPath; - - // Set the surface ID to display the video image. - await videoPlayer.setDisplaySurface(surfaceID).then(() => { - console.info('setDisplaySurface success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the prepare API to prepare for playback. - await videoPlayer.prepare().then(() => { - console.info('prepare success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the play API to start playback. - await videoPlayer.play().then(() => { - console.info('play success'); - }, this.failureCallback).catch(this.catchCallback); - - // Stop playback. - await videoPlayer.stop().then(() => { - console.info('stop success'); - }, this.failureCallback).catch(this.catchCallback); - - // Release playback resources. - await videoPlayer.release().then(() => { - console.info('release success'); - }, this.failureCallback).catch(this.catchCallback); - - // Set the related instances to undefined. - videoPlayer = undefined; - surfaceID = undefined; + this.avPlayer.url = fdPath; + } + + // The following demo shows how to use resourceManager to obtain the media file packed in the HAP file and play the media file by using the fdSrc attribute. + async avPlayerFdSrcDemo() { + // Create an AVPlayer instance. + this.avPlayer = await media.createAVPlayer(); + // Set a callback function for state changes. + this.setAVPlayerCallback(); + // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. + // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. + let context = getContext(this) as common.UIAbilityContext; + let fileDescriptor = await context.resourceManager.getRawFd('H264_AAC.mp4'); + // Assign a value to fdSrc to trigger the reporting of the initialized state. + this.avPlayer.fdSrc = fileDescriptor; } } ``` -### Switching to the Next Video Clip - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' -export class VideoPlayerDemo { - // Report an error in the case of a function invocation failure. - failureCallback(error) { - console.info(`error happened,error Name is ${error.name}`); - console.info(`error happened,error Code is ${error.code}`); - console.info(`error happened,error Message is ${error.message}`); - } - - // Report an error in the case of a function invocation exception. - catchCallback(error) { - console.info(`catch error happened,error Name is ${error.name}`); - console.info(`catch error happened,error Code is ${error.code}`); - console.info(`catch error happened,error Message is ${error.message}`); - } - - // Used to print the video track information. - printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('key is ' + item); - console.info('value is ' + property); - } - } - - async videoPlayerDemo() { - let videoPlayer = undefined; - let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. For details about the document link, see the method of creating the XComponent. - let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; - let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.mp4'; - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - // Call createVideoPlayer to create a VideoPlayer instance. - await media.createVideoPlayer().then((video) => { - if (typeof (video) != 'undefined') { - console.info('createVideoPlayer success!'); - videoPlayer = video; - } else { - console.info('createVideoPlayer fail!'); - } - }, this.failureCallback).catch(this.catchCallback); - // Set the playback source for the player. - videoPlayer.url = fdPath; - - // Set the surface ID to display the video image. - await videoPlayer.setDisplaySurface(surfaceID).then(() => { - console.info('setDisplaySurface success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the prepare API to prepare for playback. - await videoPlayer.prepare().then(() => { - console.info('prepare success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the play API to start playback. - await videoPlayer.play().then(() => { - console.info('play success'); - }, this.failureCallback).catch(this.catchCallback); - - // Reset the playback configuration. - await videoPlayer.reset().then(() => { - console.info('reset success'); - }, this.failureCallback).catch(this.catchCallback); - - // Obtain the next video FD address. - fdPath = 'fd://' - let nextFile = await fs.open(nextPath); - fdPath = fdPath + '' + nextFile.fd; - // Set the second video playback source. - videoPlayer.url = fdPath; - - // Call the prepare API to prepare for playback. - await videoPlayer.prepare().then(() => { - console.info('prepare success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the play API to start playback. - await videoPlayer.play().then(() => { - console.info('play success'); - }, this.failureCallback).catch(this.catchCallback); - - // Release playback resources. - await videoPlayer.release().then(() => { - console.info('release success'); - }, this.failureCallback).catch(this.catchCallback); - - // Set the related instances to undefined. - videoPlayer = undefined; - surfaceID = undefined; - } -} -``` - -### Looping a Video Clip - -```js -import media from '@ohos.multimedia.media' -import fs from '@ohos.file.fs' -export class VideoPlayerDemo { - // Report an error in the case of a function invocation failure. - failureCallback(error) { - console.info(`error happened,error Name is ${error.name}`); - console.info(`error happened,error Code is ${error.code}`); - console.info(`error happened,error Message is ${error.message}`); - } - - // Report an error in the case of a function invocation exception. - catchCallback(error) { - console.info(`catch error happened,error Name is ${error.name}`); - console.info(`catch error happened,error Code is ${error.code}`); - console.info(`catch error happened,error Message is ${error.message}`); - } - - // Used to print the video track information. - printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('key is ' + item); - console.info('value is ' + property); - } - } - - async videoPlayerDemo() { - let videoPlayer = undefined; - let surfaceID = 'test' // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API. For details about the document link, see the method of creating the XComponent. - let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4'; - let file = await fs.open(path); - fdPath = fdPath + '' + file.fd; - // Call createVideoPlayer to create a VideoPlayer instance. - await media.createVideoPlayer().then((video) => { - if (typeof (video) != 'undefined') { - console.info('createVideoPlayer success!'); - videoPlayer = video; - } else { - console.info('createVideoPlayer fail!'); - } - }, this.failureCallback).catch(this.catchCallback); - // Set the playback source for the player. - videoPlayer.url = fdPath; - - // Set the surface ID to display the video image. - await videoPlayer.setDisplaySurface(surfaceID).then(() => { - console.info('setDisplaySurface success'); - }, this.failureCallback).catch(this.catchCallback); - - // Call the prepare API to prepare for playback. - await videoPlayer.prepare().then(() => { - console.info('prepare success'); - }, this.failureCallback).catch(this.catchCallback); - // Set the loop playback attribute. - videoPlayer.loop = true; - // Call the play API to start loop playback. - await videoPlayer.play().then(() => { - console.info('play success, loop value is ' + videoPlayer.loop); - }, this.failureCallback).catch(this.catchCallback); - } -} -``` + \ No newline at end of file diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md deleted file mode 100644 index fd9de91b4bae0591e2a5dc4869455bdd4055943e..0000000000000000000000000000000000000000 --- a/en/application-dev/media/video-recorder.md +++ /dev/null @@ -1,160 +0,0 @@ -# Video Recording Development - -## Introduction - -You can use video recording APIs to capture audio and video signals, encode them, and save them to files. You can start, suspend, resume, and stop recording, and release resources. You can also specify parameters such as the encoding format, encapsulation format, and file path for video recording. - -## Working Principles - -The following figures show the video recording state transition and the interaction with external modules for video recording. - -**Figure 1** Video recording state transition - -![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) - -**Figure 2** Interaction with external modules for video recording - -![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) - -**NOTE**: When a third-party camera application or system camera calls a JS interface provided by the JS interface layer, the framework layer uses the media service of the native framework to invoke the audio component. Through the audio HDI, the audio component captures audio data, encodes the audio data through software, and saves the encoded audio data to a file. The graphics subsystem captures image data through the video HDI, encodes the image data through the video codec HDI, and saves the encoded image data to a file. In this way, video recording is implemented. - -## Constraints - -Before developing video recording, configure the permissions **ohos.permission.MICROPHONE** and **ohos.permission.CAMERA** for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). - -## How to Develop - -For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md#videorecorder9). - -### Full-Process Scenario - -The full video recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources. - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' -export class VideoRecorderDemo { - private testFdNumber; // Used to save the FD address. - // pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Video/01.mp4. - // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. - async getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - this.testFdNumber = "fd://" + fdNumber.toString(); - } - } - - // Error callback triggered in the case of an error - failureCallback(error) { - console.info('error happened, error name is ' + error.name); - console.info('error happened, error code is ' + error.code); - console.info('error happened, error message is ' + error.message); - } - - // Error callback triggered in the case of an exception - catchCallback(error) { - console.info('catch error happened, error name is ' + error.name); - console.info('catch error happened, error code is ' + error.code); - console.info('catch error happened, error message is ' + error.message); - } - - async videoRecorderDemo() { - let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called. - let surfaceID = null; // Used to save the surface ID returned by getInputSurface. - // Obtain the FD address of the video to be recorded. - await this.getFd('01.mp4'); - // Configure the parameters related to video recording based on those supported by the hardware device. - let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 2000000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 - } - - let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : this.testFdNumber, // testFdNumber is generated by getFd. - orientationHint : 0, - location : { latitude : 30, longitude : 130 } - } - // Create a VideoRecorder object. - await media.createVideoRecorder().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); - - // Call the prepare API to prepare for video recording. - await videoRecorder.prepare(videoConfig).then(() => { - console.info('prepare success'); - }, this.failureCallback).catch(this.catchCallback); - - // Obtain the surface ID, save it, and pass it to camera-related APIs. - await videoRecorder.getInputSurface().then((surface) => { - console.info('getInputSurface success'); - surfaceID = surface; - }, 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. For details about how to call the camera APIs, see the samples. - // 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); - - // Release the video recording resources and camera object resources. - await videoRecorder.release().then(() => { - console.info('release success'); - }, this.failureCallback).catch(this.catchCallback); - - // Set the related object to null. - videoRecorder = undefined; - surfaceID = undefined; - } -} -``` - diff --git a/en/application-dev/media/video-recording.md b/en/application-dev/media/video-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..8eabb4e1aad61f954135832ff2e5439912acdb34 --- /dev/null +++ b/en/application-dev/media/video-recording.md @@ -0,0 +1,237 @@ +# Video Recording + +OpenHarmony provides the AVRecorder for you to develop the video recording service. The AVRecorder supports audio recording, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple video recording scenarios and can be used to generate local video files directly. + +You will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping recording. + +During application development, you can use the **state** attribute of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state. + +**Figure 1** Recording state transition + +![Recording state change](figures/video-recording-status-change.png) + +For details about the state, see [AVRecorderState](../reference/apis/js-apis-media.md#avrecorderstate9). + +## How to Develop + +> **NOTE** +> +> The AVRecorder only processes video data. To complete video recording, it must work with the video data collection module, which transfers the captured video data to the AVRecorder for data processing through the surface. A typical video data collection module is the camera module, which currently is available only to system applications. For details, see [Camera](../reference/apis/js-apis-camera.md). + +Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API reference. + +1. Create an **AVRecorder** instance. The AVRecorder is the **idle** state. + + ```ts + import media from '@ohos.multimedia.media' + let avRecorder + media.createAVRecorder().then((recorder) => { + avRecorder = recorder + }, (error) => { + console.error('createAVRecorder failed') + }) + ``` + +2. Set the events to listen for. + | Event Type| Description| + | -------- | -------- | + | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.| + | error | Mandatory; used to listen for AVRecorder errors.| + + ```ts + // Callback function for state changes. + avRecorder.on('stateChange', (state, reason) => { + console.info('current state is: ' + state); + }) + // Callback function for errors. + avRecorder.on('error', (err) => { + console.error('error happened, error message is ' + err); + }) + ``` + +3. Set video recording parameters and call **prepare()**. The AVRecorder enters the **prepared** state. + > **NOTE** + > + > Pay attention to the following when configuring parameters: + > + > - In pure video recording scenarios, set only video-related parameters in **avConfig** of **prepare()**. + > If audio-related parameters are configured, the system regards it as audio and video recording. + > + > - The [recording specifications](avplayer-avrecorder-overview.md#supported-formats) in use must be those supported. The video bit rate, resolution, and frame rate are subject to the ranges supported by the hardware device. + > + > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md). + + ```ts + let avProfile = { + fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. + videoBitrate: 200000, // Video bit rate. + videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. + videoFrameWidth: 640, // Video frame width. + videoFrameHeight: 480, // Video frame height. + videoFrameRate: 30 // Video frame rate. + } + let avConfig = { + videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. + profile : this.avProfile, + url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. + rotation: 0, // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270. + } + avRecorder.prepare(avConfig).then(() => { + console.info('avRecorder prepare success') + }, (error) => { + console.error('avRecorder prepare failed') + }) + ``` + +4. Obtain the surface ID required for video recording. + + Call **getInputSurface()**. The returned surface ID is transferred to the video data collection module (video input source), which is the camera module in the sample code. + + The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data. + + ```ts + avRecorder.getInputSurface().then((surfaceId) => { + console.info('avRecorder getInputSurface success') + }, (error) => { + console.error('avRecorder getInputSurface failed') + }) + ``` + +5. Initialize the video data input source. + + This step is performed in the video data collection module. For the camera module, you need to create a **Camera** instance, obtain the camera list, create a camera input stream, and create a video output stream. For details, see [Recording](camera-recording-case.md). + +6. Start recording. + + Start the input source to input video data, for example, by calling **camera.VideoOutput.start**. Then call **AVRecorder.start()** to switch the AVRecorder to the **started** state. + +7. Call **pause()** to pause recording. The AVRecorder enters the **paused** state. In addition, pause data input in the video data collection module, for example, by calling **camera.VideoOutput.stop**. + +8. Call **resume()** to resume recording. The AVRecorder enters the **started** state again. + +9. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording in the video data collection module. + +10. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. + +11. Call **release()** to release the resources. The AVRecorder enters the **released** state. In addition, release the video data input source resources (camera resources in this example). + + +## Sample Code + +Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording. + + +```ts +import media from '@ohos.multimedia.media' +const TAG = 'VideoRecorderDemo:' +export class VideoRecorderDemo { + private avRecorder; + private videoOutSurfaceId; + private avProfile = { + fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. + videoBitrate : 100000, // Video bit rate. + videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. + videoFrameWidth: 640, // Video frame width. + videoFrameHeight: 480, // Video frame height. + videoFrameRate: 30 // Video frame rate. + } + private avConfig = { + videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. + profile : this.avProfile, + url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. + rotation: 0, // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270. + } + + // Set AVRecorder callback functions. + setAvRecorderCallback() { + // Callback function for state changes. + this.avRecorder.on('stateChange', (state, reason) => { + console.info(TAG + 'current state is: ' + state); + }) + // Callback function for errors. + this.avRecorder.on('error', (err) => { + console.error(TAG + 'error ocConstantSourceNode, error message is ' + err); + }) + } + + // Complete camera-related preparations. + async prepareCamera() { + // For details on the implementation, see the camera document. + } + + // Start the camera stream output. + async startCameraOutput() { + // Call start of the VideoOutput class to start video output. + } + + // Stop the camera stream output. + async stopCameraOutput() { + // Call stop of the VideoOutput class to stop video output. + } + + // Release the camera instance. + async releaseCamera() { + // Release the instances created during camera preparation. + } + + // Process of starting recording. + async startRecordingProcess() { + // 1. Create an AVRecorder instance. + this.avRecorder = await media.createAVRecorder(); + this.setAvRecorderCallback(); + // 2. Obtain the file descriptor of the recorded file. The obtained file descriptor is passed in to the URL in avConfig. The implementation is omitted here. + // 3. Set recording parameters to complete the preparations. + await this.avRecorder.prepare(this.avConfig); + this.videoOutSurfaceId = await this.avRecorder.getInputSurface(); + // 4. Complete camera-related preparations. + await this.prepareCamera(); + // 5. Start the camera stream output. + await this.startCameraOutput(); + // 6. Start recording. + await this.videoRecorder.start(); + } + + // Process of pausing recording. + async pauseRecordingProcess() { + if (this.avRecorder.state ==='started') { // pause() can be called only when the AVRecorder is in the started state . + await this.avRecorder.pause(); + await this.stopCameraOutput(); // Stop the camera stream output. + } + } + + // Process of resuming recording. + async resumeRecordingProcess() { + if (this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state . + await this.startCameraOutput(); // Start camera stream output. + await this.avRecorder.resume(); + } + } + + async stopRecordingProcess() { + // 1. Stop recording. + if (this.avRecorder.state === 'started' + || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state. + await this.avRecorder.stop(); + await this.stopCameraOutput(); + } + // 2. Reset the AVRecorder. + await this.avRecorder.reset(); + // 3. Release the AVRecorder instance. + await this.avRecorder.release(); + // 4. After the file is recorded, close the file descriptor. The implementation is omitted here. + // 5. Release the camera instance. + await this.releaseCamera(); + } + + // Complete sample code for starting, pausing, resuming, and stopping recording. + async videoRecorderDemo() { + await this.startRecordingProcess(); // Start recording. + // You can set the recording duration. For example, you can set the sleep mode to prevent code execution. + await this.pauseRecordingProcess(); // Pause recording. + await this.resumeRecordingProcess(); // Resume recording. + await this.stopRecordingProcess(); // Stop recording. + } +} +``` + + \ No newline at end of file diff --git a/en/application-dev/media/volume-management.md b/en/application-dev/media/volume-management.md new file mode 100644 index 0000000000000000000000000000000000000000..f6461d968856c7d865c999ab9c604e5ef718548b --- /dev/null +++ b/en/application-dev/media/volume-management.md @@ -0,0 +1,48 @@ +# Volume Management + +You can use different APIs to manage the system volume and audio stream volume. The system volume and audio stream volume refer to the volume of a OpenHarmony device and the volume of a specified audio stream, respectively. The audio stream volume is restricted by the system volume. + +## System Volume + +The API for managing the system volume is **AudioVolumeManager**. Before using this API, you must call **getVolumeManager()** to obtain an **AudioVolumeManager** instance. Currently, this API can be used to obtain volume information and listen for volume changes. It cannot be used to adjust the system volume. + +```ts +import audio from '@ohos.multimedia.audio'; +let audioManager = audio.getAudioManager(); +let audioVolumeManager = audioManager.getVolumeManager(); +``` + +### Listening for System Volume Changes + +You can set an event to listen for system volume changes. + +```ts +audioVolumeManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +}); +``` + +### Adjusting the System Volume (for System Applications Only) + +Currently, the system volume is mainly adjusted by using system APIs, which serve the physical volume button and the Settings application. When the user presses the volume button, a system API is called to adjust the system volume, including the volume for media, ringtone, or notification. + +## Audio Stream Volume + +The API for managing the audio stream volume is **setVolume()** in the **AVPlayer** or **AudioRenderer** class. The code snippet below is used for setting the audio stream volume by using the **AVPlayer** class: + +```ts +let volume = 1.0 // Specified volume. The value range is [0.00-1.00]. The value 1 indicates the maximum volume. +avPlayer.setVolume(volume) +``` + +The code snippet below is used for setting the audio stream volume by using the **AudioRenderer** class: + +```ts +audioRenderer.setVolume(0.5).then(data=>{ // The volume range is [0.0-1.0]. + console.info('Invoke setVolume succeeded.'); +}).catch((err) => { + console.error(`Invoke setVolume failed, code is ${err.code}, message is ${err.message}`); +}); +``` diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md index a48a081a3e69ea8259727efd343264f80c6cc284..22d85aec0fe405e47cd92abeafa94ba5e7b7ed5f 100644 --- a/en/application-dev/napi/drawing-guidelines.md +++ b/en/application-dev/napi/drawing-guidelines.md @@ -189,7 +189,7 @@ The following steps describe how to use the text drawing and display feature of OH_Drawing_CreateFontCollection()); OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle); // Set the text content. - const char* text = "OpenHarmony\n"; + const char* text = "Hello World\n"; OH_Drawing_TypographyHandlerAddText(handler, text); OH_Drawing_TypographyHandlerPopTextStyle(handler); OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler); diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md index 8090e7e835dae7f0658127fafbf04680a4e81114..db7cae812218c2f7b6c363d204baa04dfeeb639f 100644 --- a/en/application-dev/notification/progress-bar-notification.md +++ b/en/application-dev/notification/progress-bar-notification.md @@ -3,7 +3,7 @@ The progress notification is a commonly used notification type, mainly used to display the progress of an ongoing operation, such as file downloading. When publishing a progress notification through the notification subsystem, you can use the readily available template by specifying the related attributes, such as the template name and template data. -In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data. +In the [NotificationTemplate](../reference/apis/js-apis-inner-notification-notificationTemplate.md), which can only be of the progress type, **data** indicates custom template data. ## Available APIs diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md index f68ec8ee66f92910e0f11c4a8b705bfd7bbfd08d..cbc97f24e80d576f747d69eeeaec89f50c264283 100644 --- a/en/application-dev/quick-start/app-configuration-file.md +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -19,7 +19,9 @@ This document gives an overview of the **app.json5** configuration file. To star "debug": false, "car": { "minAPIVersion": 8, - } + }, + "targetBundleName": "com.application.test", + "targetPriority": 50 }, } ``` @@ -28,11 +30,12 @@ This document gives an overview of the **app.json5** configuration file. To star As shown above, the **app.json5** file contains several tags. -**Table 1** Tags in the app.json5 file + **Table 1** Tags in the app.json5 file | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:
- Consists of letters, digits, underscores (_), and periods (.).
- Starts with a letter.
- Contains 7 to 127 bytes.
You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| +| bundleType| Bundle type, which is used to distinguish applications and atomic services.
- **app**: The bundle is a common application.
- **atomicService**: The bundle is an atomic service.
- **shared**: The bundle is a shared object application. | String| Yes (initial value: **"app"**)| | debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.
- **true**: The application can be debugged.
- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| | icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No| | label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No| @@ -51,3 +54,5 @@ As shown above, the **app.json5** file contains several tags. | wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | car | Head unit–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on head units, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | default | Default device–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +|targetBundleName|Target application name of the bundle. The value rule and range are the same as those of **bundleName**.|String|Yes (if the initial value is used, the target application is not an application with the overlay feature)| +|targetPriority|Priority of the application. When **targetBundleName** is set, the application is an application with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)| diff --git a/en/application-dev/quick-start/application-package-structure-fa.md b/en/application-dev/quick-start/application-package-structure-fa.md index 6909481445ecb1219c30ed3ae425d6b475662805..a9d647385fa9b5e9a47ebcf4ea77e546d4df3108 100644 --- a/en/application-dev/quick-start/application-package-structure-fa.md +++ b/en/application-dev/quick-start/application-package-structure-fa.md @@ -11,7 +11,7 @@ The difference between the application package structures in the FA model and st - The **assets** folder is a collection of all the resource files, library files, and code files in a HAP file. It can be further organized into the **entry** folder and the **js** folder. The **entry** folder stores the **resources** folder and the **resources.index** file. -- The **resources** folder stores resource files (such as strings and images) of the application. +- The **resources** folder stores resource files (such as strings and images) of the application. For details, see [Resource Categories and Access](resource-categories-and-access.md). - The **resources.index** file provides a resource index table, which is generated by DevEco Studio invoking the specific SDK tool. diff --git a/en/application-dev/quick-start/application-package-structure-stage.md b/en/application-dev/quick-start/application-package-structure-stage.md index cb6dc3b12ef12ff249d8afaa9871f901babd9412..0736157fd42b4b6b6a2549e9262a7d25313aa452 100644 --- a/en/application-dev/quick-start/application-package-structure-stage.md +++ b/en/application-dev/quick-start/application-package-structure-stage.md @@ -22,7 +22,7 @@ To develop an application based on the [stage model](application-configuration-f - The HAP file includes folders such as **ets**, **libs**, and **resources** and files such as **resources.index**, **module.json**, and **pack.info**. - The **ets** folder stores bytecode files generated after application code build. - The **libs** folder stores library files, which are .so binary files that contain third-party code on which the OpenHarmony application depends. - - The **resources** folder stores resource files (such as strings and images) of the application. + - The **resources** folder stores resource files (such as strings and images) of the application. For details, see [Resource Categories and Access](resource-categories-and-access.md). - The **resources.index** file provides a resource index table, which is generated when the application project is built in DevEco Studio. - The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md). - The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. diff --git a/en/application-dev/quick-start/atomicService.md b/en/application-dev/quick-start/atomicService.md new file mode 100644 index 0000000000000000000000000000000000000000..2c2216bfc22b87411408d2753f04955b89a852f6 --- /dev/null +++ b/en/application-dev/quick-start/atomicService.md @@ -0,0 +1,218 @@ +# Atomic Service + +## Pre-loading by HAP Type + +### HAP File Implementation + +To speed up the initial startup of an atomic service, you can configure it to load on demand with the use of HAP files. HAP files of an atomic service are classified as entry-type or feature-type. The entry-type HAP file contains the page code and related resources required for starting up the atomic service. The feature-type HAP files contain the rest of the code and resources. To start the atomic service, the user only needs to download and install the entry-type HAP file, which minimizes the time for downloading the atomic service. + +#### How to Use + +You create HAP files of an atomic service by creating an atomic service project in DevEco Studio. The basic project directory structure is as follows: + +``` +├── AppScope +| ├── resources +| └── app.json5 +├── entry +| └── src/main +| ├── ets +| ├── resources +| └── module.json5 +├── feature +| └── src/main +| ├── ets +| ├── resources +| └── module.json5 +├── library +| └── src/main +| ├── ets +| ├── resources +| └── module.json5 +├── node_modules +``` + +Note that you must set the **bundleType** field to **atomicService** in the [app.json5](app-configuration-file.md) file, which is located in the **AppScope** folder. The following is an example of the file content: + +```json +{ + "app": { + "bundleName": "com.example.hmservice", + "bundleType":"atomicService", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "distributedNotificationEnabled": true, + "targetAPIVersion": 9 + } +} +``` + +For details about HAP files, see [Multi-HAP Design Objectives](multi-hap-objective.md). + +#### Restrictions + +1. The **installationFree** field must be set to **true** in each module-specific configuration file [module.json5](module-configuration-file.md) file. + +2. When packaging an atomic service, comply with the following size rules: + +- The total size of HAP files cannot exceed 10 MB. + +- The size of a HAP file itself and all its dependent [HSP](in-app-hsp.md) cannot exceed 2 MB. + + +### Pre-loading Implementation + +You can configure the system to automatically pre-download required modules when the atomic service enters a module, thereby speeding up module access. + +Currently, pre-loading can be implemented only through configuration, not by invoking APIs. + +#### How to Use + +Pre-loading is triggered after the first frame of the newly accessed module is rendered. You can configure what to pre-load for a module, by setting the **preloads** field under **atomicService** in the [module.json5](module-configuration-file.md) file of the module. The following is an example of the **module.json5** file of the **entry** module, saved in **entry/src/main**: + +```json +{ + "module": { + "name": "entry", + "type": "entry", + "srcEntrance": "./ets/Application/MyAbilityStage.ts", + "description": "$string:entry_desc", + "mainElement": "MainAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": true, + "pages": "$profile:main_pages", + "atomicService": { + "preloads": [ + { + "moduleName": "feature" + } + ] + }, + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:MainAbility_desc", + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:white", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ] + } +} +``` + +In this example, the system automatically pre-loads the **feature** module after the first frame of the **entry** module is rendered. + +#### Restrictions + +[moduleType](../reference/apis/js-apis-bundleManager.md#moduletype) corresponding to moduleName in the **preloads** list cannot be entry. + +## Using Dynamic Shared Packages in Atomic Services + +A [Harmony Shared Package (HSP)](shared-guide.md) is a dynamic shared package for sharing code, C++ libraries, resources, and configuration files among modules. +For details about how to use the HSP within an atomic service, see [In-Application HSP Development](in-app-hsp.md). + +#### How to Use + +Assume that the project directory structure is as follows: +``` +├── AppScope +| ├── resources +| └── app.json5 +├── entry +| └── src/main +| ├── ets +| ├── entryAbility +| └── pages +| └── Index.ets +| ├── resources +| └── module.json5 +├── feature +| └── src/main +| ├── ets +| ├── resources +| └── module.json5 +├── library +| └── src/main +| ├── ets +| └── pages +| └── menu.ets +| ├── resources +| └── module.json5 +├── node_modules +``` + +If you want to add a button in the **entry** module to jump to the menu page (**library/src/main/ets/pages/menu.ets**) in the **library** module, you can write the following code in the **entry/src/main/ets/MainAbility/Index.ets** file of the **entry** module: + +```ts +import router from '@ohos.router'; + +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + // Add a button to respond to user clicks. + Button() { + Text('click to menu') + .fontSize(30) + .fontWeight(FontWeight.Bold) + } + .type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('40%') + .height('5%') + // Bind click events. + .onClick(() => { + router.pushUrl({ + url: '@bundle:com.example.hmservice/library/ets/pages/menu' + }).then(() => { + console.log("push page success"); + }).catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +The input parameter **url** of the **router.pushUrl** API is as follows: +```ets +'@bundle:com.example.hmservice/library/ets/pages/menu' +``` +The **url** content template is as follows: +```ets +'@bundle:bundle name/module name/path/page file name (without the extension .ets)' +``` diff --git a/en/application-dev/quick-start/figures/application_details.jpg b/en/application-dev/quick-start/figures/application_details.jpg new file mode 100644 index 0000000000000000000000000000000000000000..02524b549eaf636e2a8a0f2ec869513d99f1a161 Binary files /dev/null and b/en/application-dev/quick-start/figures/application_details.jpg differ diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 8fca81167d6d016376877602de947c4c9cc83bd1..aeb16b360e08d9d89eb3594d28b75cd21f37ca59 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -59,7 +59,9 @@ This document gives an overview of the **module.json5** configuration file. To s } } ] - } + }, + "targetModuleName": "feature", + "targetPriority": 50 } ``` @@ -79,7 +81,7 @@ As shown above, the **module.json5** file contains several tags. | mainElement | Name of the entry UIAbility or ExtensionAbility of the module. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | [deviceTypes](#devicetypes) | Type of the device on which the module can run.| String array| No (can be left empty)| | deliveryWithInstall | Whether the HAP file of the module will be installed when the user installs the application.
- **true**: The HAP file will be installed when the user installs the application.
- **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| -| installationFree | Whether the module supports the installation-free feature.
- **true**: The module supports the installation-free feature and meets installation-free constraints.
- **false**: The module does not support the installation-free feature.
**NOTE**
- If this tag is set to **true** for an entry-type module, it must also be set to **true** for feature-type modules of the same application.
- If this tag is set to **false** for an entry-type module, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| +| installationFree | Whether the module supports the installation-free feature.
- **true**: The module supports the installation-free feature and meets installation-free constraints.
- **false**: The module does not support the installation-free feature.
**NOTE**
If this tag is set to **true** for an entry-type module, it must also be set to **true** for feature-type modules of the same application.
If this tag is set to **false** for an entry-type module, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| | virtualMachine | Type of the target virtual machine (VM) where the module runs. It is used for cloud distribution, such as distribution by the application market and distribution center.
If the target VM type is ArkTS engine, the value is **ark**+*version number*.| String| Yes (initial value: automatically inserted when DevEco Studio builds the HAP file)| | [pages](#pages)| Profile that represents information about each page in the current module. The value can contain a maximum of 255 bytes.| String| No in the UIAbility scenario| | [metadata](#metadata)| Custom metadata of the module. The setting is valid only for the current module, UIAbility, or ExtensionAbility.| Object array| Yes (initial value: left empty)| @@ -87,7 +89,10 @@ As shown above, the **module.json5** file contains several tags. | [extensionAbilities](#extensionabilities) | ExtensionAbility configuration of the module, which is valid only for the current ExtensionAbility component.| Object| Yes (initial value: left empty)| | [requestPermissions](#requestpermissions) | A set of permissions that the application needs to request from the system for running correctly.| Object| Yes (initial value: left empty)| | [testRunner](#testrunner) | Test runner configuration of the module.| Object| Yes (initial value: left empty)| - +| [atomicService](#atomicservice)| Atomic service configuration.| Object| Yes (initial value: left empty) | +| [dependencies](#dependencies)| List of shared libraries on which the current module depends during running.| Object array| Yes (initial value: left empty) | +| targetModuleName | Target module of the bundle. The value is a string with a maximum of 31 bytes. It must be unique in the entire application.|String|Yes (if the initial value is used, the target module is not a module with the overlay feature)| +| targetPriority | Priority of the module. When **targetModuleName** is set, the module is a module with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)| ## deviceTypes @@ -131,8 +136,21 @@ The **pages** tag is a profile that represents information about specified pages } ``` -Define the **main_pages.json** file under **resources/base/profile** in the development view. The base name of the file (**main_pages** in this example) can be customized, but must be consistent with the information specified by the **pages** tag. The file lists the page information of the current application. +Define the **main_pages.json** file under **resources/base/profile** in the development view. The file name (**main_pages** in this example) can be customized, but must be consistent with the information specified by the **pages** tag. The file lists the page information of the current application, including the route information and the window-related configuration. + + **Table 3** Tags in the pages configuration file +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| src | Route information about all pages in the JavaScript module, including the page path and page name. The value is an array, each element of which represents a page and the first element represents the home page.| String array| No| +| window | Window-related configuration. | Object| Yes (initial value: left empty)| + + **Table 4** window tag in the pages configuration file + +| 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**)| ```json { @@ -141,7 +159,11 @@ Define the **main_pages.json** file under **resources/base/profile** in the deve "pages/second/payment", "pages/third/shopping_cart", "pages/four/owner" - ] + ], + "window": { + "designWidth": 720, + "autoDesignWidth": false + } } ``` @@ -150,7 +172,7 @@ Define the **main_pages.json** file under **resources/base/profile** in the deve The **metadata** tag represents the custom metadata of the HAP file. The tag value is an array and contains three subtags: **name**, **value**, and **resource**. -**Table 3** metadata +**Table 5** metadata | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -165,7 +187,7 @@ The **metadata** tag represents the custom metadata of the HAP file. The tag val "metadata": [{ "name": "module_metadata", "value": "a test demo for module metadata", - "resource": "$profile:shortcuts_config", + "resource": "$profile:shortcuts_config" }], "abilities": [{ @@ -206,10 +228,13 @@ UIAbility configuration of the module, which is valid only for the current UIAbi The OpenHarmony system imposes a strict rule on the presence of application icons. If no icon is configured in the HAP file of an application, the system uses the icon specified in the **app.json** file as the application icon and displays it on the home screen. -Touching this icon will direct the user to the application details screen in **Settings**. +Touching this icon will direct the user to the application details screen in **Settings**, as shown in Figure 1. To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). +**Objectives**: + +This requirement on application icons is intended to prevent malicious applications from deliberately configuring no icon to block uninstallation attempts. **Setting the application icon to be displayed on the home screen**: @@ -231,40 +256,42 @@ Set **icon**, **label**, and **skills** under **abilities** in the **module.json }] }], ... - + } } ``` -**Querying an application icon:** -* The HAP file contains ability configuration. - * The application icon is set under **abilities** in the **module.json5** file. +**Display rules of application icons and labels on the home screen:** +* The HAP file contains UIAbility configuration. + * The application icon on the home screen is set under **abilities** in the **module.json5** file. * The application does not have the privilege to hide its icon from the home screen. - * The returned home screen icon is the icon configured for the ability. - * The returned home screen label is the label configured for the ability. If no label is configured, the bundle name is returned. - * The returned component name is the component name of the ability. - * When the user touches the home screen icon, the home screen of the ability is displayed. + * The application icon displayed on the home screen is the icon configured for the UIAbility. + * The application label displayed on the home screen is the label configured for the UIAbility. If no label is configured, the bundle name is returned. + * The name of the UIAbility is displayed. + * When the user touches the home screen icon, the home screen of the UIAbility is displayed. * The application has the privilege to hide its icon from the home screen. * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. - * The application icon is not set under **abilities** in the **module.json5** file. + * The application icon on the home screen is not set under **abilities** in the **module.json5** file. * The application does not have the privilege to hide its icon from the home screen. - * The returned home screen icon is the icon configured under **app**. (The **icon** parameter in the **app.json** file is mandatory.) - * The returned home screen label is the label configured under **app**. (The **label** parameter in the **app.json** file is mandatory.) - * The returned component name is the component name displayed on the application details screen (this component is built in the system). - * Touching the home screen icon will direct the user to the application details screen. + * The application icon displayed on the home screen is the icon specified under **app**. (The **icon** field in the **app.json** file is mandatory.) + * The application label displayed on the home screen is the label specified under **app**. (The **label** field in the **app.json** file is mandatory.) + * Touching the application icon on the home screen will direct the user to the application details screen shown in Figure 1. * The application has the privilege to hide its icon from the home screen. * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. -* The HAP file does not contain ability configuration. +* The HAP file does not contain UIAbility configuration. * The application does not have the privilege to hide its icon from the home screen. - * The returned home screen icon is the icon configured under **app**. (The **icon** parameter in the **app.json** file is mandatory.) - * The returned home screen label is the label configured under **app**. (The **label** parameter in the **app.json** file is mandatory.) - * The returned component name is the component name displayed on the application details screen (this component is built in the system). - * Touching the home screen icon will direct the user to the application details screen. + * The application icon displayed on the home screen is the icon specified under **app**. (The **icon** field in the **app.json** file is mandatory.) + * The application label displayed on the home screen is the label specified under **app**. (The **label** field in the **app.json** file is mandatory.) + * Touching the application icon on the home screen will direct the user to the application details screen shown in Figure 1. * The application has the privilege to hide its icon from the home screen. - * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. + * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen.

+ +**Figure 1** Application details screen +![Application details screen](figures/application_details.jpg) - **Table 4** abilities + + **Table 6** abilities | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -285,14 +312,14 @@ Set **icon**, **label**, and **skills** under **abilities** in the **module.json | removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the UIAbility component is destroyed.
- **true**: Remove the relevant task from the task list after the UIAbility component is destroyed.
- **false**: Do not remove the relevant task from the task list after the UIAbility component is destroyed.| Boolean| Yes (initial value: **false**)| | orientation | Orientation of the UIAbility component when it is started. The options are as follows:
- **unspecified**: automatically determined by the system.
- **landscape**: landscape mode.
- **portrait**: portrait mode.
- **landscape_inverted**: inverted landscape mode.
- **portrait_inverted**: inverted portrait mode.
- **auto_rotation**: determined by the sensor.
- **auto_rotation_landscape**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes.
- **auto_rotation_portrait**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes.
- **auto_rotation_restricted**: determined by the sensor when the sensor switch is enabled.
- **auto_rotation_landscape_restricted**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes, when the sensor switch is enabled.
- **auto_rotation_portrait_restricted**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes, when the sensor switch is enabled.
- **locked**: auto rotation disabled.| String| Yes (initial value: **"unspecified"**)| | supportWindowMode | Window mode supported by the UIAbility component. The options are as follows:
- **fullscreen**: full-screen mode.
- **split**: split-screen mode.
- **floating**: floating window mode.| String array| Yes (initial value:
["fullscreen", "split", "floating"])| -| priority | Priority of the UIAbility component. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.
**NOTE**
This tag applies only to system applications and does not take effect for third-party applications.| Number| Yes (initial value: **0**)| +| priority | Priority of the UIAbility component. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.
**NOTE**
This attribute applies only to system applications and does not take effect for third-party applications.| Number| Yes (initial value: **0**)| | maxWindowRatio | Maximum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: maximum aspect ratio supported by the platform)| | minWindowRatio | Minimum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: minimum aspect ratio supported by the platform)| | maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowWidth** or greater than the maximum window width allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window width supported by the platform)| | minWindowWidth | Minimum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the minimum window width allowed by the platform or greater than the value of **maxWindowWidth**. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: minimum window width supported by the platform)| | maxWindowHeight | Maximum window height supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowHeight** or greater than the maximum window height allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window height supported by the platform)| | minWindowHeight | Minimum window height supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the minimum window height allowed by the platform or greater than the value of **maxWindowHeight**. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: minimum window height supported by the platform)| -| excludeFromMissions | Whether the UIAbility component is displayed in the recent task list.
- **true**: displayed in the recent task list.
- **false**: not displayed in the recent task list.
**NOTE**
This tag applies only to system applications and does not take effect for third-party applications.| Boolean| Yes (initial value: **false**)| +| excludeFromMissions | Whether the UIAbility component is displayed in the recent task list.
- **true**: displayed in the recent task list.
- **false**: not displayed in the recent task list.
**NOTE**
This attribute applies only to system applications and does not take effect for third-party applications.| Boolean| Yes (initial value: **false**)| | recoverable | Whether the application can be recovered to its previous state in case of a detected fault.
- **true**: The application can be recovered to its previous state in case of a detected fault.
- **false**: The application cannot be recovered to its previous state in case of a detected fault.| Boolean| Yes (initial value: **false**)| Example of the **abilities** structure: @@ -348,7 +375,7 @@ Example of the **abilities** structure: The **skills** tag represents the feature set of [wants](../application-models/want-overview.md) that can be received by the UIAbility or ExtensionAbility component. - **Table 5** skills + **Table 7** skills | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -356,7 +383,7 @@ The **skills** tag represents the feature set of [wants](../application-models/w | entities | [Entities](../application-models/actions-entities.md) of wants that can be received.| String array| Yes (initial value: left empty)| |uris | URIs that match the wants.| Object array| Yes (initial value: left empty)| - **Table 6** uris + **Table 8** Internal structure of the uris tag | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -397,44 +424,11 @@ Example of the **skills** structure: } ``` -**Enhanced implicit query** - -URI-level prefix matching is supported. -When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if a URI prefixed with the configuration file is passed in. - - - * The query enhancement involves the following APIs: - [@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)
- 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void;
- 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void;
- 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise>; - * Configuration requirements
- abilities -> skills -> uris object
- Configuration 1: only **scheme = 'http'**
- Configuration 2: only **(scheme = 'http') + (host = 'example.com')**
- Configuration 3: only **(scheme = 'http') + (host = 'example.com') + (port = '8080')** - * Prefix match
- If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API: - 1. uri = 'https://': No matches
- 2. uri = 'http://': Matches configuration 1
- 3. uri = 'https://example.com': No matches
- 4. uri = 'https://exa.com': No matches
- 5. uri = 'http://exa.com': Matches configuration 1
- 6. uri = 'http://example.com': Matches configuration 1 and configuration 2
- 7. uri = 'https://example.com:8080': No matches
- 8. uri = 'http://exampleaa.com:8080': Matches configuration 1
- 9. uri = 'http://example.com:9180': Matches configuration 1 and configuration 2
- 10. uri = 'http://example.com:8080': Matches configuration 1, configuration 2, and configuration 3
- 11. uri = 'https://example.com:9180/path': No matches
- 12. uri = 'http://exampleap.com:8080/path': Matches configuration 1
- 13. uri = 'http://example.com:9180/path': Matches configuration 1 and configuration 2
- 14. uri = 'http://example.com:8080/path': Matches configuration 1, configuration 2, and configuration 3
- ## extensionAbilities The **extensionAbilities** tag represents the configuration of extensionAbilities, which is valid only for the current extensionAbility. - **Table 7** extensionAbilities + **Table 9** extensionAbilities | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -443,10 +437,10 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie | description | Description of the ExtensionAbility component. The value is a string with a maximum of 255 bytes or a resource index to the description.| String| Yes (initial value: left empty)| | icon | Icon of the ExtensionAbility component. The value is an icon resource index. If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| Yes (initial value: left empty)| | label | Name of the ExtensionAbility component displayed to users. The value is a string resource index.
**NOTE**
If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No| -| type | Type of the ExtensionAbility component. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a Work Scheduler task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **dataShare**: ExtensionAbility for data sharing.
- **fileShare**: ExtensionAbility for file sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
**NOTE**
The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| +| type | Type of the ExtensionAbility component. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a Work Scheduler task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **dataShare**: ExtensionAbility for data sharing.
- **fileShare**: ExtensionAbility for file sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
- **driver**: ExtensionAbility for the driver framework.
**NOTE**
The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| | permissions | Permissions required for another application to access the ExtensionAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)| -| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when the type of the **ExtensionAbility** component is set to **dataShare**. | String| Yes (initial value: left empty)| -|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application, but not for an OpenHarmony service. | Array| Yes (initial value: left empty)| +| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| +|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service. | Array| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | exported | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| @@ -462,7 +456,7 @@ Example of the **extensionAbilities** structure: "icon": "$media:icon", "label" : "$string:extension_name", "description": "$string:form_description", - "type": "form", + "type": "form", "permissions": ["ohos.abilitydemo.permission.PROVIDER"], "readPermission": "", "writePermission": "", @@ -476,7 +470,7 @@ Example of the **extensionAbilities** structure: "metadata": [ { "name": "ohos.extension.form", - "resource": "$profile:form_config", + "resource": "$profile:form_config", } ] } @@ -494,12 +488,12 @@ The **requestPermissions** tag represents a set of permissions that the applicat > - The permission settings configured in the **requestPermissions** tag apply to the entire application. > - If your application needs to subscribe to an event published by itself and the permissions required for accessing the application are set in the **permissions** tag under **extensionAbilities**, then the application must register the related permissions in the **requestPermissions** tag to receive the event. -**Table 8** requestPermissions +**Table 10** requestPermissions | Name| Description| Data Type| Value Range| Default Value| | -------- | -------- | -------- | -------- | -------- | | name | Permission name. This attribute is mandatory.| String| Custom| –| -| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**.
**NOTE**
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.| String| Resource reference of the string type in $string: \*\*\* format| A null value| +| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**.
**NOTE**
If the permission to request is **user_grant**, this attribute is required for the application to be released to the application market. Multi-language adaptation is required.| String| Resource reference of the string type in $string: \*\*\* format| A null value| | usedScene | Scene under which the permission is used. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured.
**NOTE**
This attribute is optional by default. If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional.| **abilities**: string array
**when**: string| **abilities**: array of names of UIAbility or ExtensionAbility components
**when**: **inuse** or **always**| **abilities**: null
**when**: null| Example of the **requestPermissions** structure: @@ -534,8 +528,10 @@ The **shortcut** information is identified in **metadata**, where: - **name** indicates the name of the shortcut, identified by **ohos.ability.shortcuts**. - **resource** indicates where the resources of the shortcut are stored. - -| Attribute| Description| Data Type | Default Value| + +**Table 11** shortcuts + +| Name| Description| Data Type | Default Value| | -------- | -------- | -------- | -------- | | shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No| | label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label, with a maximum of 255 bytes.| String| Yes (initial value: left empty)| @@ -544,7 +540,7 @@ The **shortcut** information is identified in **metadata**, where: 1. Configure the **shortcuts_config.json** file in **/resource/base/profile/**. - + ```json { "shortcuts": [ @@ -564,7 +560,7 @@ The **shortcut** information is identified in **metadata**, where: ``` 2. In the **abilities** tag of the **module.json5** file, configure the **metadata** tag for the UIAbility component to which a shortcut needs to be added so that the shortcut configuration file takes effect for the UIAbility. - + ```json { "module": { @@ -601,7 +597,7 @@ The **shortcut** information is identified in **metadata**, where: The **distributionFilter** tag 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 five factors: API version, screen shape, screen size, screen resolution, and country code. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these five factors. This tag must be configured in the **/resource/profile resource** directory. Its sub-tags are optional. - **Table 9** distributionFilter + **Table 12** distributionFilter | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -611,28 +607,28 @@ The **distributionFilter** tag defines the rules for distributing HAP files base | countryCode | Code of the country or region to which the application is to be distributed. The value is subject to the ISO-3166-1 standard. Enumerated definitions of multiple countries and regions are supported.| Object array| Yes (initial value: left empty)| - **Table 10** screenShape + **Table 13** Internal structure of the screenShape tag | 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.| String array| No| - **Table 11** screenWindow + **Table 14** Internal structure of the screenWindow tag | 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"**.| String array| No| - **Table 12** screenDensity + **Table 15** Internal structure of the screenDensity tag | 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 DPI.| String array| No| - **Table 13** countryCode + **Table 16** Internal structure of the countryCode tag | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | @@ -699,14 +695,14 @@ Configure **metadata** in the **module** tag in the **module.json5** file. The **testRunner** tag represents the supported test runner. -**Table 14** testRunner +**Table 17** Internal structure of the testRunner tag | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | name | Name of the test runner object. The value is a string with a maximum of 255 bytes.| String| No| | srcPath | Code path of the test runner. The value is a string with a maximum of 255 bytes.| String| No| -Example of the / structure: +Example of the **testRunner** structure: ```json @@ -720,3 +716,84 @@ Example of the / structure: } } ``` + +## atomicService + +The **atomicService** tag represents the atomic service configuration. It is available only when **bundleType** is set to **atomicService** in the **app.json** file. + +**Table 18** Internal structure of the atomicService tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| preloads | List of modules to pre-load.| Object array| Yes (initial value: left empty)| + +Example of the **atomicService** structure: + + +```json +{ + "module": { + "atomicService": { + "preloads":[ + { + "moduleName":"feature" + } + ] + } + } +} +``` + +## preloads + +The **preloads** tag represents a list of modules to pre-load in an atomic service. + +**Table 19** Internal structure of the preloads tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| moduleName | Name of the module to be preloaded when the current module is loaded in the atomic service.| String| No| + +Example of the **preloads** structure: + +```json +{ + "module": { + "atomicService": { + "preloads":[ + { + "moduleName":"feature" + } + ] + } + } +} +``` + +## dependencies + +The **dependencies** tag identifies the list of shared libraries that the module depends on when it is running. + +**Table 20** Internal structure of the dependencies tag + +| Name | Description | Data Type| Initial Value Allowed| +| ----------- | ------------------------------ | -------- | ---------- | +| bundleName | Name of the shared bundle on which the current module depends. | String | Yes| +| moduleName | Module name of the shared bundle on which the current module depends.| String | No| +| versionCode | Version number of the shared bundle. | Number | Yes| + +Example of the **dependencies** structure: + +```json +{ + "module": { + "dependencies": [ + { + "bundleName":"com.share.library", + "moduleName": "library", + "versionCode": 10001 + } + ] + } +} +``` diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md index 352a993d5042116105ef5c50ae9138df51c622c9..d4593c12743cff7d6a5da9e10de69c6e4d6b71b5 100644 --- a/en/application-dev/quick-start/module-structure.md +++ b/en/application-dev/quick-start/module-structure.md @@ -192,12 +192,20 @@ Example of the metadata attribute: **By default, application icons cannot be hidden from the home screen in OpenHarmony.** -The OpenHarmony system imposes a strict rule on the presence of application icons. If no icon is configured in the HAP file of an application, the system creates a default icon for the application and displays it on the home screen.
-Touching this icon will direct the user to the application details screen in **Settings**. +The OpenHarmony system imposes a strict rule on the presence of application icons. If no icon is configured in the HAP file of an application, the system creates a default icon for the application and displays it on the home screen. + +Touching this icon will direct the user to the application details screen in **Settings**, as shown in Figure 1. + To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). +**Objectives**: + +This requirement on application icons is intended to prevent malicious applications from deliberately configuring no icon to block uninstallation attempts. + +**Setting the application icon to be displayed on the home screen**: + +Set **icon**, **label**, and **skills** under **abilities** in the **config.json** file. In addition, make sure the **skills** configuration contains **ohos.want.action.home** and **entity.system.home**. -**Setting the application icon to be displayed on the home screen**:
Set **icon**, **label**, and **skills** under **abilities** in the **config.json** file. In addition, make sure the **skills** configuration contains **ohos.want.action.home** and **entity.system.home**. ``` { "module":{ @@ -220,36 +228,37 @@ To hide an application icon from the home screen, you must configure the **Allow } ``` -**Querying an application icon:** +**Display rules of application icons and labels on the home screen:** * The HAP file contains Page ability configuration. - * The application icon is set under **abilities** in the **config.json** file. + * The application icon on the home screen is set under **abilities** in the **config.json** file. * The application does not have the privilege to hide its icon from the home screen. - * The returned home screen icon is the icon configured for the ability. - * The returned home screen label is the label configured for the ability. If no label is configured, the bundle name is returned. - * The returned component name is the component name of the ability. - * When the user touches the home screen icon, the home screen of the ability is displayed. + * The application icon displayed on the home screen is the icon configured for the Page ability. + * The application label displayed on the home screen is the label configured for the Page ability. If no label is configured, the bundle name is returned. + * The name of the Page ability is displayed. + * When the user touches the home screen icon, the home screen of the Page ability is displayed. * The application has the privilege to hide its icon from the home screen. * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. - * The application icon is not set under **abilities** in the **config.json** file. + * The application icon on the home screen is not set under **abilities** in the **config.json** file. * The application does not have the privilege to hide its icon from the home screen. - * The returned home screen icon is the default icon. - *The returned home screen label is the bundle name of the application. - * The returned component name is the component name displayed on the application details screen (this component is built in the system). - * Touching the home screen icon will direct the user to the application details screen. + * The application icon displayed on the home screen is the default icon. + * The application label displayed on the home screen is the bundle name of the application. + * Touching the application icon on the home screen will direct the user to the application details screen shown in Figure 1. * The application has the privilege to hide its icon from the home screen. * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. * The HAP file does not contain Page ability configuration. * The application does not have the privilege to hide its icon from the home screen. - * The returned home screen icon is the default icon. - *The returned home screen label is the bundle name of the application. - * The returned component name is the component name displayed on the application details screen (this component is built in the system). - * Touching the home screen icon will direct the user to the application details screen. + * The application icon displayed on the home screen is the default icon. + * The application label displayed on the home screen is the bundle name of the application. + * Touching the application icon on the home screen will direct the user to the application details screen shown in Figure 1. * The application has the privilege to hide its icon from the home screen. * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen. -> **NOTE** -> -> The icon and label displayed on the application details page may be different from those displayed on the home screen. For non-Page abilities, they are the entry icon and label set under **abilities**, if any. +Note: The label displayed on the application details screen may be different from that displayed on the home screen. For non-Page abilities, it is the entry label set (if any).

+ +**Figure 1** Application details screen + +![Application details screen](figures/application_details.jpg) + **Table 8** Internal structure of the abilities attribute @@ -412,39 +421,6 @@ Example of the **skills** attribute structure: ] ``` -**Enhanced implicit query** - -URI-level prefix matching is supported. - -When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if a URI prefixed with the configuration file is passed in. - - * The query enhancement involves the following APIs:
- [@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)
- 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void;
- 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void;
- 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise>; - * Configuration requirements
- abilities -> skills -> uris object
- Configuration 1: only **scheme = 'http'** - Configuration 2: only **(scheme = 'http') + (host = 'www.example.com')** - Configuration 3: only **(scheme = 'http') + (host = 'www.example.com') + (port = '8080')** - * Prefix match
- If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API:
- 1. uri = 'https://': No matches
- 2. uri = 'http://': Matches configuration 1
- 3. uri = 'https://www.example.com': No matches
- 4. uri = 'https://www.exa.com': No matches
- 5. uri = 'http://www.exa.com': Matches configuration 1
- 6. uri = 'http://www.example.com': Matches configuration 1 and configuration 2
- 7. uri = 'https://www.example.com:8080': No matches
- 8. uri = 'http://www.exampleaa.com:8080': Matches configuration 1
- 9. uri = 'http://www.example.com:9180': Matches configuration 1 and configuration 2
- 10. uri = 'http://www.example.com:8080': Matches configuration 1, configuration 2, and configuration 3
- 11. uri = 'https://www.example.com:9180/query/student/name' : No matches
- 12. uri = 'http://www.exampleap.com:8080/query/student/name': Matches configuration 1
- 13. uri = 'http://www.example.com:9180/query/student/name': Matches configuration 1 and configuration 2
- 14. uri = 'http://www.example.com:8080/query/student/name': Matches configuration 1, configuration 2, and configuration 3
- ## Internal Structure of the reqPermissions Attribute **Table 12** Internal structure of the reqPermissions attribute diff --git a/en/application-dev/quick-start/multi-hap-objective.md b/en/application-dev/quick-start/multi-hap-objective.md index ad43c84fd7799be1e3277400c6c5dfb1926d5b7c..ae7bb791b71225cfa15741d4c99975111734709f 100644 --- a/en/application-dev/quick-start/multi-hap-objective.md +++ b/en/application-dev/quick-start/multi-hap-objective.md @@ -1,10 +1,10 @@ # Multi-HAP Design Objectives -- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, If you are developing a payment application and its home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the logic of the home screen for managing other modules in the entry-type HAP file, and implement specific modules in feature-type HAP files. The feature-type HAP files are independent. You can develop and test each of them separately, and then integrate them with the entry-type HAP file. +- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, if you are developing a payment application whose home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the HAP files as follows: (1) In the entry-type HAP file, implement the home screen logic for managing modules; (2) in feature-type HAP files, implement specific modules. The feature-type HAP files are independent of each other. You can develop and test each of them separately, and then integrate them with the entry-type HAP file. -- Flexible deployment: You can combine multiple HAP files and deploy them on different devices. Assume that an application contains one entry-type HAP file (**Entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. In this way, you can easily combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B. +- Flexible deployment: You can flexibly combine HAP files for device-specific deployment. Assume that an application contains one entry-type HAP file (**entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. This means that you can combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B. -- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of an application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent. +- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of your application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent. -- Easier resource sharing: The resources (including public resource files and public pages) and shared objects (.so library files) required by multiple HAP files can be stored in an independent HAP file. In this way, other HAP files can obtain the resources and files by accessing the HAP, which reduces the size of the application package to some extent. +- Easier resource sharing: The resources (including public resource files and public pages) and shared objects (.so library files) required by multiple HAP files can be stored in an independent HAP file. In this way, other HAP files can obtain the resources and files by accessing the HAP, which also reduces the size of the application package to some extent. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 3d791befc09e01d9dda38f359d68485cd97eb2a2..69989d5c01c2f369c1e9adc72bc3a18105847d86 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -233,6 +233,7 @@ - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - File Management + - [@ohos.file.cloudSyncManager (Device-Cloud Synchronization Management)](js-apis-file-cloudsyncmanager.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) @@ -412,7 +413,6 @@ - [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md) - [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md) - [@ohos.usb (USB Management)](js-apis-usb-deprecated.md) - - [@ohos.usbV9 (USB Management)](js-apis-usb.md) - [@system.app (Application Context)](js-apis-system-app.md) - [@system.battery (Battery Information)](js-apis-system-battery.md) - [@system.bluetooth (Bluetooth)](js-apis-system-bluetooth.md) diff --git a/en/application-dev/reference/apis/development-intro.md b/en/application-dev/reference/apis/development-intro.md index 281fa66969891561b062b7cfd7185d25f7c7f474..565bb231015c61926de2c4ddc868d473527ac4c6 100644 --- a/en/application-dev/reference/apis/development-intro.md +++ b/en/application-dev/reference/apis/development-intro.md @@ -41,7 +41,7 @@ To call APIs to access these resources, you must apply for the corresponding per - If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx" - If an application can call an API without any permission, no special description is provided. -To determine whether an application can request a specific permission, see [Permission Application and Use](../../security/accesstoken-overview.md#permission-application-and-use). +To determine whether an application can request a specific permission, see [Permission Application and Use](../../security/accesstoken-overview.md#applying-for-and-using-a-permission). ## System Capability Description diff --git a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md index 13fa28f551fe677055c589c11a0b4a1b581757b5..8ffa96f54d40560d0f1998e55b377a84e7e26d8b 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @@ -3,14 +3,13 @@ The **BundleStatusCallback** module provides callbacks for bundle status changes. The changes can be obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). > **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. - ## BundleStatusCallback(deprecated) > This API is deprecated since API version 9. You are advised to use [bundleMonitor](js-apis-bundleMonitor.md) instead. -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index f45268cb699527ed412518bdee3b5f8b41f6520f..b689be21609a3d8a44e2f43dbd0f779e6f12ebf9 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -34,7 +34,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -62,7 +62,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -94,7 +94,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -121,7 +121,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -153,7 +153,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -179,7 +179,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -210,7 +210,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -236,7 +236,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -267,7 +267,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -293,7 +293,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md index eda69bbe8857d6d787753bc91247dcde124f9633..6a7a0edded1c942cb95b15be263cf5e6eda41b60 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -42,7 +42,7 @@ SystemCapability.BundleManager.DistributedBundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -71,7 +71,7 @@ SystemCapability.BundleManager.DistributedBundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -103,7 +103,7 @@ SystemCapability.BundleManager.DistributedBundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -132,7 +132,7 @@ SystemCapability.BundleManager.DistributedBundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 0051896a67f1dd2c9e662ed1ac503259ad6a7997..c116f901789c4a0fd1898d28bb7e8fd69a1b38fc 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -426,7 +426,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Return value** @@ -462,7 +462,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -499,7 +499,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -540,7 +540,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -584,7 +584,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -626,7 +626,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -671,7 +671,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -699,7 +699,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -754,7 +754,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -794,7 +794,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index 8121b906b88726624f649211a6e82b05bc722023..2aa842a8d45a8485cd098a0ba5d8f65550026d73 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -68,20 +68,20 @@ Describes the target action supported by an accessibility application. | -------- | -------- | | click | Clicking.| | longClick | Long pressing.| -| scrollForward | Scrolling forward.| -| scrollBackward | Scrolling backward.| -| focus | Obtaining focus.| -| clearFocus | Clearing focus.| -| clearSelection | Clearing selection.| -| accessibilityFocus | Obtaining the accessibility focus.| -| clearAccessibilityFocus | Clearing the accessibility focus.| -| cut | Cut.| -| copy | Copy.| -| paste | Paste.| -| select | Select.| -| setText | Setting the text.| -| delete | Delete.| -| setSelection | Setting the selection.| +| scrollForward | Scrolling forward. Not supported currently. | +| scrollBackward | Scrolling backward. Not supported currently. | +| focus | Obtaining focus. Not supported currently. | +| clearFocus | Clearing focus. Not supported currently. | +| clearSelection | Clearing selection. Not supported currently. | +| accessibilityFocus | Obtaining the accessibility focus. | +| clearAccessibilityFocus | Clearing the accessibility focus. | +| cut | Cut. Not supported currently. | +| copy | Copy. Not supported currently. | +| paste | Paste. Not supported currently. | +| select | Select. Not supported currently. | +| setText | Setting the text. Not supported currently. | +| delete | Delete. Not supported currently. | +| setSelection | Setting the selection. Not supported currently. | ## Capability @@ -94,7 +94,7 @@ Enumerates the capabilities of an accessibility application. | retrieve | Capability to retrieve the window content.| | touchGuide | Capability of touch guide mode.| | keyEventObserver | Capability to filter key events.| -| zoom | Capability to control the display zoom level.| +| zoom | Capability to control the display zoom level. Not supported currently. | | gesture | Capability to perform gesture actions.| ## CaptionsFontEdgeType8+ @@ -279,15 +279,15 @@ Describes a GUI change event. | bundleName | string | Yes| Yes| Target application name.| | componentType | string | Yes| Yes| Type of the event source component, for example, button or chart.| | pageId | number | Yes| Yes| Page ID of the event source.| -| description | string | Yes| Yes| Event description.| +| description | string | Yes| Yes| Event description. Not supported currently. | | triggerAction | [Action](#action) | Yes| Yes| Action that triggers the event.| -| textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes| Yes| Text movement unit.| +| textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes| Yes| Text movement unit. Not supported currently. | | contents | Array<string> | Yes| Yes| Array of contents.| | lastContent | string | Yes| Yes| Latest content.| -| beginIndex | number | Yes| Yes| Sequence number of the first item displayed on the page.| -| currentIndex | number | Yes| Yes| Sequence number of the current item.| -| endIndex | number | Yes| Yes| Sequence number of the last item displayed on the page.| -| itemCount | number | Yes| Yes| Total number of items.| +| beginIndex | number | Yes| Yes| Sequence number of the first item displayed on the page. Not supported currently. | +| currentIndex | number | Yes| Yes| Sequence number of the current item. Not supported currently. | +| endIndex | number | Yes| Yes| Sequence number of the last item displayed on the page. Not supported currently. | +| itemCount | number | Yes| Yes| Total number of items. Not supported currently. | ### constructor @@ -323,13 +323,13 @@ Enumerates accessibility event types. | -------- | -------- | | click | Event of clicking a component.| | longClick | Event of long-pressing a component.| -| select | Event of selecting a component.| -| focus | Event indicating that the component obtains the focus.| -| textUpdate | Event indicating that the component text has been updated.| -| hoverEnter | Event indicating that the hover enters a component.| -| hoverExit | Event indicating that the hover exits a component.| -| scroll | Event of the scroll view.| -| textSelectionUpdate | Event indicating that the selected text has been updated.| +| select | Event of selecting a component. Not supported currently. | +| focus | Event indicating that the component obtains the focus. Not supported currently. | +| textUpdate | Event indicating that the component text has been updated. Not supported currently. | +| hoverEnter | Event indicating that the hover enters a component. Not supported currently. | +| hoverExit | Event indicating that the hover exits a component. Not supported currently. | +| scroll | Event of the scroll view. Not supported currently. | +| textSelectionUpdate | Event indicating that the selected text has been updated. Not supported currently. | | accessibilityFocus | Event indicating that the accessibility focus has been obtained.| | accessibilityFocusClear | Event indicating that the accessibility focus has been cleared.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index a052c4dbec6fdb7c790c7195baf763f96dd90dad..2fe06c942fc2a329f0572395ff9cf0b8cb0c3fa9 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -26,7 +26,7 @@ import Want from '@ohos.app.ability.Want'; | entities | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| | uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No| MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerBundleName**: bundle name of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files.| | [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| **Example** @@ -34,6 +34,7 @@ import Want from '@ohos.app.ability.Want'; - Basic usage: called in a UIAbility object, as shown in the example below. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). ```ts + let context = ...; // UIAbilityContext let want = { 'deviceId': '', // An empty deviceId indicates the local device. 'bundleName': 'com.example.myapplication', @@ -41,16 +42,17 @@ import Want from '@ohos.app.ability.Want'; 'moduleName': 'entry' // moduleName is optional. }; - this.context.startAbility(want, (err) => { + context.startAbility(want, (err) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` -- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, as shown in the example below. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).) +- Currently, the following data types are supported: string, number, Boolean, object, array, and file descriptor (FD). * String ```ts + let context = ...; // UIAbilityContext let want = { bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', @@ -59,12 +61,13 @@ import Want from '@ohos.app.ability.Want'; }, }; - this.context.startAbility(want, (err) => { - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + context.startAbility(want, (err) => { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` * Number ```ts + let context = ...; // UIAbilityContext let want = { bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', @@ -74,12 +77,13 @@ import Want from '@ohos.app.ability.Want'; }, }; - this.context.startAbility(want, (err) => { - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + context.startAbility(want, (err) => { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` * Boolean ```ts + let context = ...; // UIAbilityContext let want = { bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', @@ -88,12 +92,13 @@ import Want from '@ohos.app.ability.Want'; }, }; - this.context.startAbility(want, (err) => { - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + context.startAbility(want, (err) => { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` * Object ```ts + let context = ...; // UIAbilityContext let want = { bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', @@ -107,12 +112,13 @@ import Want from '@ohos.app.ability.Want'; }, }; - this.context.startAbility(want, (err) => { - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + context.startAbility(want, (err) => { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` * Array ```ts + let context = ...; // UIAbilityContext let want = { bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', @@ -124,19 +130,21 @@ import Want from '@ohos.app.ability.Want'; }, }; - this.context.startAbility(want, (err) => { - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + context.startAbility(want, (err) => { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` - * File descriptor (FD) + * FD ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; + + let context = ...; // UIAbilityContext let fd; try { - fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); - } catch(e) { - console.error('openSync fail: ${JSON.stringify(e)}'); + fd = fs.openSync('/data/storage/el2/base/haps/pic.png').fd; + } catch(err) { + console.error(`Failed to openSync. Code: ${err.code}, message: ${err.message}`); } let want = { 'deviceId': '', // An empty deviceId indicates the local device. @@ -148,7 +156,7 @@ import Want from '@ohos.app.ability.Want'; } }; - this.context.startAbility(want, (err) => { - console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + context.startAbility(want, (err) => { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-appControl.md b/en/application-dev/reference/apis/js-apis-appControl.md index 597b3d8e3b9d15b6d18f4f8e57c0ac71563d3236..ffd45bb873f48f0b401ea4b2a163e50f98616f60 100644 --- a/en/application-dev/reference/apis/js-apis-appControl.md +++ b/en/application-dev/reference/apis/js-apis-appControl.md @@ -24,7 +24,7 @@ Sets the disposed status for an application. This API uses a promise to return t **System capability**: SystemCapability.BundleManager.BundleFramework.AppControl -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -75,7 +75,7 @@ Sets the disposed status for an application. This API uses an asynchronous callb **System capability**: SystemCapability.BundleManager.BundleFramework.AppControl -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -122,7 +122,7 @@ Obtains the disposed status of an application. This API uses a promise to return **System capability**: SystemCapability.BundleManager.BundleFramework.AppControl -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -171,7 +171,7 @@ Obtains the disposed status of an application. This API uses an asynchronous cal **System capability**: SystemCapability.BundleManager.BundleFramework.AppControl -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -216,7 +216,7 @@ Deletes the disposed status for an application. This API uses a promise to retur **System capability**: SystemCapability.BundleManager.BundleFramework.AppControl -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -265,7 +265,7 @@ Deletes the disposed status for an application. This API uses an asynchronous ca **System capability**: SystemCapability.BundleManager.BundleFramework.AppControl -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md index 7f03efce9a0fcec4585e4c3f7ebbb3d67a4fbe64..8ecd4f8bd0057abf3fd5062bae27f10c90d9b060 100644 --- a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -16,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Type| Readable| Writable| Description | -| --------- | -------- | ---- | ---- | ------------------------- | -| context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes| No| Context of the accessibility extension ability.| +| Name | Type | Readable | Writable | Description | +| ------- | ---------------------------------------- | ---- | ---- | ------------ | +| context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes | No | Context of the accessibility extension ability.| ## AccessibilityEvent @@ -28,11 +28,11 @@ Defines an accessibility event. ### Attributes -| Name | Type | Readable | Writable | Description | -| --------- | ---------------------------------------- | ---- | ---- | ---------- | -| eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | -| target | [AccessibilityElement](js-apis-inner-application-accessibilityExtensionContext.md#accessibilityelement9) | Yes | No | Target component where the event occurs.| -| timeStamp | number | Yes | No | Timestamp of the event. | +| Name | Type | Readable| Writable| Description | +| --------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType)\| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type.
**EventType**: accessibility event type.
**WindowUpdateType**: Window update type.
**TouchGuideType**: touch guide event type.
**GestureType**: gesture type.
**PageUpdateType**: page update type, which is not supported currently.| +| target | [AccessibilityElement](js-apis-inner-application-accessibilityExtensionContext.md#accessibilityelement9) | Yes | No | Target component where the event occurs. | +| timeStamp | number | Yes | No | Timestamp of the event. | ## GestureType @@ -40,35 +40,35 @@ Enumerates gesture types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Description | -| ------------- | ------------ | -| left | Left gesture. String type. | -| leftThenRight | Left-then-right gesture. String type. | -| leftThenUp | Left-then-up gesture. String type. | -| leftThenDown | Left-then-down gesture. String type. | -| right | Right gesture. String type. | -| rightThenLeft | Right-then-left gesture. String type. | -| rightThenUp | Right-then-up gesture. String type. | -| rightThenDown | Right-then-down gesture. String type. | -| up | Up gesture. String type. | -| upThenLeft | Up-then-left gesture. String type. | -| upThenRight | Up-then-right gesture. String type. | -| upThenDown | Up-then-down gesture. String type. | -| down | Down gesture. String type. | -| downThenLeft | Down-then-left gesture. String type. | -| downThenRight | Down-then-right gesture. String type. | -| downThenUp | Down-then-up gesture. String type. | +| Name | Description | +| ------------- | ------------------- | +| left | Left gesture. String type. | +| leftThenRight | Left-then-right gesture. String type.| +| leftThenUp | Left-then-up gesture. String type.| +| leftThenDown | Left-then-down gesture. String type.| +| right | Right gesture. String type. | +| rightThenLeft | Right-then-left gesture. String type.| +| rightThenUp | Right-then-up gesture. String type.| +| rightThenDown | Right-then-down gesture. String type.| +| up | Up gesture. String type. | +| upThenLeft | Up-then-left gesture. String type.| +| upThenRight | Up-then-right gesture. String type.| +| upThenDown | Up-then-down gesture. String type.| +| down | Down gesture. String type. | +| downThenLeft | Down-then-left gesture. String type.| +| downThenRight | Down-then-right gesture. String type.| +| downThenUp | Down-then-up gesture. String type.| ## PageUpdateType -Enumerates the page update types. +Enumerates the page update types. This API is not supported currently. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Description | -| ----------------- | --------- | -| pageContentUpdate | Update of the page content. String type. | -| pageStateUpdate | Update of the page status. String type. | +| Name | Description | +| ----------------- | ---------------- | +| pageContentUpdate | Update of the page content. String type.| +| pageStateUpdate | Update of the page status. String type.| ## TouchGuideType @@ -76,10 +76,10 @@ Enumerates the touch guide event types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Description | -| ---------- | ------------ | -| touchBegin | Start of touch in touch guide mode. String type. | -| touchEnd | End of touch in touch guide mode. String type. | +| Name | Description | +| ---------- | ------------------- | +| touchBegin | Start of touch in touch guide mode. String type.| +| touchEnd | End of touch in touch guide mode. String type.| ## AccessibilityExtensionAbility.onConnect @@ -127,7 +127,7 @@ Called when an event that matches the specified bundle and event type occurs. In **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | --------------- | | event | [AccessibilityEvent](#accessibilityevent) | Yes | Accessibility event. No value is returned.| @@ -154,7 +154,7 @@ Called when a physical key is pressed. In this API, you can determine whether to **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------- | | keyEvent | [KeyEvent](js-apis-keyevent.md#KeyEvent) | Yes | Key event. If **true** is returned, the key is intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-application-want.md b/en/application-dev/reference/apis/js-apis-application-want.md index 7844ed3008796cf449c32d09c246af86b65338d8..65f7fb03e38244ee92c9f94797fa3435072d2f60 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -23,10 +23,10 @@ import Want from '@ohos.application.Want'; | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | -| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| -| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | -| entities | Array\ | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags).| +| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-ability-wantConstant.md#wantconstantentity). | **Example** @@ -108,10 +108,10 @@ import Want from '@ohos.application.Want'; ``` * File descriptor (FD) ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let fd; try { - fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); + fd = fs.openSync('/data/storage/el2/base/haps/pic.png').fd; } catch(e) { console.error('openSync fail: ${JSON.stringify(e)}'); } diff --git a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md new file mode 100644 index 0000000000000000000000000000000000000000..7f15532f653340879049904a3b95fbe17576bd71 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -0,0 +1,136 @@ +# @ohos.arkui.drawableDescriptor (DrawableDescriptor) + +The **DrawableDescriptor** module provides APIs for obtaining **pixelMap** objects, including the foreground, background, mask, and layered icons. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. + +## Modules to Import + +```js +import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawableDescriptor'; +``` + +## DrawableDescriptor.constructor +constructor() + +Creates a **DrawableDescriptor** or **LayeredDrawableDescriptor** object. The globalization API [getDrawableDescriptor](js-apis-resource-manager.md##getdrawabledescriptor) or [getDrawableDescriptorByName](js-apis-resource-manager.md##getdrawabledescriptorbyname) is required for object construction. + +**System API**: This is a system API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### DrawableDescriptor + +Creates a **DrawableDescriptor** object when the passed resource ID or name belongs to a common image. + +### LayeredDrawableDescriptor + +Creates a **LayeredDrawableDescriptor** object when the passed resource ID or name belongs to a JSON file that contains foreground and background resources. + +**Example** +```js +@Entry +@Component +struct Index { + private resManager = getContext().resourceManager + let drawable1 = resManager.getDrawableDescriptor($r('app.media.icon').id) + let drawable2 = resManager.getDrawableDescriptorByName(icon) + let layeredDrawable1 = resManager.getDrawableDescriptor($r('app.media.file').id) + let layeredDrawable1 = resManager.getDrawableDescriptor(file) + } +``` + +## DrawableDescriptor.getPixelMap +getPixelMap(): image.PixelMap; + +Obtains this **pixelMap** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------- | +| [image.PixelMap](../apis/js-apis-image.md#pixelmap7) | **pixelMap** object.| + +**Example** + ```js + @State pixmap: PixelMap = drawable1.getPixelMap(); + ``` + +## LayeredDrawableDescriptor.getPixelMap +getPixelMap(): image.PixelMap; + +Obtains the **pixelMap** object where the foreground, background, and mask are blended and cropped. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------- | +| [image.PixelMap](../apis/js-apis-image.md#pixelmap7) | **pixelMap** object.| + +**Example** + ```js + @State pixmap: PixelMap = layeredDrawable1.getPixelMap(); + ``` + +## LayeredDrawableDescriptor.getForeground +getForeground(): DrawableDescriptor; + +Obtains the **DrawableDescriptor** object of the foreground. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------- | +| [DrawableDescriptor](#drawabledescriptor) | **DrawableDescriptor** object.| + +**Example** + ```js + @State drawable: DrawableDescriptor = layeredDrawable1.getForeground(); + ``` + +## LayeredDrawableDescriptor.getBackground +getBackground(): DrawableDescriptor; + +Obtains the **DrawableDescriptor** object of the background. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------- | +| [DrawableDescriptor](#drawabledescriptor) | **DrawableDescriptor** object.| + +**Example** + ```js + @State drawable: DrawableDescriptor = layeredDrawable1.getBackground(); + ``` + +## LayeredDrawableDescriptor.getMask +getMask(): DrawableDescriptor; + +Obtains the **DrawableDescriptor** object of the mask. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------- | +| [DrawableDescriptor](#drawabledescriptor) | **DrawableDescriptor** object.| + +**Example** + ```js + @State drawable: DrawableDescriptor = layeredDrawable1.getMask(); + ``` + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index ff1c5faec320b9c7deb874eee5f8329df524a735..7882c709a4ccdeaa80aa956576318d365e130a03 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -3,7 +3,7 @@ The **BundleInstaller** module provides APIs for you to install, uninstall, and recover bundles on devices. > **NOTE** -> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## BundleInstaller.install(deprecated) @@ -22,7 +22,7 @@ ohos.permission.INSTALL_BUNDLE SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -72,7 +72,7 @@ ohos.permission.INSTALL_BUNDLE SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -121,7 +121,7 @@ ohos.permission.INSTALL_BUNDLE SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -162,7 +162,7 @@ Describes the parameters required for bundle installation, recovery, or uninstal **System capability**: SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable| Writable| Description | | ----------- | ------- | ---- | ---- | ------------------ | @@ -176,12 +176,12 @@ Describes the bundle installation or uninstall status. **System capability**: SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable| Writable| Description | | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | | status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. The value must be defined in [InstallErrorCode](js-apis-Bundle.md#installerrorcode)| -| statusMessage | string | Yes | No | Installation or uninstall status message.
**SUCCESS**: install_succeed
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstallation failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstallation permission. | +| statusMessage | string | Yes | No | Installation or uninstall status message.
**SUCCESS**: install_succeed
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstallation failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstallation permission.| ## Obtaining the Sandbox Path For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the stage model, the sandbox path can be obtained using the attribute in [Context](js-apis-inner-application-uiAbilityContext.md#abilitycontext). The following describes how to obtain the sandbox path. diff --git a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md index 2ba6d913831b33b67834fa24aa1c4307259019d7..31db9e4886ecac48a49aa1439e57874514f0a6b4 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -3,7 +3,7 @@ The **LauncherAbilityInfo** module provides information about the launcher ability, which is obtained through [innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager.md). > **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. ## LauncherAbilityInfo(deprecated) @@ -12,7 +12,7 @@ The **LauncherAbilityInfo** module provides information about the launcher abili **System capability**: SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable| Writable| Description | | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index b99bd49d939b65315f9cc8e983e5ffe4641fe1a3..ab6d063fa08e6df842d28405fc80e01d9c90c7d1 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -12,11 +12,11 @@ The **PermissionDef** module provides permission details defined in the configur **System capability**: SystemCapability.BundleManager.BundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable| Writable| Description | | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | | grantMode | number | Yes | No | Grant mode of the permission. The value **0** means that the system automatically grants the permission after the application installation, and **1** means that the application needs to dynamically request the permission from the user.| -| labelId | number | Yes | No | ID of the permission label. | -| descriptionId | number | Yes | No | ID of the permission description. | +| labelId | number | Yes | No | ID of the permission label. | +| descriptionId | number | Yes | No | ID of the permission description. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index 47646ca01faf5e6915e3d4ecc42e6596697f79bf..be12e99759edb0a9a1b94f5fda05f4c27e0064d4 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -12,11 +12,10 @@ The **RemoteAbilityInfo** module provides information about a remote ability. **System capability**: SystemCapability.BundleManager.DistributedBundleFramework -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable| Writable| Description | | ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name information of the ability. | | label | string | Yes | No | Ability name. | | icon | string | Yes | No | Icon of the ability.| - diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md index 95326049595c17027a48552e04fab2d5a57816bb..64353f2c4fd878ccfcd5d5ac2d84e8d41cbd9607 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md @@ -10,7 +10,7 @@ The **LauncherAbilityInfo** module defines the ability information of the home s **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable| Writable| Description | | --------------- | ----------------------------------------------------------- | ---- | ---- | ------------------------------------ | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md index 0281e4fc7785bd815c1b988a9f67fb74b5a514de..fe52efef12fd03e53968dd186b20ebb456be5047 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md @@ -1,6 +1,6 @@ # RemoteAbilityInfo -The **RemoteAbilityInfo** module provides information about a remote ability, which can be obtained through [distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundle.md). +The **RemoteAbilityInfo** module provides information about a remote ability, which can be obtained through [distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundleManager.md#distributedbundlegetremoteabilityinfo). > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index e7d165f90fb2fade864f2e7bf2d5408d6fd190ae..d5d0ff10e38e7597fdc1bed9d6a4a2a1627c5ade 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -98,12 +98,12 @@ Enumerates the types of Extension abilities. | Name| Value| Description| |:----------------:|:---:|-----| -| FORM | 0 | [FormExtensionAbility](../../application-models/widget-development-stage.md): provides APIs for widget development.| +| FORM | 0 | [FormExtensionAbility](../../application-models/service-widget-overview.md): provides APIs for widget development.| | WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md): enables applications to execute non-real-time tasks when the system is idle.| | INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md): provides APIs for developing input method applications.| | SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md): enables applications to run in the background and provide services.| | ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.| -| DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/database-datashare-guidelines.md): enables applications to read and write data.| +| DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/share-data-by-datashareextensionability.md): enables applications to read and write data.| | FILE_SHARE | 6 | FileShareExtensionAbility: enables file sharing between applications. This ability is reserved.| | STATIC_SUBSCRIBER| 7 | [StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md): provides APIs for processing static events, such as the startup event.| | WALLPAPER | 8 | WallpaperExtensionAbility: provides APIs to implement the home screen wallpaper. This ability is reserved.| @@ -113,6 +113,7 @@ Enumerates the types of Extension abilities. | THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved.| | PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved.| | PRINT10+ | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.| +| DRIVER10+ | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.| @@ -187,7 +188,7 @@ Enumerates the display orientations of the ability. This attribute applies only | AUTO_ROTATION_PORTRAIT_RESTRICTED |11|Switched-determined auto rotation in the vertical direction.| | LOCKED |12|Locked.| -### CompatiblePolicy +### CompatiblePolicy10+ Defines the version compatibility type of the shared library. @@ -3069,3 +3070,167 @@ try { hilog.error(0x0000, 'testTag', 'getAllSharedBundleInfo failed. Cause: %{public}s', err.message); } ``` + +### bundleManager.getAppProvisionInfo10+ + +getAppProvisionInfo(bundleName: string, callback: AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\>): void; + +Obtains the provision configuration file information based on the given bundle name. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name.| +| callback | AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the provision configuration file information obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; + +try { + bundleManager.getAppProvisionInfo(bundleName, (err, data) => { + if (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); + } else { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully: %{public}s', JSON.stringify(data)); + } + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); +} +``` + +### bundleManager.getAppProvisionInfo10+ + +getAppProvisionInfo(bundleName: string, userId: number, callback: AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\>): void; + +Obtains the provision configuration file information based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name.| +| userId | number | Yes| User ID, which can be obtained by calling [getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9).| +| callback | AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the provision configuration file information obtained.| + + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700004 | The specified user ID is not found. | + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; +let userId = 100; + +try { + bundleManager.getAppProvisionInfo(bundleName, userId, (err, data) => { + if (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); + } else { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully: %{public}s', JSON.stringify(data)); + } + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); +} +``` + +### bundleManager.getAppProvisionInfo10+ + +getAppProvisionInfo(bundleName: string, userId?: number): Promise\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\>; + +Obtains the provision configuration file information based on the given bundle name and user ID. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes| Bundle name.| +| userId | number | No| User ID, which can be obtained by calling [getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9).| + + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------- | +| Promise\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\> | Promise used to return the provision configuration file obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700004 | The specified user ID is not found. | + +**Example** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; +let userId = 100; + +try { + bundleManager.getAppProvisionInfo(bundleName).then((data) => { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); +} + +try { + bundleManager.getAppProvisionInfo(bundleName, userId).then((data) => { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); +} +``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index bf20a7708d16aa7a8f8daeb7f43c8f5fb60580c3..cef362d3702423395594a8ae52326b99e5aee191 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -24,7 +24,7 @@ For details, see [Permission Levels](../../security/accesstoken-overview.md). **System capability**: SystemCapability.BundleManager.BundleFramework.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Template | Readable| Writable| Description | | ---------- | ------ | ---- | ---- | -------------------------- | @@ -39,7 +39,7 @@ Subscribes to bundle installation, uninstall, and update events. **Required permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -72,7 +72,7 @@ Unsubscribes from bundle installation, uninstall, and update events. **Required permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.BundleManager.BundleFramework.Core diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 04dcfb83d02cc263ff739c4e2618a65b2eeee181..2924cc05735a40236985ba921d39839ee796afad 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,6 +1,6 @@ # @ohos.data.rdb (RDB) -The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. +The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The worker threads are not supported. This module provides the following RDB-related functions: @@ -372,6 +372,7 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceIds = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -380,7 +381,6 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceIds = []; for (var i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } @@ -1174,7 +1174,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. -Before using the following APIs, use [executeSql](#executesql8) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). +Before using the APIs of this class, use [executeSql](#executesql) to initialize the database table structure and related data. ### insert @@ -1565,7 +1565,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** @@ -1585,7 +1585,7 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> -Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result. +Queries data using the specified SQL statement. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1594,7 +1594,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| **Return value** @@ -1605,7 +1605,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a **Example** ```js -let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +let promise = rdbStore.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) @@ -1627,19 +1627,19 @@ Executes an SQL statement that contains specified arguments but returns no value | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** ```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) { +const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" +rdbStore.executeSql(SQL_CREATE_TABLE, ['zhangsan'], function(err) { if (err) { console.info("Failed to execute SQL, err: " + err) return } - console.info('Create table done.') + console.info('Delete table done.') }) ``` @@ -1656,7 +1656,7 @@ Executes an SQL statement that contains specified arguments but returns no value | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| **Return value** @@ -1667,10 +1667,10 @@ Executes an SQL statement that contains specified arguments but returns no value **Example** ```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) +const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" +let promise = rdbStore.executeSql(SQL_DELETE_TABLE) promise.then(() => { - console.info('Create table done.') + console.info('Delete table done.') }).catch((err) => { console.info("Failed to execute SQL, err: " + err) }) @@ -1828,9 +1828,9 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. +Obtains the distributed table name of a remote device based on the local table name of the device. The distributed table name is required when the RDB store of a remote device is queried. -> **NOTE**
+> **NOTE** > > The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -1851,6 +1851,7 @@ Obtains the distributed table name for a remote device based on the local table ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceId = null; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -1859,7 +1860,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; + deviceId = devices[0].deviceId; }) @@ -1876,9 +1877,9 @@ rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableNa obtainDistributedTableName(device: string, table: string): Promise<string> -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. +Obtains the distributed table name of a remote device based on the local table name of the device. The distributed table name is required when the RDB store of a remote device is queried. -> **NOTE**
+> **NOTE** > > The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -1904,6 +1905,7 @@ Obtains the distributed table name for a remote device based on the local table ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceId = null; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -1912,7 +1914,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; + deviceId = devices[0].deviceId; }) let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") @@ -1946,6 +1948,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceIds = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -1954,7 +1957,6 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceIds = []; for (var i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } @@ -1995,13 +1997,14 @@ Synchronizes data between devices. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<Array<[string, number]>> | Promise used to return the synchronization result.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +| Promise<Array<[string, number]>> | Promise used to send the synchronization result.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceIds = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2010,7 +2013,6 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceIds = []; for (var i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } 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 5694b698b4f81cca15db7cad6777a156765df6d2..3e7e078f595f8468bf78cc953f5267c5515360a2 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -1,12 +1,12 @@ # @ohos.data.relationalStore (RDB Store) -The relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. +The relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The worker threads are not supported. The **relationalStore** module provides the following functions: - [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. - [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. -- [ResultSet](#resultset): provides APIs for accessing the result set obtained from the RDB store. +- [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store. > **NOTE** > @@ -317,6 +317,10 @@ Defines the RDB store configuration. Enumerates the RDB store security levels. +> **NOTE** +> +> To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Cross-Device Data Synchronization Mechanism](../../database/sync-app-data-across-devices-overview.md#cross-device-data-synchronization-mechanism). + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Name| Value | Description | @@ -416,7 +420,7 @@ inDevices(devices: Array<string>): RdbPredicates Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. -> **NOTE**
+> **NOTE** > > The value of **devices** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -439,6 +443,7 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceIds = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -447,7 +452,6 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceIds = []; for (var i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } @@ -1244,9 +1248,9 @@ predicates.notIn("NAME", ["Lisa", "Rose"]); ## RdbStore -Provides methods to manage an RDB store. +Provides APIs to manage an RDB store. -Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). +Before using the APIs of this class, use [executeSql](#executesql) to initialize the database table structure and related data. ### Attributes10+ @@ -1281,6 +1285,14 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re | values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1316,6 +1328,14 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re | conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1355,6 +1375,14 @@ Inserts a row of data into a table. This API uses a promise to return the result | --------------------- | ------------------------------------------------- | | Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1394,6 +1422,14 @@ Inserts a row of data into a table. This API uses a promise to return the result | --------------------- | ------------------------------------------------- | | Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1427,6 +1463,14 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur | values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1480,6 +1524,14 @@ Batch inserts data into a table. This API uses a promise to return the result. | --------------------- | ----------------------------------------------------------- | | Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1527,6 +1579,14 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T | predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1564,6 +1624,14 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T | conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1605,6 +1673,14 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr | --------------------- | ----------------------------------------- | | Promise<number> | Promise used to return the number of rows updated.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1646,6 +1722,14 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr | --------------------- | ----------------------------------------- | | Promise<number> | Promise used to return the number of rows updated.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1684,6 +1768,14 @@ Updates data based on the specified **DataSharePredicates** object. This API use | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1729,6 +1821,14 @@ Updates data based on the specified **DataSharePredicates** object. This API use | --------------------- | ----------------------------------------- | | Promise<number> | Promise used to return the number of rows updated.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1764,6 +1864,14 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. | predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1798,6 +1906,14 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. | --------------------- | ------------------------------- | | Promise<number> | Promise used to return the number of rows deleted.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1829,6 +1945,14 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -1867,6 +1991,14 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o | --------------------- | ------------------------------- | | Promise<number> | Promise used to return the number of rows deleted.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -2027,7 +2159,7 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. -> **NOTE**
+> **NOTE** > > The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -2048,6 +2180,7 @@ Queries data from the RDB store of a remote device based on specified conditions ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceId = null; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2056,7 +2189,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; + deviceId = devices[0].deviceId; }) let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); @@ -2079,7 +2212,7 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. -> **NOTE**
+> **NOTE** > > The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -2105,6 +2238,7 @@ Queries data from the RDB store of a remote device based on specified conditions ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceId = null; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2113,12 +2247,12 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; + deviceId = devices[0].deviceId; }) let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); -let promise = store.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +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}`); @@ -2137,11 +2271,11 @@ Queries data using the specified SQL statement. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | -| sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | -| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned. | **Example** @@ -2166,10 +2300,10 @@ Queries data using the specified SQL statement. This API uses a promise to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------ | ---- | --------------------- | -| sql | string | Yes | SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| **Return value** @@ -2180,7 +2314,7 @@ Queries data using the specified SQL statement. This API uses a promise to retur **Example** ```js -let promise = store.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.info(`ResultSet column names: ${resultSet.columnNames}`); console.info(`ResultSet column count: ${resultSet.columnCount}`); @@ -2199,22 +2333,30 @@ Executes an SQL statement that contains specified arguments but returns no value **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------ | ---- | ---------------------- | -| sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| **Example** ```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)" -store.executeSql(SQL_CREATE_TABLE, null, function(err) { +const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" +store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], function(err) { if (err) { console.error(`ExecuteSql failed, err: ${err}`); return; } - console.info(`Create table done.`); + console.info(`Delete table done.`); }) ``` @@ -2228,10 +2370,10 @@ Executes an SQL statement that contains specified arguments but returns no value **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------ | ---- | --------------------- | -| sql | string | Yes | SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| **Return value** @@ -2239,13 +2381,21 @@ Executes an SQL statement that contains specified arguments but returns no value | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```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 = store.executeSql(SQL_CREATE_TABLE); +const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" +let promise = store.executeSql(SQL_DELETE_TABLE); promise.then(() => { - console.info(`Create table done.`); + console.info(`Delete table done.`); }).catch((err) => { console.error(`ExecuteSql failed, err: ${err}`); }) @@ -2259,6 +2409,14 @@ Starts the transaction before executing an SQL statement. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800047 | The WAL file size exceeds the default limit.| + **Example** ```js @@ -2541,9 +2699,9 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. +Obtains the distributed table name of a remote device based on the local table name of the device. The distributed table name is required when the RDB store of a remote device is queried. -> **NOTE**
+> **NOTE** > > The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -2564,6 +2722,7 @@ Obtains the distributed table name for a remote device based on the local table ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceId = null; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2572,7 +2731,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; + deviceId = devices[0].deviceId; }) store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { @@ -2588,9 +2747,9 @@ store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) obtainDistributedTableName(device: string, table: string): Promise<string> -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. +Obtains the distributed table name of a remote device based on the local table name of the device. The distributed table name is required when the RDB store of a remote device is queried. -> **NOTE**
+> **NOTE** > > The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. @@ -2616,6 +2775,7 @@ Obtains the distributed table name for a remote device based on the local table ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceId = null; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2624,7 +2784,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceId = devices[0].deviceId; + deviceId = devices[0].deviceId; }) let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE"); @@ -2658,6 +2818,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceIds = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2666,7 +2827,6 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceIds = []; for (var i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } @@ -2714,6 +2874,7 @@ Synchronizes data between devices. This API uses a promise to return the result. ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; let dmInstance = null; +let deviceIds = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -2722,7 +2883,6 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - let deviceIds = []; for (var i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } @@ -2786,7 +2946,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses | -------- | ---------------------------------- | ---- | ------------------------------------------ | | event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. | | type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. | -| observer | Callback<Array<string>> | Yes | Callback for the data change event. | +| observer | Callback<Array<string>> | Yes | Callback for the data change event. | **Example** @@ -3301,3 +3461,5 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode | **ID**| **Error Message** | | ------------ | ------------------------------------------------------------ | | 14800012 | The result set is empty or the specified location is invalid. | + + diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index ad8ab9f54dfd43754e6e00cdfbe5ba5c9e1d39c4..4b6512f5a040108714c782387e81393a9dab4df7 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -109,7 +109,7 @@ Obtains the default application based on a system-defined application type or a **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -165,7 +165,7 @@ Obtains the default application of a user based on a system-defined application **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -217,7 +217,7 @@ Obtains the default application based on a system-defined application type or a **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -266,7 +266,7 @@ Sets the default application based on a system-defined application type or a fil **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -338,7 +338,7 @@ Sets the default application for a user based on a system-defined application ty **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -399,7 +399,7 @@ Sets the default application based on a system-defined application type or a fil **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -458,7 +458,7 @@ Resets the default application based on a system-defined application type or a f **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -508,7 +508,7 @@ Resets the default application for a user based on a system-defined application **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -559,7 +559,7 @@ Resets the default application based on a system-defined application type or a f **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 634231b14e689d9a2dbdb5e8cc74b3f0117889b8..62bfa800173c03c08c1402d79a9174b3778375ca 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -291,6 +291,63 @@ try { } ``` +## display.on('privateModeChange')10+ + +on(type: 'privateModeChange', callback: Callback<boolean>): void + +Subscribes to privacy mode changes of this display. When there is a privacy window in the foreground of the display, the display is in privacy mode, and the content in the privacy window cannot be captured or recorded. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at 'privateModeChange', indicating the event of display privacy mode changes.| +| callback | Callback<boolean> | Yes | Callback used to return whether the privacy mode of the display is changed. The value **true** means that the display changes to the privacy mode, and **false** means the opposite.| + +**Example** + +```js +let callback = (data) => { + console.info('Listening enabled. Data: ' + JSON.stringify(data)); +}; +try { + display.on("privateModeChange", callback); +} catch (exception) { + console.error('Failed to register callback. Code: ' + JSON.stringify(exception)); +} +``` + +## display.off('privateModeChange')10+ + +off(type: 'privateModeChange', callback?: Callback<boolean>): void + +Unsubscribes from privacy mode changes of this display. When there is a privacy window in the foreground of the display, the display is in privacy mode, and the content in the privacy window cannot be captured or recorded. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'privateModeChange'**, indicating the event of display private mode changes.| +| callback | Callback<boolean> | No | Callback used to return whether the privacy mode of the display is changed. The value **true** means that the display changes to the privacy mode, and **false** means the opposite.| + +**Example** + +```js +try { + display.off("privateModeChange"); +} catch (exception) { + console.error('Failed to unregister callback. Code: ' + JSON.stringify(exception)); +} +``` + ## display.getDefaultDisplay(deprecated) getDefaultDisplay(callback: AsyncCallback<Display>): void diff --git a/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md b/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md new file mode 100644 index 0000000000000000000000000000000000000000..3fa93ccd105819ea71a709d861a71287ae1312cc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md @@ -0,0 +1,142 @@ +# @ohos.file.cloudSyncManager (Device-Cloud Synchronization Management) + +The **cloudSyncManager** module provides APIs for changing the cloud and device service status and notifying the data changes. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 10. 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 cloudSyncManager from '@ohos.file.cloudSyncManager'; +``` + +## cloudSyncManager.changeAppCloudSwitch + +changeAppCloudSwitch(accountId: string, bundleName: string, status: boolean): Promise<void>; + +Changes the device-cloud file synchronization switch for an application. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.DistributedFileService.CloudSyncManager + +**Parameters** + +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| accountId | string | Yes | Account ID.| +| bundleName | string | Yes | Bundle name of the application.| +| status | boolean | Yes | State of the cloud-device file synchronization switch to set. The value **true** means to enable this function; the value **false** means the opposite.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```js + let accountId = "testAccount"; + let bundleName = "com.example.bundle"; + cloudSyncManager.changeAppCloudSwitch(accountId, bundleName, true).then(function() { + console.info("changeAppCloudSwitch successfully"); + }).catch(function(err) { + console.info("changeAppCloudSwitch failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## cloudSyncManager.changeAppCloudSwitch + +changeAppCloudSwitch(accountId: string, bundleName: string, status: boolean, callback: AsyncCallback<void>): void; + +Changes the device-cloud file synchronization switch for an application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.DistributedFileService.CloudSyncManager + +**Parameters** + +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| accountId | string | Yes | Account ID.| +| bundleName | string | Yes | Bundle name of the application.| +| status | boolean | Yes | State of the cloud-device file synchronization switch to set. The value **true** means to enable this function; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + + ```js + let accountId = "testAccount"; + let bundleName = "com.example.bundle"; + cloudSyncManager.changeAppCloudSwitch(accountId, bundleName, true, (err) => { + if (err) { + console.info("changeAppCloudSwitch failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("changeAppCloudSwitch successfully"); + } + }); + ``` +## cloudSyncManager.notifyDataChange + +notifyDataChange(accountId: string, bundleName: string): Promise<void>; + +Notifies the cloud and device services of the application data change in the cloud. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.DistributedFileService.CloudSyncManager + +**Parameters** + +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| accountId | string | Yes | Account ID.| +| bundleName | string | Yes | Bundle name of the application.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------- | +| Promise<void> | Promise used to return the application data change in the cloud.| + +**Example** + + ```js + let accountId = "testAccount"; + let bundleName = "com.example.bundle"; + cloudSyncManager.notifyDataChange(accountId, bundleName).then(function() { + console.info("notifyDataChange successfully"); + }).catch(function(err) { + console.info("notifyDataChange failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## cloudSyncManager.notifyDataChange + +notifyDataChange(accountId: string, bundleName: string, callback: AsyncCallback<void>): void; + +Notifies the cloud and device services of the application data change in the cloud. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.DistributedFileService.CloudSyncManager + +**Parameters** + +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| accountId | string | Yes | Account ID.| +| bundleName | string | Yes | Bundle name of the application.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the application data change in the cloud.| + +**Example** + + ```js + let accountId = "testAccount"; + let bundleName = "com.example.bundle"; + cloudSyncManager.notifyDataChange(accountId, bundleName, (err) => { + if (err) { + console.info("notifyDataChange failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("notifyDataChange successfully"); + } + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-file-fileUri.md b/en/application-dev/reference/apis/js-apis-file-fileUri.md index 9f524c06525a1a1f6ebdd8b2fd0117a2c43b89d5..f8c6717fab58f9ca5eacac6ebc3963a6faae63fa 100644 --- a/en/application-dev/reference/apis/js-apis-file-fileUri.md +++ b/en/application-dev/reference/apis/js-apis-file-fileUri.md @@ -1,4 +1,4 @@ -# @ohos.file.fileUri (File URI) +# @ohos.file.fileuri (File URI) The **fileUri** module allows the uniform resource identifier (URI) of a file to be obtained based on the file path. With the file URI, you can use the APIs provided by [@ohos.file.fs](js-apis-file-fs.md) to operate the file. @@ -9,7 +9,7 @@ The **fileUri** module allows the uniform resource identifier (URI) of a file to ## Modules to Import ```js -import fileUri from "@ohos.file.fileUri"; +import fileuri from "@ohos.file.fileuri"; ``` Before using this module, you need to obtain the path of the file in the application sandbox. The following is an example: @@ -57,5 +57,5 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```js let filePath = pathDir + "test.txt"; -let uri = fileUri.getUriFromPath(filePath); +let uri = fileuri.getUriFromPath(filePath); ``` diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md index 44296a0c8391d0b8005277b3e363571f01892900..d210887e3e92e5baea3dd6c7c45ad709e7244587 100644 --- a/en/application-dev/reference/apis/js-apis-file-fs.md +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -1,12 +1,9 @@ # @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. +The **fs** module provides APIs for file operations, including basic file management, directory management, file information statistics, and data read and write using a stream. -> **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). +> **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. ## Modules to Import @@ -14,9 +11,13 @@ The **fs** module provides APIs for file operations, including basic file manage import fs from '@ohos.file.fs'; ``` +## Error Code Description + +The APIs of this module supports processing of error codes. For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + ## Guidelines -Before using the APIs provided by this module to perform operations on files or folders, obtain the path of the file or directory in the application sandbox as follows: +Before using the APIs provided by this module to perform operations on a file or folder, obtain the application sandbox path of the file or folder as follows: **Stage Model** @@ -56,7 +57,7 @@ Obtains detailed file information. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file.| +| file | string\|number | Yes | Application sandbox path or file descriptor (FD) of the file.| **Return value** @@ -87,7 +88,7 @@ Obtains detailed file information. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------ | -| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| file | string\|number | Yes | Application sandbox path or FD of the file. | | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| **Example** @@ -114,7 +115,7 @@ Obtains detailed file information synchronously. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file.| +| file | string\|number | Yes | Application sandbox path or FD of the file.| **Return value** @@ -142,13 +143,13 @@ Checks whether a file exists. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox. | +| path | string | Yes | Application sandbox path of the file. | **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<boolean> | Promise used to return a Boolean value.| + | Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| **Example** @@ -176,7 +177,7 @@ Checks whether a file exists. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox. | +| path | string | Yes | Application sandbox path of the file. | | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -206,7 +207,13 @@ Synchronously checks whether a file exists. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox. | +| path | string | Yes | Application sandbox path of the file. | + +**Return value** + + | Type | Description | + | ------------------- | ---------------------------- | + | boolean | Returns **true** if the file exists; returns **false** otherwise.| **Example** @@ -410,7 +417,7 @@ Creates a directory. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the directory in the application sandbox. | +| path | string | Yes | Application sandbox path of the directory. | **Return value** @@ -442,7 +449,7 @@ Creates a directory. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the directory in the application sandbox. | +| path | string | Yes | Application sandbox path of the directory. | | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | **Example** @@ -471,7 +478,7 @@ Synchronously creates a directory. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the directory in the application sandbox. | +| path | string | Yes | Application sandbox path of the directory. | **Example** @@ -493,7 +500,7 @@ Opens a file. This API uses a promise to return the result. File uniform resourc | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| path | string | Yes | Application sandbox path 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** @@ -526,7 +533,7 @@ Opens a file. This API uses an asynchronous callback to return the result. File | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| path | string | Yes | Application sandbox path 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** @@ -554,7 +561,7 @@ Synchronously opens a file. File URIs are supported. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| path | string | Yes | Application sandbox path 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** @@ -689,7 +696,7 @@ Deletes a directory. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Path of the directory in the application sandbox.| +| path | string | Yes | Application sandbox path of the directory.| **Return value** @@ -721,7 +728,7 @@ Deletes a directory. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | -| path | string | Yes | Path of the directory in the application sandbox.| +| path | string | Yes | Application sandbox path of the directory.| | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | **Example** @@ -750,7 +757,7 @@ Synchronously deletes a directory. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Path of the directory in the application sandbox.| +| path | string | Yes | Application sandbox path of the directory.| **Example** @@ -772,7 +779,7 @@ Deletes a file. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Path of the file in the application sandbox.| +| path | string | Yes | Application sandbox path of the file.| **Return value** @@ -804,7 +811,7 @@ Deletes a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | -| path | string | Yes | Path of the file in the application sandbox.| +| path | string | Yes | Application sandbox path of the file.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | **Example** @@ -833,7 +840,7 @@ Synchronously deletes a file. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Path of the file in the application sandbox.| +| path | string | Yes | Application sandbox path of the file.| **Example** @@ -956,8 +963,8 @@ Truncates a file. This API uses a promise to return the result. | 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.| +| file | string\|number | Yes | Application sandbox path or FD of the file. | +| len | number | No | File length, in bytes, after truncation. The default value is **0**.| **Return value** @@ -990,8 +997,8 @@ Truncates a file. This API uses an asynchronous callback to return the result. | 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.| +| file | string\|number | Yes | Application sandbox path or FD of the file. | +| len | number | No | File length, in bytes, after truncation. The default value is **0**.| | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -1021,8 +1028,8 @@ Synchronously truncates a file. | 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.| +| file | string\|number | Yes | Application sandbox path or FD of the file. | +| len | number | No | File length, in bytes, after truncation. The default value is **0**.| **Example** @@ -1045,7 +1052,7 @@ Reads the text content of a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filePath | string | Yes | Path of the file in the application sandbox. | +| filePath | string | Yes | Application sandbox path of the file. | | 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** @@ -1078,7 +1085,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| filePath | string | Yes | Path of the file in the application sandbox. | +| filePath | string | Yes | Application sandbox path of the file. | | 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 invoked to return the content read. | @@ -1108,7 +1115,7 @@ Synchronously reads the text of a file. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filePath | string | Yes | Path of the file in the application sandbox. | +| filePath | string | Yes | Application sandbox path of the file. | | 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** @@ -1137,7 +1144,7 @@ Obtains information about a symbolic link. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| path | string | Yes | Path of the symbolic link in the application sandbox.| +| path | string | Yes | Application sandbox path of the file.| **Return value** @@ -1169,7 +1176,7 @@ Obtains information about a symbolic link. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | -------------------------------------- | -| path | string | Yes | Path of the symbolic link in the application sandbox.| +| path | string | Yes | Application sandbox path of the file.| | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the symbolic link information obtained. | **Example** @@ -1197,7 +1204,7 @@ Obtains information about a symbolic link synchronously. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| path | string | Yes | Path of the file in the application sandbox.| +| path | string | Yes | Application sandbox path of the file.| **Return value** @@ -1224,8 +1231,8 @@ Renames a file or folder. This API uses a promise to return the result. | 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. | +| oldPath | string | Yes | Application sandbox path of the file to rename.| +| newPath | string | Yes | Application sandbox path of the renamed file. | **Return value** @@ -1257,8 +1264,8 @@ Renames a file or folder. This API uses an asynchronous callback to return the r | 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. | +| oldPath | string | Yes | Application sandbox path of the file to rename.| +| newPath | string | Yes | Application sandbox path of the renamed file. | | callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | **Example** @@ -1287,8 +1294,8 @@ Renames a file or folder synchronously. | 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. | +| oldPath | string | Yes | Application sandbox path of the file to rename.| +| newPath | string | Yes | Application sandbox path of the renamed file. | **Example** @@ -1487,8 +1494,8 @@ Creates a symbolic link based on a file path. This API uses a promise to return | 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.| +| target | string | Yes | Application sandbox path of the source file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link.| **Return value** @@ -1520,8 +1527,8 @@ Creates a symbolic link based on a file path. This API uses an asynchronous call | 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. | +| target | string | Yes | Application sandbox path of the source file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link. | | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| **Example** @@ -1550,8 +1557,8 @@ Synchronously creates a symbolic link based on a file path. | 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.| +| target | string | Yes | Application sandbox path of the source file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link.| **Example** @@ -1566,9 +1573,9 @@ listFile(path: string, options?: { recursion?: boolean; listNum?: number; filter?: Filter; -}): Promise; +}): Promise -Lists all files in a folder. This API uses a promise to return the result.
This API supports recursive listing of all files (including files in subfolders) and file filtering. +Lists all files in a directory. This API uses a promise to return the result.
This API supports recursive listing of all files (including files in subdirectories) and file filtering. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1576,14 +1583,14 @@ Lists all files in a folder. This API uses a promise to return the result.
Th | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | path | string | Yes | Path of the folder in the application sandbox.| - | options | Object | No | File filtering options.| + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| **options parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| @@ -1621,23 +1628,23 @@ listFile(path: string, options?: { recursion?: boolean; listNum?: number; filter?: Filter; -}, callback: AsyncCallback): void; +}, callback: AsyncCallback): void -Lists all files in a folder. This API uses an asynchronous callback to return the result.
This API supports recursive listing of all files (including files in subfolders) and file filtering. +Lists all files in a directory. This API uses an asynchronous callback to return the result.
This API supports recursive listing of all files (including files in subdirectories) and file filtering. **Parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | path | string | Yes | Path of the folder in the application sandbox.| - | options | Object | No | File filtering options.| + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| | callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | **options parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| @@ -1672,22 +1679,22 @@ listFileSync(path: string, options?: { recursion?: boolean; listNum?: number; filter?: Filter; -}): string[]; +}): string[] -Lists all files in a folder synchronously. This API supports recursive listing of all files (including files in subfolders) and file filtering. +Lists all files in a directory synchronously. This API supports recursive listing of all files (including files in subdirectories) and file filtering. **Parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | path | string | Yes | Path of the folder in the application sandbox.| - | options | Object | No | File filtering options.| + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| **options parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| @@ -1716,9 +1723,89 @@ Lists all files in a folder synchronously. This API supports recursive listing o console.info("filename: %s", filenames[i]); } ``` + +## fs.moveDir10+ + +moveDir(src: string, dest: string, mode?: number): Promise\ + +Moves a folder. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source folder.| + | dest | string | Yes | Application sandbox path of the destination folder.| + | mode | number | No | Mode for moving the folder. The default value is **0**.
- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.
- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.
- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.
- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.| + +**Return value** + + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| + +**Example** + + ```js + // move directory from srcPath to destPath/srcPath + let srcPath = pathDir + "/srcDir/"; + let destPath = pathDir + "/destDir/"; + fs.moveDir(srcPath, destPath, 1).then(() => { + console.info("move directory succeed"); + }).catch((err) => { + if (err.code == 13900015) { + for (let i = 0; i < err.data.length; i++) { + console.info("move directory failed with conflicting files: " + err.data[i].srcFile + + " " + err.data[i].destFile); + } + } else { + console.info("move directory failed with error message: " + err.message + ", error code: " + err.code); + } + }); + ``` + +## fs.moveDir10+ + +moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): void + +Moves a folder. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source folder.| + | dest | string | Yes | Application sandbox path of the destination folder.| + | mode | number | No | Whether to overwrite the file of the same name in the destination directory. The default value is **0**.
- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.
- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.
- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.
- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the folder is moved. | + +**Example** + + ```js + // move directory from srcPath to destPath/srcPath + let srcPath = pathDir + "/srcDir/"; + let destPath = pathDir + "/destDir/"; + fs.moveDir(srcPath, destPath, 1, (err) => { + if (err && err.code == 13900015) { + for (let i = 0; i < err.data.length; i++) { + console.info("move directory failed with conflicting files: " + err.data[i].srcFile + + " " + err.data[i].destFile); + } + } else if (err) { + console.info("move directory failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("move directory succeed"); + } + }); + ``` + ## fs.moveFile -moveFile(src: string, dest: string, mode?: number): Promise\; +moveFile(src: string, dest: string, mode?: number): Promise\ Moves a file. This API uses a promise to return the result. @@ -1728,10 +1815,16 @@ Moves a file. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | src | string | Yes | Path of the file to move in the application sandbox.| - | dest | string | Yes | Destination path of the file in the application sandbox.| + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| | mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| +**Return value** + + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| + **Example** ```js @@ -1746,7 +1839,7 @@ Moves a file. This API uses a promise to return the result. ## fs.moveFile -moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\): void; +moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\): void Moves a file. This API uses an asynchronous callback to return the result. @@ -1756,8 +1849,8 @@ Moves a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | src | string | Yes | Path of the file to move in the application sandbox.| - | dest | string | Yes | Destination path of the file in the application sandbox.| + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| | mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | @@ -1777,7 +1870,7 @@ Moves a file. This API uses an asynchronous callback to return the result. ## fs.moveFileSync -moveFile(src: string, dest: string, mode?: number): void; +moveFile(src: string, dest: string, mode?: number): void Moves a file synchronously. @@ -1787,8 +1880,8 @@ Moves a file synchronously. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | src | string | Yes | Path of the file to move in the application sandbox.| - | dest | string | Yes | Destination path of the file in the application sandbox.| + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| | mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| **Example** @@ -1888,7 +1981,7 @@ Synchronously creates a temporary directory. 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. +Creates a stream based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1896,7 +1989,7 @@ Opens a file stream based on the file path. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox. | +| path | string | Yes | Application sandbox path 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** @@ -1921,7 +2014,7 @@ Opens a file stream based on the file path. This API uses a promise to return th 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. +Creates a stream based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1929,9 +2022,9 @@ Opens a file stream based on the file path. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox. | +| path | string | Yes | Application sandbox path 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. | +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is created asynchronously. | **Example** @@ -1950,7 +2043,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba createStreamSync(path: string, mode: string): Stream -Synchronously opens a stream based on the file path. +Synchronously creates a stream based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1958,7 +2051,7 @@ Synchronously opens a stream based on the file path. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the file in the application sandbox. | +| path | string | Yes | Application sandbox path 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** @@ -1979,7 +2072,7 @@ Synchronously opens a stream based on the file path. 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. +Opens a stream based on the file descriptor. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2014,7 +2107,7 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret 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. +Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2085,8 +2178,8 @@ Creates a **Watcher** object to observe file or directory changes. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | - | path | string | Yes | Path of the file or directory to observe in the application sandbox. | - | events | number | Yes | Events to observe. Multiple events can be separated by a bitwise OR operator (|).
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted form the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **0xfff: IN_ALL_EVENTS**: All events.| + | path | string | Yes | Application sandbox path of the file or directory to observe. | + | events | number | Yes | Events to observe. Multiple events can be separated by a bitwise OR operator (|)|.
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **0xfff: IN_ALL_EVENTS**: All events.| | listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. | **Return value** @@ -2317,7 +2410,7 @@ Checks whether this file is a symbolic link. ## Stream -Provides file stream management. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. +Provides a stream for file operations. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. ### close @@ -2638,7 +2731,7 @@ Synchronously reads data from the stream. | 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.
| + | 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** @@ -2668,7 +2761,7 @@ Represents a **File** object opened by **open()**. ### lock -lock(exclusive?: boolean): Promise\; +lock(exclusive?: boolean): Promise\ Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. @@ -2699,7 +2792,7 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A ### lock -lock(exclusive?: boolean, callback: AsyncCallback\): void; +lock(exclusive?: boolean, callback: AsyncCallback\): void Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. @@ -2727,7 +2820,7 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A ### tryLock -tryLock(exclusive?: boolean): void; +tryLock(exclusive?: boolean): void Applies an exclusive lock or a shared lock on this file in non-blocking mode. @@ -2749,7 +2842,7 @@ Applies an exclusive lock or a shared lock on this file in non-blocking mode. ### unlock -unlock(): void; +unlock(): void Unlocks this file synchronously. @@ -2808,7 +2901,7 @@ Stops listening. ## OpenMode -Defines the constants of the **mode** parameter used in **open()**. It species the mode for opening a file. +Defines the constants of the **mode** parameter used in **open()**. It specifies the mode for opening a file. **System capability**: SystemCapability.FileManagement.File.FileIO diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 3bf1e990cd2fcb0f2853c224d0adf70ce5e7b5dc..de7d46dc6b83bb64d24cb5a0e6c5c1857616c329 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -4,7 +4,7 @@ The **geolocation** module provides a wide array of location services, including > **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. +> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md). ## Applying for Permissions @@ -1486,7 +1486,7 @@ Sets the priority of the location request. Enumerates error codes of the location service. > **NOTE**
-> This API is deprecated since API version 9. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager](../errorcodes/errorcode-geoLocationManager.md). **Required permissions**: ohos.permission.LOCATION diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 3b3c16a565cca24d717a7843b08ccbb615b18c7a..9c6037df7f907354d71a6eacb211855b579945a5 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -80,9 +80,9 @@ image.createPixelMap(color, opts, (error, pixelmap) => { ## PixelMap7+ -Provides APIs to read or write image pixel map data and obtain image pixel map information. Before calling any API in **PixelMap**, you must use **createPixelMap** to create a **PixelMap** object. +Provides APIs to read or write image pixel map data and obtain image pixel map information. Before calling any API in **PixelMap**, you must use **createPixelMap** to create a **PixelMap** object. Currently, the maximum size of a serialized pixel map is 128 MB. A larger size will cause a display failure. The size is calculated as follows: Width * Height * Number of bytes occupied by each pixel. - ### Attributes +### Attributes **System capability**: SystemCapability.Multimedia.Image.Core @@ -950,7 +950,7 @@ Creates an **ImageSource** instance based on the URI. ```js // Stage model const context = getContext(this); -const path = context.getCacheDir() + "/test.jpg"; +const path = context.cacheDir() + "/test.jpg"; const imageSourceApi = image.createImageSource(path); ``` @@ -2227,7 +2227,7 @@ Creates an **ImageCreator** instance by specifying the image width, height, form | Type | Description | | ------------------------------ | --------------------------------------- | -| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| **Example** @@ -2729,7 +2729,7 @@ Describes image properties. ## PropertyKey7+ -Describes the exchangeable image file format (EXIF) information of an image. +Describes the exchangeable image file format (EXIF) data of an image. **System capability**: SystemCapability.Multimedia.Image.Core diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index 54c8f0400be1f1e8b9f9b836098a94ace0c4f637..13573de144bf718175bf6690408f7f52c388a8fc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,6 +1,6 @@ # AbilityResult -The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-context.md#abilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-context.md#abilitycontextterminateselfwithresult). +The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7). > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index 33de553183850772206e48cbd1e732d3a3b8cc4f..0eebe1059e031d66c7353b26ea8812b0c48e04a6 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -15,10 +15,10 @@ Want is a carrier for information transfer between objects (application componen | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | -| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags). | -| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: Object} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | -| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags).| +| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | +| parameters | {[key: string]: Object} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | | moduleName9+ | string | No | Module to which the ability belongs.| **Example** @@ -41,12 +41,12 @@ Want is a carrier for information transfer between objects (application componen - Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility): ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; // ... let fd; try { - fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); + fd = fs.openSync('/data/storage/el2/base/haps/pic.png').fd; } catch(e) { console.error('openSync fail: ${JSON.stringify(e)}'); } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 445443209e3ca4a670cfced56f285530144505c4..a3e98a1cebd86dc45ac0e09f17ca505543d52935 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -57,7 +57,7 @@ Defines a rectangle. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | --------- | | left | number | Yes | No | Left boundary of the rectangle.| | top | number | Yes | No | Top boundary of the rectangle.| @@ -85,14 +85,14 @@ Sets the concerned target bundle. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ----------- | ------------------- | ---- | -------- | | targetNames | Array<string> | Yes | Name of the target bundle.| **Return value** -| Type | Description | -| ---------------------- | --------------------- | +| Type | Description | +| ------------------- | ---------------- | | Promise<void> | Promise that returns no value.| **Example** @@ -120,9 +120,9 @@ Sets the concerned target bundle. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | -------- | -| targetNames | Array<string> | Yes | Name of the target bundle.| +| Name | Type | Mandatory | Description | +| ----------- | ------------------------- | ---- | ---------------------------------------- | +| targetNames | Array<string> | Yes | Name of the target bundle. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation fails, **error** that contains data is returned.| **Example** @@ -152,7 +152,7 @@ Obtains the focus element. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------------------- | ------- | ---- | ------------------- | | isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| @@ -166,8 +166,8 @@ Obtains the focus element. This API uses a promise to return the result. For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -196,16 +196,16 @@ Obtains the focus element. This API uses an asynchronous callback to return the **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -236,10 +236,10 @@ Obtains the focus element. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | -| isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus.| -| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ----------------- | +| isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| **Example** @@ -269,8 +269,8 @@ Obtains the root element of a window. This API uses a promise to return the resu **Parameters** -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ---------------------- | | windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| **Return value** @@ -283,8 +283,8 @@ Obtains the root element of a window. This API uses a promise to return the resu For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -313,16 +313,16 @@ Obtains the root element of a window. This API uses an asynchronous callback to **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -353,17 +353,17 @@ Obtains the root element of a window. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | -| windowId | number | Yes | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| -| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------- | +| windowId | number | Yes | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element. | **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -395,22 +395,22 @@ Obtains the list of windows on a display. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | --------------------- | | displayId | number | No | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| **Return value** -| Type | Description | -| ----------------------------------- | ---------------------- | +| Type | Description | +| ---------------------------------------- | ---------------------- | | Promise<Array<AccessibilityElement>> | Promise used to return the window list.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -439,16 +439,16 @@ Obtains the list of windows on a display. This API uses an asynchronous callback **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -479,17 +479,17 @@ Obtains the list of windows on a display. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | -| displayId | number | Yes | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| -| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | --------------------- | +| displayId | number | Yes | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list. | **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -521,22 +521,22 @@ Inject a gesture. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject.| **Return value** -| Type | Description | -| ----------------------------------- | ---------------------- | +| Type | Description | +| ------------------- | ---------------- | | Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -569,17 +569,17 @@ Inject a gesture. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ------------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ---------------------------------------- | | 9300003 | Do not have accessibility right for this operation. | **Example** @@ -620,8 +620,8 @@ Obtains all attribute names of this element. This API uses a promise to return t **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ----------------------------- | ------------------------ | | Promise<Array<T>> | Promise used to return all attribute names of the element.| **Example** @@ -646,9 +646,9 @@ Obtains all attribute names of this element. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback<Array<T>> | Yes | Callback used to return all attribute names of the element.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ------------------- | +| callback | AsyncCallback<Array<T>> | Yes | Callback used to return all attribute names of the element.| **Example** @@ -674,22 +674,22 @@ Obtains the attribute value based on an attribute name. This API uses a promise **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| attributeName | T | Yes | Attribute name. | +| Name | Type | Mandatory | Description | +| ------------- | ---- | ---- | -------- | +| attributeName | T | Yes | Attribute name.| **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ---------------------------------------- | --------------------------- | | Promise<ElementAttributeValues[T]> | Promise used to return the attribute value.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ----------------------------- | | 9300004 | This property does not exist. | **Example** @@ -720,17 +720,17 @@ Obtains the attribute value based on an attribute name. This API uses an asynchr **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| attributeName | T | Yes | Attribute name. | -| callback | AsyncCallback<ElementAttributeValues[T]> | Yes | Callback used to return the attribute value.| +| Name | Type | Mandatory | Description | +| ------------- | ---------------------------------------- | ---- | ---------------------- | +| attributeName | T | Yes | Attribute name. | +| callback | AsyncCallback<ElementAttributeValues[T]> | Yes | Callback used to return the attribute value.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ----------------------------- | | 9300004 | This property does not exist. | **Example** @@ -762,8 +762,8 @@ Obtains the names of all actions supported by this element. This API uses a prom **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ---------------------------------- | -------------------------- | | Promise<Array<string>> | Promise used to return the names of all actions supported by the element.| **Example** @@ -788,9 +788,9 @@ Obtains the names of all actions supported by this element. This API uses an asy **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the names of all actions supported by the element.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the names of all actions supported by the element.| **Example** @@ -818,21 +818,21 @@ Performs an action based on the specified action name. This API uses a promise t | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). -| parameters | object | No | Parameter required for performing the target action. | +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | +| parameters | object | No | Parameters required for performing the target action. Not supported currently. | **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ------------------- | ---------------- | | Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ----------------------------- | | 9300005 | This action is not supported. | **Example** @@ -861,15 +861,15 @@ Performs an action based on the specified action name. This API uses an asynchro | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ----------------------------- | | 9300005 | This action is not supported. | **Example** @@ -898,18 +898,18 @@ Performs an action based on the specified action name. This API uses an asynchro **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action).| -| parameters | object | Yes | Parameter required for performing the target action. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ---------------------------------------- | +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action).| +| parameters | object | Yes | Parameters required for performing the target action. Not supported currently. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). -| ID| Error Message| -| ------- | -------------------------------- | +| ID | Error Message | +| ------- | ----------------------------- | | 9300005 | This action is not supported. | **Example** @@ -942,15 +942,15 @@ Queries the element information of the **content** type. This API uses a promise **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'content'**. | -| condition | string | Yes | Search criteria. | +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----------------------------- | +| type | string | Yes | Information type. The value is fixed at **'content'**.| +| condition | string | Yes | Search criteria. | **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ---------------------------------------- | ----------------------------- | | Promise<Array<AccessibilityElement>> | Promise used to return the result.| **Example** @@ -981,11 +981,11 @@ Queries the element information of the **content** type. This API uses an asynch **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'content'**. | -| condition | string | Yes | Search criteria. | -| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------------- | +| type | string | Yes | Information type. The value is fixed at **'content'**.| +| condition | string | Yes | Search criteria. | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the result. | **Example** @@ -1017,15 +1017,15 @@ Queries the element information of the **focusType** type. This API uses a promi **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'focusType'**. | -| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | +| Name | Type | Mandatory | Description | +| --------- | ----------------------- | ---- | ---------------------------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**.| +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ----------------------------------- | ------------------------------ | | Promise<AccessibilityElement> | Promise used to return the result.| **Example** @@ -1056,11 +1056,11 @@ Queries the element information of the **focusType** type. This API uses an asyn **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'focusType'**. | -| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | -| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**.| +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result. | **Example** @@ -1092,15 +1092,15 @@ Queries the element information of the **focusDirection** type. This API uses a **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | -| condition | [FocusDirection](#focusdirection) | Yes | Enumerates the focus directions. | +| Name | Type | Mandatory | Description | +| --------- | --------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**.| +| condition | [FocusDirection](#focusdirection) | Yes | Enumerates the focus directions. | **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------ | +| Type | Description | +| ----------------------------------- | -------------------------------- | | Promise<AccessibilityElement> | Promise used to return the result.| **Example** @@ -1131,11 +1131,11 @@ Queries the element information of the **focusDirection** type. This API uses an **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | -| condition | [FocusDirection](#focusdirection) | Yes | Direction of the next focus element. | -| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**.| +| condition | [FocusDirection](#focusdirection) | Yes | Direction of the next focus element. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index f84648998cc5d6201a7d8af6e0021896651063b7..476d143241154b165388a743950ed0d8f5afa48d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -46,26 +46,21 @@ Starts an ability. This API uses an asynchronous callback to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -118,26 +113,21 @@ Starts an ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -170,7 +160,7 @@ Starts an ability. This API uses a promise to return the result. startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void -Starts an ability. This API uses an asynchronous callback to return the result. +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -188,26 +178,21 @@ Starts an ability. This API uses an asynchronous callback to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -245,7 +230,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -264,27 +249,21 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -320,7 +299,7 @@ Starts an ability with the account ID and start options specified. This API uses Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -340,27 +319,21 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -400,7 +373,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -425,27 +398,21 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -497,18 +464,16 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -561,18 +526,16 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -623,19 +586,16 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -693,19 +653,16 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -754,15 +711,15 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -815,15 +772,15 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -874,16 +831,15 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -940,16 +896,15 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -997,12 +952,14 @@ Terminates this ability. This API uses an asynchronous callback to return the re | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1038,12 +995,14 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1084,14 +1043,13 @@ Connects this ability to a ServiceExtensionAbility. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | | 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000011 | Context does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1145,15 +1103,13 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | | 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000011 | Context does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1202,13 +1158,11 @@ Disconnects this ability from a ServiceExtensionAbility and after the successful | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000003 | Input error. The specified id does not exist. | -| 16000011 | Context does not exist. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1259,13 +1213,11 @@ Disconnects this ability from a ServiceExtensionAbility and after the successful | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000003 | Input error. The specified id does not exist. | -| 16000011 | Context does not exist. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1299,7 +1251,7 @@ Starts an ability in the foreground or background and obtains the caller object Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1322,16 +1274,17 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | | 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Incorrect ability type. | | 16000004 | Visibility verification failed. | | 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000006 | Cross-user operations are not allowed. | | 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000017 | The previous ability is starting, wait start later. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index b930a1027edd7c68715178a2229dbeb4979673eb..59edfc898f6c32815b3926c9775913351dc476e9 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -29,7 +29,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -54,12 +54,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -92,7 +93,7 @@ Starts an ability with the start options specified. This API uses an asynchronou Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -118,12 +119,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -160,7 +162,7 @@ Starts an ability. This API uses a promise to return the result. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -191,12 +193,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -235,7 +238,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -260,12 +263,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -302,7 +306,7 @@ Starts an ability with the start options specified. This API uses an asynchronou Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -328,12 +332,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -374,7 +379,7 @@ Starts an ability. This API uses a promise to return the result when the ability Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -406,12 +411,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -447,7 +453,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) @@ -477,12 +483,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -518,7 +525,7 @@ Starts an ability with the start options and account ID specified. This API uses Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) @@ -549,12 +556,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -593,7 +601,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) @@ -629,12 +637,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -693,6 +702,8 @@ Starts a ServiceExtensionAbility. This API uses an asynchronous callback to retu | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -747,6 +758,8 @@ Starts a ServiceExtensionAbility. This API uses a promise to return the result. | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -805,6 +818,8 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses an | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -863,6 +878,8 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses a | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -917,6 +934,8 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -970,6 +989,8 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1027,6 +1048,8 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1084,6 +1107,8 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic | 16000050 | Internal error. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1135,6 +1160,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1180,6 +1207,8 @@ Terminates this ability. This API uses a promise to return the result. | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1226,6 +1255,8 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1288,6 +1319,8 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1348,6 +1381,8 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1414,6 +1449,8 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1469,11 +1506,11 @@ Disconnects this ability from a ServiceExtensionAbility and after the successful | ID| Error Message| | ------- | -------------------------------- | -| 16000001 | The specified ability does not exist. | -| 16000005 | The specified process does not have the permission. | | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1517,11 +1554,11 @@ Disconnects this ability from a ServiceExtensionAbility and after the successful | ID| Error Message| | ------- | -------------------------------- | -| 16000001 | The specified ability does not exist. | -| 16000005 | The specified process does not have the permission. | | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1554,7 +1591,7 @@ Starts an ability in the foreground or background and obtains the caller object Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1581,15 +1618,12 @@ Observe the following when using this API: | 16000005 | The specified process does not have the permission. | | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | -| 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | -| 16000053 | The ability is not on the top of the UI. | -| 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** Start an ability in the background. @@ -1661,7 +1695,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) @@ -1691,12 +1725,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1732,7 +1767,7 @@ Starts an ability with the account ID and start options specified. This API uses Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) @@ -1763,12 +1798,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1807,7 +1843,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) @@ -1837,12 +1873,13 @@ Observe the following when using this API: | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1887,6 +1924,15 @@ Sets a label for this UIAbility in the mission. This API uses an asynchronous ca | label | string | Yes| Label of the ability to set.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1922,6 +1968,8 @@ Sets a label for this UIAbility in the mission. This API uses a promise to retur | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -1955,6 +2003,8 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -2010,6 +2060,8 @@ Sets an icon for this ability in the mission. This API uses a promise to return | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -2057,6 +2109,8 @@ Restores the WindowStage data in the UIAbility. | 16000011 | The context does not exist. | | 16000050 | Internal error. | +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -2083,7 +2137,8 @@ Checks whether this UIAbility is in the terminating state. | ID| Error Message| | ------- | -------------------------------- | | 16000011 | The context does not exist. | -| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -2100,7 +2155,7 @@ Starts a ServiceExtensionAbility that supports modal dialog boxes. After the Ser Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2112,6 +2167,26 @@ Observe the following when using this API: | want |[Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| | result | AsyncCallback<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Yes| Callback used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts @@ -2147,7 +2222,7 @@ Starts a ServiceExtensionAbility that supports modal dialog boxes. After the Ser Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2165,6 +2240,26 @@ Observe the following when using this API: | -------- | -------- | | Promise<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Promise used to return the result. +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md index 8f1a3fddc9344bcf5d04a526b5c70a77837e29d0..14a5ed2b9a6fee26af15baabfeb07470e9a0f658 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md @@ -14,16 +14,19 @@ import InputMethodSubtype from '@ohos.InputMethodSubtype'; ## Attributes - **System capability**: SystemCapability.MiscServices.InputMethodFramework + + +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -------- | | label | string | Yes| No| No| Label of the input method subtype.| -| name | string | Yes| No| Yes| Name of the input method subtype.| +| labelId10+ | string | Yes| No| No| Label ID of the input method subtype.| +| name | string | Yes| No| Yes| Bundle name of the input method.| | id | string | Yes| No| Yes| ID of the input method subtype.| | mode | string | Yes| No| No| Mode of the input method subtype, including **upper** (uppercase) and **lower** (lowercase).| | locale | string | Yes| No| Yes| Locale of the input method subtype.| | language | string | Yes| No| Yes| Language of the input method subtype.| | icon | string | Yes| No| No| Icon of the input method subtype.| | iconId | number | Yes| No| No| Icon ID of the input method subtype.| -| extra | object | Yes| Yes| Yes| Extra information of the input method subtype.| +| extra | object | Yes| Yes| No| Extra information of the input method subtype.
**NOTE**
This parameter is optional since API version 10.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 17bdc1697f905a48693041cff2b3a609803675b8..f6f1cf9ca6cf7a77d9e55c7ce329d81cbef1dc7f 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,6 +1,6 @@ # @ohos.inputMethod (Input Method Framework) -The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. +The **inputMethod** module is oriented to common foreground applications (third-party applications and system applications such as Notes, Messaging, and Settings). It provides input method control and management capabilities, including displaying or hiding the soft keyboard, switching between input methods, and obtaining the list of all input methods. > **NOTE** > @@ -33,10 +33,11 @@ Describes the input method application attributes. | -------- | -------- | -------- | -------- | -------- | | name9+ | string | Yes| No| Internal name of the input method. Mandatory.| | id9+ | string | Yes| No| Unique ID of the input method. Mandatory.| -| label9+ | string | Yes| No| External display name of the input method. Optional.| +| label9+ | string | Yes| No| External name of the input method. Optional.| +| labelId10+ | string | Yes| No| External ID of the input method. Optional.| | icon9+ | string | Yes| No| Icon of the input method. Optional.| | iconId9+ | number | Yes| No| Icon ID of the input method. Optional.| -| extra9+ | object | Yes| Yes| Extra information about the input method. Mandatory.| +| extra9+ | object | Yes| Yes| Extra information about the input method. Optional.
**NOTE**
This parameter is optional since API version 10.| | packageName(deprecated) | string | Yes| No| Name of the input method package. Mandatory.
**NOTE**
This API is supported since API version 8 and deprecated since API version 9. You are advised to use **name**.| | methodId(deprecated) | string | Yes| No| Unique ID of the input method. Mandatory.
**NOTE**
This API is supported since API version 8 and deprecated since API version 9. You are advised to use **id**.| @@ -231,7 +232,7 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb Switches to another subtype of the current input method. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications)
**NOTE**
Since API version 10, this permission is not required if the caller is the current input method. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -239,7 +240,7 @@ Switches to another subtype of the current input method. This API uses an asynch | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| +| target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md)| Yes| Input method subtype to switch to.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| **Error codes** @@ -256,9 +257,9 @@ For details about the error codes, see [Input Method Framework Error Codes](../e ```js try { inputMethod.switchCurrentInputMethodSubtype({ - id: "com.example.kikakeyboard", - label: "ServiceExtAbility", - name: "", + id: "ServiceExtAbility", + label: "", + name: "com.example.kikakeyboard", mode: "upper", locale: "", language: "", @@ -287,7 +288,7 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean& Switches to another subtype of the current input method. This API uses a promise to return the result. -**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications)
**NOTE**
Since API version 10, this permission is not required if the caller is the current input method. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -295,7 +296,7 @@ Switches to another subtype of the current input method. This API uses a promise | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -|target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| +|target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md)| Yes| Input method subtype to switch to.| **Return value** @@ -317,9 +318,9 @@ For details about the error codes, see [Input Method Framework Error Codes](../e ```js try { inputMethod.switchCurrentInputMethodSubtype({ - id: "com.example.kikakeyboard", - label: "ServiceExtAbility", - name: "", + id: "ServiceExtAbility", + label: "", + name: "com.example.kikakeyboard", mode: "upper", locale: "", language: "", @@ -352,7 +353,7 @@ Obtains the current input method subtype. | Type | Description | | -------------------------------------------- | ------------------------ | -| [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype) | Current input method subtype.| +| [InputMethodSubtype](./js-apis-inputmethod-subtype.md) | Current input method subtype.| **Example** @@ -375,7 +376,7 @@ Switches to a specified subtype of a specified input method. This API uses an as | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | |inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| -|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| +|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md)| Yes| Input method subtype to switch to.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| **Error codes** @@ -391,25 +392,9 @@ For details about the error codes, see [Input Method Framework Error Codes](../e ```js let im = inputMethod.getCurrentInputMethod(); -let inputMethodProperty = { - packageName: im.packageName, - methodId: im.methodId, - name: im.packageName, - id: im.methodId, - extra: {} -} +let imSubType = inputMethod.getCurrentInputMethodSubtype(); try { - inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, { - id: "com.example.kikakeyboard", - label: "ServiceExtAbility", - name: "", - mode: "upper", - locale: "", - language: "", - icon: "", - iconId: 0, - extra: {} - }, (err,result) => { + inputMethod.switchCurrentInputMethodAndSubtype(im, imSubType, (err,result) => { if (err !== undefined) { console.error('Failed to switchCurrentInputMethodAndSubtype: ' + JSON.stringify(err)); return; @@ -440,7 +425,7 @@ Switches to a specified subtype of a specified input method. This API uses a pro | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | |inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| -|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| +|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md)| Yes| Input method subtype to switch to.| **Return value** @@ -461,25 +446,9 @@ For details about the error codes, see [Input Method Framework Error Codes](../e ```js let im = inputMethod.getCurrentInputMethod(); -let inputMethodProperty = { - packageName: im.packageName, - methodId: im.methodId, - name: im.packageName, - id: im.methodId, - extra: {} -} +let imSubType = inputMethod.getCurrentInputMethodSubtype(); try { - inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, { - id: im.packageName, - label: im.methodId, - name: "", - mode: "upper", - locale: "", - language: "", - icon: "", - iconId: 0, - extra: {} - }).then((result) => { + inputMethod.switchCurrentInputMethodAndSubtype(im, imSubType).then((result) => { if (result) { console.info('Succeeded in switching currentInputMethodAndSubtype.'); } else { @@ -886,7 +855,7 @@ inputMethodController.off('selectByRange'); on(type: 'selectByMovement', callback: Callback<Movement>): void -Enables listening for the selection-by-cursor-movement event. This API uses an asynchronous callback to return the result. +Enables listening for the select-by-cursor-movement event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -894,7 +863,7 @@ Enables listening for the selection-by-cursor-movement event. This API uses an a | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **selectByMovement** indicates the selection-by-cursor-movement event.| +| type | string | Yes | Listening type.
The value **selectByMovement** indicates the select-by-cursor-movement event.| | callback | Callback<[Movement](./js-apis-inputmethod-InputMethodCommon.md#movement)> | Yes | Callback used to return the range of the text to be selected.
Your application needs to select the text in the returned range in the text box.| **Example** @@ -909,7 +878,7 @@ inputMethodController.on('selectByMovement', (movement) => { off(type: 'selectByMovement'): void -Disables listening for the selection-by-cursor-movement event. +Disables listening for the select-by-cursor-movement event. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -917,7 +886,7 @@ Disables listening for the selection-by-cursor-movement event. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **selectByMovement** indicates the selection-by-cursor-movement event.| +| type | string | Yes | Listening type.
The value **selectByMovement** indicates the select-by-cursor-movement event.| **Example** @@ -942,7 +911,7 @@ Enables listening for the input method and subtype change event. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Listening type.
The value **'imeChange'** indicates the input method and subtype change event.| -| callback | (inputMethodProperty: [InputMethodProperty](#inputmethodproperty8), inputMethodSubtype: [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)) => void | Yes| Callback used to return the input method attributes and subtype.| +| callback | (inputMethodProperty: [InputMethodProperty](#inputmethodproperty8), inputMethodSubtype: [InputMethodSubtype](./js-apis-inputmethod-subtype.md)) => void | Yes| Callback used to return the input method attributes and subtype.| **Example** @@ -965,7 +934,7 @@ Disables listening for the input method and subtype change event. This API uses | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Listening type.
The value **'imeChange'** indicates the input method and subtype change event.| -| callback | (inputMethodProperty: [InputMethodProperty](#inputmethodproperty8), inputMethodSubtype: [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)) => void | No| Callback used to return the input method attributes and subtype.| +| callback | (inputMethodProperty: [InputMethodProperty](#inputmethodproperty8), inputMethodSubtype: [InputMethodSubtype](./js-apis-inputmethod-subtype.md)) => void | No| Callback used to return the input method attributes and subtype.| **Example** @@ -986,7 +955,7 @@ Obtains all subtypes of a specified input method. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ---------------------- | | inputMethodProperty | InputMethodProperty| Yes| Input method to which the subtypes belong.| -| callback | AsyncCallback<Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)>> | Yes| Callback used to return all subtypes of the specified input method.| +| callback | AsyncCallback<Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md)>> | Yes| Callback used to return all subtypes of the specified input method.| **Error codes** @@ -1038,7 +1007,7 @@ Obtains all subtypes of a specified input method. This API uses a promise to ret | Type | Description | | ----------------------------------------------------------- | ---------------------- | -| Promise> | Promise used to return all subtypes of the specified input method.| +| Promise> | Promise used to return all subtypes of the specified input method.| **Error codes** @@ -1082,7 +1051,7 @@ Obtains all subtypes of this input method. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ---------------------- | -| callback | AsyncCallback<Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)>> | Yes | Callback used to return all subtypes of the current input method.| +| callback | AsyncCallback<Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md)>> | Yes | Callback used to return all subtypes of the current input method.| **Error codes** @@ -1121,7 +1090,7 @@ Obtains all subtypes of this input method. This API uses a promise to return the | Type | Description | | ----------------------------------------------------------- | ---------------------- | -| Promise> | Promise used to return all subtypes of the current input method.| +| Promise> | Promise used to return all subtypes of the current input method.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index c13da820d4fb20828a2b001c54278bfe1cb82c23..a2e087795857ff8a788b72826bf64f7ec1961f82 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,6 +1,6 @@ # @ohos.inputMethodEngine (Input Method Service) -The **inputMethodEngine** module streamlines the interactions between input methods and applications. By calling APIs of this module, applications can be bound to input method services to accept text input, request the keyboard to display or hide, listen for the input method status, and much more. +The **inputMethodEngine** module is oriented to input method applications (including system and third-party input method applications). With the APIs of this module, input method applications are able to create soft keyboard windows, insert or delete characters, select text, and listen for physical keyboard events. > **NOTE** > @@ -56,15 +56,15 @@ Provides the constant values of function keys, edit boxes, and the cursor. getInputMethodAbility(): InputMethodAbility -Obtains an **InputMethodEngine** instance. +Obtains an [InputMethodAbility](#inputmethodability) instance for the input method. The input method can use the obtained instance to subscribe to a soft keyboard display/hide request event, create/destroy an input method panel, and the like. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| --------------------------------------- | ------------ | -| [InputMethodAbility](#inputmethodability) | **InputMethodEngine** instance obtained.| +| Type | Description | +| ----------------------------------------- | ------------------ | +| [InputMethodAbility](#inputmethodability) | **InputMethodAbility** instance.| **Example** @@ -76,15 +76,15 @@ let InputMethodAbility = inputMethodEngine.getInputMethodAbility(); getKeyboardDelegate(): KeyboardDelegate -Obtains a **KeyboardDelegate** instance. +Obtains a [KeyboardDelegate](#keyboarddelegate) instance for the input method. The input method can use the obtained instance to subscribe to a physical keyboard event, text selection change event, and more. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| ------------------------------------- | ---------------- | -| [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance obtained.| +| Type | Description | +| ------------------------------------- | ------------------------ | +| [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance.| **Example** @@ -96,7 +96,7 @@ let KeyboardDelegate = inputMethodEngine.getKeyboardDelegate(); getInputMethodEngine(): InputMethodEngine -Obtains an **InputMethodEngine** instance. +Obtains an [InputMethodEngine](#inputmethodengine-1) instance for the input method. The input method can use the obtained instance to subscribe to a soft keyboard display/hide request event. > **NOTE** > @@ -106,9 +106,9 @@ Obtains an **InputMethodEngine** instance. **Return value** -| Type | Description | -| --------------------------------------- | ------------ | -| [InputMethodEngine](#inputmethodengine-1) | **InputMethodEngine** instance obtained.| +| Type | Description | +| ----------------------------------------- | ------------------ | +| [InputMethodEngine](#inputmethodengine-1) | **InputMethodAbility** instance.| **Example** @@ -120,7 +120,7 @@ let InputMethodEngine = inputMethodEngine.getInputMethodEngine(); createKeyboardDelegate(): KeyboardDelegate -Obtains a **KeyboardDelegate** instance. +Obtains a [KeyboardDelegate](#keyboarddelegate) instance for the input method. The input method can use the obtained instance to subscribe to a physical keyboard event, text selection change event, and more. > **NOTE** > @@ -130,9 +130,9 @@ Obtains a **KeyboardDelegate** instance. **Return value** -| Type | Description | -| ------------------------------------- | ---------------- | -| [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance obtained.| +| Type | Description | +| ------------------------------------- | ------------------------ | +| [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance.| **Example** @@ -157,7 +157,7 @@ Enables listening for the input method binding event. This API uses an asynchron | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Listening type.
The value **'inputStart'** indicates the input method binding event.| -| callback | (kbController: [KeyboardController](#keyboardcontroller), textInputClient: [TextInputClient](#textinputclient)) => void | Yes| Callback used to return the **KeyboardController** and **TextInputClient** instances.| +| callback | (kbController: [KeyboardController](#keyboardcontroller), textInputClient: [TextInputClient](#textinputclientdeprecated)) => void | Yes| Callback used to return the **KeyboardController** and **TextInputClient** instances.| **Example** @@ -181,7 +181,7 @@ Cancels listening for the input method binding event. | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Listening type.
The value **'inputStart'** indicates the input method binding event.| -| callback | (kbController: [KeyboardController](#keyboardcontroller), textInputClient: [TextInputClient](#textinputclient)) => void | No| Callback used to return the **KeyboardController** and **TextInputClient** instances.| +| callback | (kbController: [KeyboardController](#keyboardcontroller), textInputClient: [TextInputClient](#textinputclientdeprecated)) => void | No| Callback used to return the **KeyboardController** and **TextInputClient** instances.| **Example** @@ -195,7 +195,7 @@ inputMethodEngine.getInputMethodEngine().off('inputStart', (kbController, textIn on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -Enables listening for a keyboard event. This API uses an asynchronous callback to return the result. +Enables listening for a keyboard visibility event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -221,7 +221,7 @@ inputMethodEngine.getInputMethodEngine().on('keyboardHide', () => { off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void -Disables listening for a keyboard event. This API uses an asynchronous callback to return the result. +Disables listening for a keyboard visibility event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -478,6 +478,186 @@ inputMethodEngine.getInputMethodAbility().off('setSubtype', () => { }); ``` +### createPanel10+ + +createPanel(ctx: BaseContext, info: PanelInfo, callback: AsyncCallback\): void + +Creates an input method panel. This API can be called only by input method applications and system applications with the system_core permission. Only one SOFT_KEYBOARD panel and one STATUS_BAR panel can be created for a single input method application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------- | ---- | ------------------------ | +| ctx | [BaseContext](./js-apis-inner-application-baseContext.md) | Yes | Context of the current input method.| +| info | [PanelInfo](#panelinfo10) | Yes | Information about the input method panel.| +| callback | AsyncCallback\<[Panel](#panel10)> | Yes | Callback used to return the result. If the operation is successful, the created input method panel is returned. | + +**Error codes** + +| Error Code ID | Error Message | +| ---------- | ----------------------------- | +| 12800004 | not an input method extension | + +**Example** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +try { + inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo, (err, panel) => { + if (err !== undefined) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); + return; + } + console.log('Succeed in creating panel.'); + }) +} catch(err) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +} +``` + +### createPanel10+ + +createPanel(ctx: BaseContext, info: PanelInfo): Promise\ + +Creates an input method panel. This API can be called only by input method applications and system applications with the system_core permission. Only one SOFT_KEYBOARD panel and one STATUS_BAR panel can be created for a single input method application. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------- | ---- | ------------------------ | +| ctx | [BaseContext](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md) | Yes | Context of the current input method.| +| info | [PanelInfo](#panelinfo10) | Yes | Information about the input method panel.| + +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------------ | +| Promise\<[Panel](#panel10)> | Promise used to return the result. If the operation is successful, the created input method panel is returned. | + +**Error codes** + +| Error Code ID | Error Message | +| ---------- | ----------------------------- | +| 12800004 | not an input method extension | + +**Example** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo).then((panel) => { + console.log('Succeed in creating panel.'); +}).catch((err) => { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +}) +``` + +### destroyPanel10+ + +destroyPanel(panel: Panel, callback: AsyncCallback\): void; + +Destroys an input method panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------- | ---- | ------------------------ | +| panel | [Panel](#panel10) | Yes | Input method panel to destroy.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Example** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +try { + inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo, (err, panel) => { + if (err !== undefined) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); + return; + } + globalThis.inputMethodPanel = panel; + console.log('Succeed in creating panel.'); + }) +} catch(err) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +} + +try { + inputMethodEngine.getInputMethodAbility().destroyPanel(globalThis.inputMethodPanel, (err) => { + if(err !== undefined) { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); + return; + } + console.log('Succeed in destroying panel.'); + }) +} catch(err) { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); +} +``` + +### destroyPanel10+ + +destroyPanel(panel: Panel): Promise\; + +Destroys an input method panel. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------| ----------- | ---- | ------------------------ | +| panel | [Panel](#panel10) | Yes | Input method panel to destroy. | + +**Return value** +| Type | Description | +| ------- | -------------------------------------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +try { + inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo, (err, panel) => { + if (err !== undefined) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); + return; + } + globalThis.inputMethodPanel = panel; + console.log('Succeed in creating panel.'); + }) +} catch(err) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +} + +try { + inputMethodEngine.getInputMethodAbility().destroyPanel(globalThis.inputMethodPanel).then(() => { + console.log('Succeed in destroying panel.'); + }).catch((err) => { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); + }); +} catch (err) { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); +} +``` + ## KeyboardDelegate In the following API examples, you must first use **[getKeyboardDelegate](#inputmethodenginegetkeyboarddelegate9)** to obtain a **KeyboardDelegate** instance, and then call the APIs using the obtained instance. @@ -684,6 +864,455 @@ inputMethodEngine.getKeyboardDelegate().off('textChange', (text) => { }); ``` +## Panel10+ + +In the following API examples, you must first use **[createPanel](#createpanel10)** to obtain a **Panel** instance, and then call the APIs using the obtained instance. + +### setUiContent10+ + +setUiContent(path: string, callback: AsyncCallback\): void + +Loads content from a page to this panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| path | string | Yes | Path of the page from which the content will be loaded.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +try { + panel.setUiContent('pages/page2/page2', (err) => { + if (err) { + console.error('Failed to set the content. err:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the content.'); + }); +} catch (exception) { + console.error('Failed to set the content. err:' + JSON.stringify(exception)); +} +``` + +### setUiContent10+ + +setUiContent(path: string): Promise\ + +Loads content from a page to this panel. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| path | string | Yes | Path of the page from which the content will be loaded.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +try { + let promise = panel.setUiContent('pages/page2/page2'); + promise.then(() => { + console.info('Succeeded in setting the content.'); + }).catch((err) =>{ + console.error('Failed to set the content. err: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the content. err: ' + JSON.stringify(exception)); +} +``` + +### setUiContent10+ + +setUiContent(path: string, storage: LocalStorage, callback: AsyncCallback\): void + +Loads content from a page linked to LocalStorage to this panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| path | string | Yes | Path of the page from which the content will be loaded.| +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | Storage unit that provides storage for mutable and immutable state variables in the application.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +try { + panel.setUiContent('pages/page2/page2', storage, (err) => { + if (err) { + console.error('Failed to set the content. err:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the content.'); + }); +} catch (exception) { + console.error('Failed to set the content. err:' + JSON.stringify(exception)); +} +``` + +### setUiContent10+ + +setUiContent(path: string, storage: LocalStorage): Promise\ + +Loads content from a page linked to LocalStorage to this panel. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| path | string | Yes | Path of the page from which the content will be loaded.| +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | Storage unit that provides storage for mutable and immutable state variables in the application.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +try { + let promise = panel.setUiContent('pages/page2/page2'); + promise.then(() => { + console.info('Succeeded in setting the content.'); + }).catch((err) =>{ + console.error('Failed to set the content. err: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the content. err: ' + JSON.stringify(exception)); +} +``` + +### resize10+ + +resize(width: number, height: number, callback: AsyncCallback\): void + +Resizes this panel. This API uses an asynchronous callback to return the result. +The panel width cannot exceed the screen width, and the panel height cannot be higher than half of the screen height. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| width | number | Yes | Target width of the panel, in pixels.| +| height | number | Yes | Target height of the panel, in pixels.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +try { + panel.resize(500, 1000, (err) => { + if (err) { + console.error('Failed to change the panel size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the panel size.'); + }); +} catch (exception) { + console.error('Failed to change the panel size. Cause:' + JSON.stringify(exception)); +} +``` + +### resize10+ + +resize(width: number, height: number): Promise\; + +Resizes this panel. This API uses a promise to return the result. +The panel width cannot exceed the screen width, and the panel height cannot be higher than half of the screen height. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| width | number | Yes | Target width of the panel, in pixels.| +| height | number | Yes | Target height of the panel, in pixels.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| Promise | Promise that returns no value. | + +**Example** + +```js +try { + let promise = panel.resize(500, 1000); + promise.then(() => { + console.info('Succeeded in changing the panel size.'); + }).catch((err) =>{ + console.error('Failed to change the panel size. err: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to change the panel size. err: ' + JSON.stringify(exception)); +} +``` + +### moveTo10+ + +moveTo(x: number, y: number, callback: AsyncCallback\): void + +Moves this panel to the specified position. This API uses an asynchronous callback to return the result. +This API does not work on panels in the FLG_FIXED state. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| x | number | Yes | Distance to move along the x-axis, in px. A positive value indicates moving rightwards.| +| y | number | Yes | Distance to move along the y-axis, in pixels. A positive value indicates moving downwards.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +try { + panel.moveTo(300, 300, (err) =>{ + if (err) { + console.error('Failed to move the panel. err:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the panel.'); + }); +} catch (exception) { + console.error('Failed to move the panel. err:' + JSON.stringify(exception)); +} +``` + +### moveTo10+ + +moveTo(x: number, y: number): Promise\ + +Moves this panel to the specified position. This API uses a promise to return the result. +This API does not work on panels in the FLG_FIXED state. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| x | number | Yes | Distance to move along the x-axis, in pixels. A positive value indicates moving rightwards.| +| y | number | Yes | Distance to move along the y-axis, in pixels. A positive value indicates moving downwards.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| Promise | Promise that returns no value. | + +**Example** + +```js +try { + let promise = windowClass.moveTo(300, 300); + promise.then(() => { + console.info('Succeeded in moving the panel.'); + }).catch((err) =>{ + console.error('Failed to move the panel. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to move the panel. Cause:' + JSON.stringify(exception)); +} +``` + +### show10+ + +show(callback: AsyncCallback\): void + +Displays this panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +panel.show((err) => { + if (err) { + console.error('Failed to show the panel. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the panel.'); +}); +``` + +### show10+ + +show(): Promise\ + +Displays this panel. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let promise = panel.show(); +promise.then(() => { + console.info('Succeeded in showing the panel.'); +}).catch((err) =>{ + console.error('Failed to show the panel. err: ' + JSON.stringify(err)); +}); +``` + +### hide10+ + +hide(callback: AsyncCallback\): void + +Hides this panel. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +panel.hide((err) => { + if (err) { + console.error('Failed to hide the panel. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hiding the panel.'); +}); +``` + +### hide10+ + +hide(): Promise\ + +Hides this panel. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| Promise\ | Promise that returns no value. | + +**Example** + +```js +let promise = panel.hide(); +promise.then(() => { + console.info('Succeeded in hiding the panel.'); +}).catch((err) =>{ + console.error('Failed to hide the panel. err: ' + JSON.stringify(err)); +}); +``` + +### on10+ + +on(type: 'show' | 'hide', callback: () => void): void + +Enables listening for a panel visibility event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| type | 'show'\|'hide' | Yes| Listening type.
- The value **'show'** indicates the panel display event.
- The value **'hide'** indicates the panel hiding event.| +| callback | () => void | Yes | Callback used to return the result.| + +**Example** + +```js +panel.on('show', () => { + console.info('Panel is showing.'); +}); +``` + +### off10+ + +off(type: 'show' | 'hide', callback?: () => void): void + +Disables listening for a panel visibility event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| type | 'show'/'hide' | Yes| Listening type.
- The value **'show'** indicates the panel display event.
- The value **'hide'** indicates the panel hiding event.| +| callback | () => void | No | Callback used to return the result.| + +**Example** + +```js +panel.off('show'); +``` + +### changeFlag10+ + +changeFlag(flag: PanelFlag): void + +Changes the panel state type. This API only works for SOFT_KEYBOARD panels. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| flag | [PanelFlag](#panelflag10) | Yes| State type of the panel to switch to.| + +**Example** + +```js +let panelFlag = inputMethodEngine.getInputMethodAbility().PanelFlag.FLG_FIXED; +panel.changeFlag(panelFlag); +``` + ## KeyboardController In the following API examples, you must first use **[on('inputStart')](#oninputstart9)** to obtain a **KeyboardController** instance, and then call the APIs using the obtained instance. @@ -1752,6 +2381,39 @@ Describes the attribute of a key. | keyCode | number | Yes | No | Key value.| | keyAction | number | Yes | No | Key status.| +## PanelFlag10+ + +Enumerates the state types of the input method panel. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name | Value| Description | +| ------------ | -- | ------------------ | +| FLG_FIXED | 0 | Fixed state type.| +| FLG_FLOATING | 1 | Floating state type.| + +## PanelType10+ + +Enumerates the types of the input method panel. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name | Value| Description | +| ------------ | -- | ------------------ | +| SOFT_KEYBOARD | 0 | Soft keyboard type.| +| STATUS_BAR | 1 | Status bar type.| + +## PanelInfo10+ + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +Describes the attributes of the input method panel. + +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ------------ | +| type | number | Yes | Yes | Type of the panel.| +| flag | number | Yes | Yes | State type of the panel.| + ## TextInputClient(deprecated) > **NOTE** @@ -2250,3 +2912,4 @@ textInputClient.getEditorAttribute().then((editorAttribute) => { console.error('Failed to getEditorAttribute: ' + JSON.stringify(err)); }); ``` + diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index e45395f5ed1b4c15a1aa77c1a651a884b40f0b21..fc1fe9ef77b77ef0eaae619f5c0f630b39a6bb40 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -3,7 +3,7 @@ The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. > **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. ## Modules to Import @@ -150,6 +150,64 @@ try { console.error('getBundleInstaller failed. Cause: ' + error.message); } ``` +## BundleInstaller.install +install(hapFilePaths: Array<string>, callback: AsyncCallback<void>): void; + +Installs a bundle. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| hapFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700010 | Failed to install the HAP because the HAP fails to be parsed. | +| 17700011 | Failed to install the HAP because the HAP signature fails to be verified. | +| 17700012 | Failed to install the HAP because the HAP path is invalid or the HAP is too large. | +| 17700015 | Failed to install the HAPs because they have different configuration information. | +| 17700016 | Failed to install the HAP because of insufficient system disk space. | +| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. | +| 17700018 | Failed to install because the dependent module does not exist. | +| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. | +| 17700036 | Failed to install the HSP because lacks appropriate permissions. | +| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | +| 17700041 | Failed to install because enterprise device management disallow install. | + +**Example** + +```ts +import installer from '@ohos.bundle.installer'; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; + +try { + installer.getBundleInstaller().then(data => { + data.install(hapFilePaths, err => { + if (err) { + console.error('install failed:' + err.message); + } else { + console.info('install successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` ## BundleInstaller.install @@ -210,9 +268,9 @@ try { installer.getBundleInstaller().then(data => { data.install(hapFilePaths, installParam) .then((data) => { - console.info('install success: ' + JSON.stringify(data)); + console.info('install successfully: ' + JSON.stringify(data)); }).catch((error) => { - console.error('install failed:' + err.message); + console.error('install failed:' + error.message); }); }).catch(error => { console.error('getBundleInstaller failed. Cause: ' + error.message); @@ -248,7 +306,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700004 | The specified user ID is not found. | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | @@ -280,11 +339,11 @@ try { } ``` -## BundleInstaller.uninstall10+ +## BundleInstaller.uninstall -uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : void ; +uninstall(bundleName: string, callback: AsyncCallback<void>): void; -Uninstalls a shared bundle. This API uses an asynchronous callback to return the result. +Uninstalls a bundle. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -294,10 +353,10 @@ Uninstalls a shared bundle. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| uninstallParam | [UninstallParam](#uninstallparam10) | Yes | Parameters required for the uninstall. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Name of the target bundle. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| **Error codes** @@ -305,21 +364,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundle name is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | -| 17700037 | The version of shared bundle is dependent on other applications. | -| 17700038 | The specified shared bundle does not exist. | +| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | **Example** ```ts import installer from '@ohos.bundle.installer'; -let uninstallParam = { - bundleName : "com.ohos.demo", -}; +let bundleName = 'com.ohos.demo'; try { installer.getBundleInstaller().then(data => { - data.uninstall(uninstallParam, err => { + data.uninstall(bundleName, err => { if (err) { console.error('uninstall failed:' + err.message); } else { @@ -333,12 +390,11 @@ try { console.error('getBundleInstaller failed. Cause: ' + error.message); } ``` +## BundleInstaller.uninstall -## BundleInstaller.uninstall10+ - -uninstall(uninstallParam: UninstallParam) : Promise\; +uninstall(bundleName: string, installParam?: InstallParam) : Promise\; -Uninstalls a shared bundle. This API uses a promise to return the result. +Uninstalls a bundle. This API uses a promise to return the result. **System API**: This is a system API. @@ -348,14 +404,15 @@ Uninstalls a shared bundle. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ----------------------------------- | ---- | ---------------------------- | -| uninstallParam | [UninstallParam](#uninstallparam10) | Yes | Parameters required for the uninstall.| +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Name of the target bundle. | +| installParam | [InstallParam](#installparam) | No | Parameters required for the uninstall. | **Return value** -| Type | Description | -| ------------- | -------------------------------------- | +| Type | Description | +| --------------- | -------------------------------------- | | Promise\ | Promise that returns no value.| **Error codes** @@ -364,26 +421,28 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified userId is not existed. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | -| 17700037 | The version of shared bundle is dependent on other applications. | -| 17700038 | The specified shared bundle does not exist. | +| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | **Example** - ```ts import installer from '@ohos.bundle.installer'; -let uninstallParam = { - bundleName : "com.ohos.demo", +let bundleName = 'com.ohos.demo'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, }; try { installer.getBundleInstaller().then(data => { - data.uninstall(uninstallParam, err => { - if (err) { - console.error('uninstall failed:' + err.message); - } else { - console.info('uninstall successfully.'); - } + data.uninstall(bundleName, installParam) + .then((data) => { + console.info('uninstall successfully: ' + JSON.stringify(data)); + }).catch((error) => { + console.error('uninstall failed:' + error.message); }); }).catch(error => { console.error('getBundleInstaller failed. Cause: ' + error.message); @@ -397,7 +456,7 @@ try { recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback<void>): void; -Recovers a bundle. This API uses an asynchronous callback to return the result. +Rolls back a bundle to the initial installation state. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -410,7 +469,7 @@ Recovers a bundle. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Name of the target bundle. | -| installParam | [InstallParam](#installparam) | Yes | Parameters required for the recovering. | +| installParam | [InstallParam](#installparam) | Yes | Parameters required for the recovery. | | callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| **Error codes** @@ -419,6 +478,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ----------------------------------- | +| 17700001 | The specified bundle name is not found. | | 17700004 | The specified user ID is not found. | **Example** @@ -449,6 +509,229 @@ try { } ``` + +## BundleInstaller.recover + +recover(bundleName: string, callback: AsyncCallback<void>): void; + +Rolls back a bundle to the initial installation state. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Name of the target bundle. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 17700001 | The specified bundle name is not found. | + +**Example** + +```ts +import installer from '@ohos.bundle.installer'; +let bundleName = 'com.ohos.demo'; + +try { + installer.getBundleInstaller().then(data => { + data.recover(bundleName, err => { + if (err) { + console.error('recover failed:' + err.message); + } else { + console.info('recover successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.recover + +recover(bundleName: string, installParam?: InstallParam) : Promise\; + +Rolls back a bundle to the initial installation state. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Name of the target bundle. | +| installParam | [InstallParam](#installparam) | No | Parameters required for the recovery. | + +**Return value** + +| Type | Description | +| --------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user ID is not found. | + +**Example** +```ts +import installer from '@ohos.bundle.installer'; +let bundleName = 'com.ohos.demo'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +try { + installer.getBundleInstaller().then(data => { + data.recover(bundleName, installParam) + .then((data) => { + console.info('recover successfully: ' + JSON.stringify(data)); + }).catch((error) => { + console.error('recover failed:' + error.message); + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.uninstall10+ + +uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : void ; + +Uninstalls a shared bundle. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| uninstallParam | [UninstallParam](#uninstallparam10) | Yes | Parameters required for the uninstall. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is undefined; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | +| 17700037 | The version of shared bundle is dependent on other applications. | +| 17700038 | The specified shared bundle does not exist. | + +**Example** + +```ts +import installer from '@ohos.bundle.installer'; +let uninstallParam = { + bundleName : "com.ohos.demo", +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(uninstallParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.uninstall10+ + +uninstall(uninstallParam: UninstallParam) : Promise\; + +Uninstalls a shared bundle. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| uninstallParam | [UninstallParam](#uninstallparam10) | Yes | Parameters required for the uninstall.| + +**Return value** + +| Type | Description | +| ------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | +| 17700037 | The version of shared bundle is dependent on other applications. | +| 17700038 | The specified shared bundle does not exist. | + +**Example** + +```ts +import installer from '@ohos.bundle.installer'; +let uninstallParam = { + bundleName : "com.ohos.demo", +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(uninstallParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` ## HashParam Defines the hash parameters for bundle installation and uninstall. @@ -477,7 +760,7 @@ Defines the parameters that need to be specified for bundle installation, uninst | isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall.| | hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. | | crowdtestDeadline| number | No |End date of crowdtesting.| -| sharedBundleDirPaths | Array\ | No|Paths of the shared bundle files.| +| sharedBundleDirPaths10+ | Array\ | No|Paths of the shared bundle files.| ## UninstallParam10+ diff --git a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md index 3180bf582281372886331d6d37ff059cad79e1db..74b5cf879abb768bf4abc5f07d0bdb4c4cbc571b 100644 --- a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -29,7 +29,7 @@ Obtains the launcher ability information based on the given bundle name and user | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| | userId | number | Yes | User ID.| **Return value** @@ -45,7 +45,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------- | | 17700001 | The specified bundle name is not found. | -| 17700004 | The specified userId is not found. | +| 17700004 | The specified user ID is not found. | **Example** @@ -55,12 +55,13 @@ import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; try { launcherBundleManager.getLauncherAbilityInfo('com.example.demo', 100, (errData, data) => { if (errData !== null) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); + } else { + console.log("data is " + JSON.stringify(data)); } - console.log("data is " + JSON.stringify(data)); }) } catch (errData) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -80,7 +81,7 @@ Obtains the launcher ability information based on the given bundle name and user | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| | userId | number | Yes | User ID.| **Return value** @@ -96,7 +97,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------- | | 17700001 | The specified bundle name is not found. | -| 17700004 | The specified userId is not found. | +| 17700004 | The specified user ID is not found. | **Example** @@ -107,10 +108,10 @@ try { launcherBundleManager.getLauncherAbilityInfo("com.example.demo", 100).then(data => { console.log("data is " + JSON.stringify(data)); }).catch (errData => { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); }) } catch (errData) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -144,7 +145,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------- | -| 17700004 | The specified userId is not found. | +| 17700004 | The specified user ID is not found. | Example @@ -154,12 +155,13 @@ import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; try { launcherBundleManager.getAllLauncherAbilityInfo(100, (errData, data) => { if (errData !== null) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); + } else { + console.log("data is " + JSON.stringify(data)); } - console.log("data is " + JSON.stringify(data)); }); } catch (errData) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` ## launcherBundlemanager.getAllLauncherAbilityInfo9+ @@ -192,7 +194,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------- | -| 17700004 | The specified userId is not found. | +| 17700004 | The specified user ID is not found. | **Example** @@ -203,10 +205,10 @@ try { launcherBundleManager.getAllLauncherAbilityInfo(100).then(data => { console.log("data is " + JSON.stringify(data)); }).catch (errData => { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); }); } catch (errData) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -224,7 +226,7 @@ Obtains the shortcut information of the current user based on the given bundle n | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** @@ -248,12 +250,13 @@ import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; try { launcherBundleManager.getShortcutInfo("com.example.demo", (errData, data) => { if (errData !== null) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); + } else { + console.log("data is " + JSON.stringify(data)); } - console.log("data is " + JSON.stringify(data)); }); } catch (errData) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -271,7 +274,7 @@ Obtains the shortcut information of the current user based on the given bundle n | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** @@ -296,9 +299,9 @@ try { launcherBundleManager.getShortcutInfo("com.example.demo").then(data => { console.log("data is " + JSON.stringify(data)); }).catch (errData => { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); }); } catch (errData) { - console.log(`errData is errCode:${errData.code} message:${errData.message}`); + console.error(`errData is errCode:${errData.code} message:${errData.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-net-mdns.md b/en/application-dev/reference/apis/js-apis-net-mdns.md index b2e157c03a7afec840f4af21aa729f3c081e540a..2f32a68fea2b56a3acd4458f09ebff0102bcbc16 100644 --- a/en/application-dev/reference/apis/js-apis-net-mdns.md +++ b/en/application-dev/reference/apis/js-apis-net-mdns.md @@ -399,7 +399,7 @@ discoveryService.stopSearchingMDNS(); ### on('discoveryStart') -on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MDNS_ERR}>): void +on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void Enables listening for **discoveryStart** events. @@ -410,7 +410,7 @@ Enables listening for **discoveryStart** events. | Name | Type | Mandatory| Description | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | Yes |Event type. This field has a fixed value of **discoveryStart**.
**discoveryStart**: event of starting discovery of mDNS services on the LAN.| -| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MDNS_ERR](#mdns_err)}> | Yes | Callback used to return the mDNS service and error information. | +| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | Yes | Callback used to return the mDNS service and error information. | **Example** @@ -428,7 +428,7 @@ discoveryService.stopSearchingMDNS(); ### on('discoveryStop') -on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MDNS_ERR}>): void +on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void Enables listening for **discoveryStop** events. @@ -439,7 +439,7 @@ Enables listening for **discoveryStop** events. | Name | Type | Mandatory| Description | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | Yes |Event type. This field has a fixed value of **discoveryStop**.
**discoveryStop**: event of stopping discovery of mDNS services on the LAN.| -| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MDNS_ERR](#mdns_err)}> | Yes | Callback used to return the mDNS service and error information. | +| callback | Callback<{serviceInfo: [LocalServiceInfo](#localserviceinfo), errorCode?: [MdnsError](#mdnserror)}> | Yes | Callback used to return the mDNS service and error information. | **Example** @@ -538,7 +538,7 @@ Defines the mDNS service attribute information. | key | string | Yes| mDNS service attribute key. The value contains a maximum of 9 characters. | | value | Array\ | Yes| mDNS service attribute value. | -## MDNS_ERR +## MdnsError Defines the mDNS error information. diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index 9fede96b4b9bce626e63d715b34113ab8451bf61..4c55691b61cd60cb59543ae0881a719d5bb8fc1b 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -66,7 +66,7 @@ Opens NFC. ## controller.enableNfc9+ -enableNfc(): boolean +enableNfc(): void Enables NFC. @@ -104,7 +104,7 @@ Closes NFC. ## controller.disableNfc9+ -disableNfc(): boolean +disableNfc(): void Disables NFC. diff --git a/en/application-dev/reference/apis/js-apis-overlay.md b/en/application-dev/reference/apis/js-apis-overlay.md index 1542953d78f5f09b01cbbe795c02e4170a195ef3..30c46bad02c997e7915e5595a6308446a2f5d722 100644 --- a/en/application-dev/reference/apis/js-apis-overlay.md +++ b/en/application-dev/reference/apis/js-apis-overlay.md @@ -239,7 +239,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | | 17700002 | The specified module name is not found. | -| 17700032 | he specified bundle does not contain any overlay module. | +| 17700032 | The specified bundle does not contain any overlay module. | | 17700033 | The specified module is not an overlay module. | **Example** @@ -415,7 +415,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700001 | The specified bundleName is not found | +| 17700001 | The specified bundleName is not found. | | 17700002 | The specified module name is not found. | | 17700032 | The specified bundle does not contain any overlay module. | | 17700033 | The specified module is not an overlay module. | @@ -462,7 +462,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700001 | The specified bundleName is not found | +| 17700001 | The specified bundleName is not found. | | 17700002 | The specified module name is not found. | | 17700032 | The specified bundle does not contain any overlay module. | | 17700033 | The specified module is not an overlay module. | @@ -511,7 +511,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700001 | The specified bundleName is not found | +| 17700001 | The specified bundleName is not found. | | 17700002 | The specified module name is not found. | | 17700032 | The specified bundle does not contain any overlay module. | | 17700033 | The specified module is not an overlay module. | @@ -557,7 +557,7 @@ Obtains the information about modules with the overlay feature in another applic | Type | Description | | ------------------------- | ------------------ | -| Promise\> | Promise used to return the array of overlay module information obtained.| +| Promise\> | Promise used to return the result, which is an array of **OverlayModuleInfo** objects.| **Error codes** @@ -565,7 +565,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700001 | The specified bundleName is not found | +| 17700001 | The specified bundleName is not found. | | 17700002 | The specified module name is not found. | | 17700034 | The specified module is an overlay module. | | 17700035 | The specified bundle is an overlay bundle. | @@ -612,7 +612,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700001 | The specified bundleName is not found | +| 17700001 | The specified bundleName is not found. | | 17700002 | The specified module name is not found. | | 17700034 | The specified module is an overlay module. | | 17700035 | The specified bundle is an overlay bundle. | @@ -661,7 +661,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700001 | The specified bundleName is not found | +| 17700001 | The specified bundleName is not found. | | 17700002 | The specified module name is not found. | | 17700034 | The specified module is an overlay module. | | 17700035 | The specified bundle is an overlay bundle. | diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index cc24c7ab23912cb3abb8f2ee648c0be026565aac..0cd8b2df9f10074df34a7405be624953b7feb233 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -13,7 +13,7 @@ The Resource Manager module provides APIs to obtain information about applicatio import resourceManager from '@ohos.resourceManager'; ``` -## Instruction +## How to Use Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object. For details about how to reference context in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). @@ -78,7 +78,7 @@ Obtains the **ResourceManager** object of an application based on the specified | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of the target application. | | callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.| **Example** @@ -135,7 +135,7 @@ Obtains the **ResourceManager** object of an application based on the specified | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name of the target application.| **Return value** @@ -171,12 +171,12 @@ Enumerates the device types. | Name | Value | Description | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | Phone | -| DEVICE_TYPE_TABLET | 0x01 | Tablet | -| DEVICE_TYPE_CAR | 0x02 | Head unit | -| DEVICE_TYPE_PC | 0x03 | PC | -| DEVICE_TYPE_TV | 0x04 | TV | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable | +| DEVICE_TYPE_PHONE | 0x00 | Phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Head unit. | +| DEVICE_TYPE_PC | 0x03 | PC. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -278,7 +278,7 @@ Defines the capability of accessing application resources. > **NOTE** > -> - The APIs involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. +> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. > > - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**. @@ -645,7 +645,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -1543,7 +1543,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ``` -### closeRawFd8+ +### closeRawFd9+ closeRawFd(path: string): Promise<void> @@ -1658,7 +1658,7 @@ Obtains the string corresponding to the specified resource name. This API uses a | Type | Description | | --------------------- | ---------- | -| Promise<string> | String corresponding to the resource name.| +| Promise<string> | Promise used to return the result.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -1770,7 +1770,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -2036,7 +2036,7 @@ Obtains the string corresponding to the specified resource ID. This API returns | Type | Description | | ------ | ----------- | -| string | Promise used to return the result.| +| string | String corresponding to the specified resource ID.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2057,6 +2057,47 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getStringSync10+ + +getStringSync(resId: number, ...args: Array): string + +Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: %% is used to translate %.
Example: %%d is translated into the %d string.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +**Error codes** + +| ID| Error Message| +| -------- | ----------------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | +| 9001007 | If the resource obtained by resId formatting error. | + +**Example** + ```ts + try { + this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78); + } catch (error) { + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getStringSync9+ getStringSync(resource: Resource): string @@ -2075,7 +2116,7 @@ Obtains the string corresponding to the specified resource object. This API retu | Type | Description | | ------ | ---------------- | -| string | Promise used to return the result.| +| string | String corresponding to the resource object.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2101,6 +2142,52 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getStringSync10+ + +getStringSync(resource: Resource, ...args: Array): string + +Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: %% is used to translate %.
Example: %%d is translated into the %d string.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +**Error codes** + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | +| 9001007 | If the resource obtained by resId formatting error. | + +**Example** + ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.string.test').id + }; + try { + this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78); + } catch (error) { + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getStringByNameSync9+ getStringByNameSync(resName: string): string @@ -2119,7 +2206,7 @@ Obtains the string corresponding to the specified resource name. This API return | Type | Description | | ------ | ---------- | -| string | String corresponding to the specified resource name.| +| string | String corresponding to the resource name.| For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). @@ -2140,6 +2227,47 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` +### getStringByNameSync10+ + +getStringByNameSync(resName: string, ...args: Array): string + +Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: %% is used to translate %.
Example: %%d is translated into the %d string.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +**Error codes** + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | +| 9001008 | If the resource obtained by resName formatting error. | + +**Example** + ```ts + try { + this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78); + } catch (error) { + console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`) + } + ``` + ### getBoolean9+ getBoolean(resId: number): boolean @@ -2399,7 +2527,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor; -Obtains the **DrawableDescriptor** object based on the specified resource ID. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2443,7 +2571,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; -Obtains the **DrawableDescriptor** object based on the specified resource. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2492,7 +2620,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor; -Obtains the **DrawableDescriptor** object based on the specified resource name. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2666,7 +2794,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead. diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index 9235dace79f11592adb3d84fbde631c33ec21780..e8a2ba6886ea9f74252e56a62136e1b6b909c72b 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -183,8 +183,6 @@ Checks whether the tag is connected. > **NOTE** > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.isConnected](#tagsessionisconnected9). -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -211,8 +209,6 @@ isConnected(): boolean Checks whether the tag is connected. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Tag **Return value** diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md deleted file mode 100644 index 49bb9b53a08027852baa2614975e6ec9f53d90e9..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ /dev/null @@ -1,952 +0,0 @@ -# @ohos.usbV9 (USB) - -The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. - -> **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 provided by this module are no longer maintained since API version 9. You are advised to use [`@ohos.usbManager`](js-apis-usbManager.md). - -## Modules to Import - -```js -import usb from "@ohos.usbV9"; -``` - -## usb.getDevices - -getDevices(): Array<Readonly<USBDevice>> - -Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. - -**System capability**: SystemCapability.USB.USBManager - -**Return value** - -| Type | Description | -| ---------------------------------------------------- | ------- | -| Array<Readonly<[USBDevice](#usbdevice)>> | USB device list.| - -**Example** - -```js -let devicesList = usb.getDevices(); -console.log(`devicesList = ${devicesList}`); -// devicesList is a list of USB devices. -// A simple example of devicesList is provided as follows: -[ - { - name: "1-1", - serial: "", - manufacturerName: "", - productName: "", - version: "", - vendorId: 7531, - productId: 2, - clazz: 9, - subClass: 0, - protocol: 1, - devAddress: 1, - busNum: 1, - configs: [ - { - id: 1, - attributes: 224, - isRemoteWakeup: true, - isSelfPowered: true, - maxPower: 0, - name: "1-1", - interfaces: [ - { - id: 0, - protocol: 0, - clazz: 9, - subClass: 0, - alternateSetting: 0, - name: "1-1", - endpoints: [ - { - address: 129, - attributes: 3, - interval: 12, - maxPacketSize: 4, - direction: 128, - number: 1, - type: 3, - interfaceId: 0, - }, - ], - }, - ], - }, - ], - }, -] -``` - -## usb.connectDevice - -connectDevice(device: USBDevice): Readonly<USBDevicePipe> - -Connects to the USB device based on the device information returned by **getDevices()**. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | [USBDevice](#usbdevice) | Yes| USB device information.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Readonly<[USBDevicePipe](#usbdevicepipe)> | USB device pipe for data transfer.| - -**Error codes** - -For details about the error codes, see [USB Error Codes](../errorcodes/errorcode-usb.md). - -| ID| Error Message| -| -------- | -------- | -| 14400001 |Permission denied. Need call requestRight to get permission. | - -**Example** - -```js -let devicesList = usb.getDevices(); -if (devicesList.length == 0) { - console.log(`device list is empty`); -} - -let device = devicesList[0]; -usb.requestRight(device.name); -let devicepipe = usb.connectDevice(device); -console.log(`devicepipe = ${devicepipe}`); -``` - -## usb.hasRight - -hasRight(deviceName: string): boolean - -Checks whether the application has the permission to access the device. - -Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Yes| Device name.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise.| - -**Example** - -```js -let devicesName="1-1"; -let bool = usb.hasRight(devicesName); -console.log(bool); -``` - -## usb.requestRight - -requestRight(deviceName: string): Promise<boolean> - -Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Yes| Device name.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite.| - -**Example** - -```js -let devicesName="1-1"; -usb.requestRight(devicesName).then((ret) => { - console.log(`requestRight = ${ret}`); -}); -``` - -## usb.removeRight - -removeRight(deviceName: string): boolean - -Removes the permission for the application to access a USB device. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Yes| Device name.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite.| - -**Example** - -```js -let devicesName="1-1"; -if usb.removeRight(devicesName) { - console.log(`Succeed in removing right`); -} -``` - -## usb.addRight - -addRight(bundleName: string, deviceName: string): boolean - -Adds the permission for the application to access a USB device. - -[requestRight](#usbrequestright) triggers a dialog box to request for user authorization, whereas **addRight** adds the access permission directly without displaying a dialog box. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Yes| Device name.| -| bundleName | string | Yes| Bundle name of the application.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.| - -**Example** - -```js -let devicesName = "1-1"; -let bundleName = "com.example.hello"; -if usb.addRight(bundleName, devicesName) { - console.log(`Succeed in adding right`); -} -``` - -## usb.claimInterface - -claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number - -Claims a USB interface. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and USB interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| -| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to claim.| -| force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise.| - -**Example** - -```js -let ret = usb.claimInterface(devicepipe, interfaces); -console.log(`claimInterface = ${ret}`); -``` - -## usb.releaseInterface - -releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number - -Releases a USB interface. - -Before you do this, ensure that you have claimed the interface by calling [usb.claimInterface](#usbclaiminterface). - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| -| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise.| - -**Example** - -```js -let ret = usb.releaseInterface(devicepipe, interfaces); -console.log(`releaseInterface = ${ret}`); -``` - -## usb.setConfiguration - -setConfiguration(pipe: USBDevicePipe, config: USBConfig): number - -Sets the device configuration. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device configuration, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| -| config | [USBConfig](#usbconfig) | Yes| USB configuration to set.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise.| - -**Example** - -```js -let ret = usb.setConfiguration(devicepipe, config); -console.log(`setConfiguration = ${ret}`); -``` - -## usb.setInterface - -setInterface(pipe: USBDevicePipe, iface: USBInterface): number - -Sets a USB interface. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----- | ------------------------------- | --- | ------------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes | Device pipe, which is used to determine the bus number and device address.| -| iface | [USBInterface](#usbinterface) | Yes | USB interface to set. | - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise.| - -**Example** - -```js -let ret = usb.setInterface(devicepipe, interfaces); -console.log(`setInterface = ${ret}`); -``` - -## usb.getRawDescriptor - -getRawDescriptor(pipe: USBDevicePipe): Uint8Array - -Obtains the raw USB descriptor. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.| - -**Example** - -```js -let ret = usb.getRawDescriptor(devicepipe); -``` - -## usb.getFileDescriptor - -getFileDescriptor(pipe: USBDevicePipe): number - -Obtains the file descriptor. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| - -**Return value** - -| Type | Description | -| ------ | -------------------- | -| number | Returns the file descriptor of the USB device if the operation is successful; returns **-1** otherwise.| - -**Example** - -```js -let ret = usb.getFileDescriptor(devicepipe); -``` - -## usb.controlTransfer - -controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise<number> - -Performs control transfer. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| -| controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| -| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.| - -**Example** - -```js -let param = new usb.USBControlParams(); -usb.controlTransfer(devicepipe, param).then((ret) => { - console.log(`controlTransfer = ${ret}`); -}) -``` - -## usb.bulkTransfer - -bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> - -Performs bulk transfer. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| -| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB port for data transfer.| -| buffer | Uint8Array | Yes| Buffer for writing or reading data.| -| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.| - -**Example** - -```js -// Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission. -// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. -// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. -usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { - console.log(`bulkTransfer = ${ret}`); -}); -``` - -## usb.closePipe - -closePipe(pipe: USBDevicePipe): number - -Closes a USB device pipe. - -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise.| - -**Example** - -```js -let ret = usb.closePipe(devicepipe); -console.log(`closePipe = ${ret}`); -``` - -## usb.usbFunctionsFromString - -usbFunctionsFromString(funcs: string): number - -Converts the USB function list in the string format to a numeric mask in Device mode. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| funcs | string | Yes | Function list in string format.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Function list in numeric mask format.| - -**Example** - -```js -let funcs = "acm"; -let ret = usb.usbFunctionsFromString(funcs); -``` - -## usb.usbFunctionsToString - -usbFunctionsToString(funcs: FunctionType): string - -Converts the USB function list in the numeric mask format to a string in Device mode. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ----------------- | -| funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| - -**Return value** - -| Type | Description | -| ------ | ------------------------------ | -| string | Function list in string format.| - -**Example** - -```js -let funcs = usb.ACM | usb.ECM; -let ret = usb.usbFunctionsToString(funcs); -``` - -## usb.setCurrentFunctions - -setCurrentFunctions(funcs: FunctionType): Promise\ - -Sets the current USB function list in Device mode. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ----------------- | -| funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| - -**Return value** - -| Type | Description | -| --------------- | ------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -let funcs = usb.HDC; -usb.setCurrentFunctions(funcs).then(() => { - console.info('usb setCurrentFunctions successfully.'); -}).catch(err => { - console.error('usb setCurrentFunctions failed: ' + err.code + ' message: ' + err.message); -}); -``` - -## usb.getCurrentFunctions - -getCurrentFunctions(): FunctionType - -Obtains the numeric mask combination for the USB function list in Device mode. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Return value** - -| Type | Description | -| ------------------------------ | --------------------------------- | -| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.| - -**Example** - -```js -let ret = usb.getCurrentFunctions(); -``` - -## usb.getPorts - -getPorts(): Array\ - -Obtains the list of all physical USB ports. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Return value** - -| Type | Description | -| ----------------------------- | --------------------- | -| [Array\](#usbport) | List of physical USB ports.| - -**Example** - -```js -let ret = usb.getPorts(); -``` - -## usb.getSupportedModes - -getSupportedModes(portId: number): PortModeType - -Obtains the mask combination for the supported mode list of a given USB port. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------- | -| portId | number | Yes | Port number.| - -**Return value** - -| Type | Description | -| ------------------------------ | -------------------------- | -| [PortModeType](#portmodetype) | Mask combination for the supported mode list.| - -**Example** - -```js -let ret = usb.getSupportedModes(0); -``` - -## usb.setPortRoles - -setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ - -Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer). - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | -------------------------------- | ---- | ---------------- | -| portId | number | Yes | Port number. | -| powerRole | [PowerRoleType](#powerroletype) | Yes | Role for charging. | -| dataRole | [DataRoleType](#dataroletype) | Yes | Role for data transfer.| - -**Return value** - -| Type | Description | -| --------------- | ------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -let portId = 1; -usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { - console.info('usb setPortRoles successfully.'); -}).catch(err => { - console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); -}); -``` - -## USBEndpoint - -Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface). - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| ------------- | ------------------------------------------- | ------------- |------------- | -| address | number | Yes|Endpoint address. | -| attributes | number | Yes|Endpoint attributes. | -| interval | number | Yes|Endpoint interval. | -| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. | -| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. | -| number | number | Yes|Endpoint number. | -| type | number | Yes|Endpoint type. | -| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.| - -## USBInterface - -Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **USBInterface** instances, each providing a specific function. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| ---------------- | ---------------------------------------- | ------------- |--------------------- | -| id | number | Yes|Unique ID of the USB interface. | -| protocol | number | Yes|Interface protocol. | -| clazz | number | Yes|Device type. | -| subClass | number | Yes|Device subclass. | -| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.| -| name | string | Yes|Interface name. | -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes|Endpoints that belong to the USB interface. | - -## USBConfig - -Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| -------------- | ------------------------------------------------ | --------------- |--------------- | -| id | number | Yes|Unique ID of the USB configuration. | -| attributes | number | Yes|Configuration attributes. | -| maxPower | number | Yes|Maximum power consumption, in mA. | -| name | string | Yes|Configuration name, which can be left empty. | -| isRemoteWakeup | boolean | Yes|Support for remote wakeup.| -| isSelfPowered | boolean | Yes| Support for independent power supplies.| -| interfaces | Array <[USBInterface](#usbinterface)> | Yes|Supported interface attributes. | - -## USBDevice - -Represents the USB device information. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| ---------------- | ------------------------------------ | ---------- |---------- | -| busNum | number | Yes|Bus address. | -| devAddress | number | Yes|Device address. | -| serial | string | Yes|Sequence number. | -| name | string | Yes|Device name. | -| manufacturerName | string | Yes| Device manufacturer. | -| productName | string | Yes|Product name. | -| version | string | Yes|Version number. | -| vendorId | number | Yes|Vendor ID. | -| productId | number | Yes|Product ID. | -| clazz | number | Yes|Device class. | -| subClass | number | Yes|Device subclass. | -| protocol | number | Yes|Device protocol code. | -| configs | Array<[USBConfig](#usbconfig)> | Yes|Device configuration descriptor information.| - -## USBDevicePipe - -Represents a USB device pipe, which is used to determine a USB device. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| ---------- | ------ | ----- |----- | -| busNum | number |Yes| Bus address.| -| devAddress | number |Yes| Device address.| - -## USBControlParams - -Represents control transfer parameters. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| ------- | ----------------------------------------------- | ---------------- |---------------- | -| request | number | Yes |Request type. | -| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. | -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. | -| value | number | Yes |Request parameter value. | -| index | number | Yes |Index of the request parameter value.| -| data | Uint8Array | Yes |Buffer for writing or reading data. | - -## USBPort - -Represents a USB port. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type | Mandatory |Description | -| -------------- | ------------------------------- | ------------------- |------------------------ | -| id | number | Yes |Unique identifier of a USB port. | -| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.| -| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. | - -## USBPortStatus - -Enumerates USB port roles. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Type| Mandatory |Description | -| ---------------- | -------- | ---------------- |---------------------- | -| currentMode | number | Yes|Current USB mode. | -| currentPowerRole | number | Yes |Current power role. | -| currentDataRole | number | Yes |Current data role.| - -## USBRequestTargetType - -Enumerates request target types. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| ---------------------------- | ---- | ------ | -| USB_REQUEST_TARGET_DEVICE | 0 | Device| -| USB_REQUEST_TARGET_INTERFACE | 1 | Interface| -| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint| -| USB_REQUEST_TARGET_OTHER | 3 | Other| - -## USBControlRequestType - -Enumerates control request types. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| ------------------------- | ---- | ------ | -| USB_REQUEST_TYPE_STANDARD | 0 | Standard| -| USB_REQUEST_TYPE_CLASS | 1 | Class | -| USB_REQUEST_TYPE_VENDOR | 2 | Vendor| - -## USBRequestDirection - -Enumerates request directions. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| --------------------------- | ---- | ------------------------ | -| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.| -| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.| - -## FunctionType - -Enumerates USB device function types. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| ------------ | ---- | ---------- | -| NONE | 0 | No function.| -| ACM | 1 | ACM function. | -| ECM | 2 | ECM function. | -| HDC | 4 | HDC function. | -| MTP | 8 | Not supported currently.| -| PTP | 16 | Not supported currently.| -| RNDIS | 32 | Not supported currently.| -| MIDI | 64 | Not supported currently.| -| AUDIO_SOURCE | 128 | Not supported currently.| -| NCM | 256 | Not supported currently.| - -## PortModeType - -Enumerates USB port mode types. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| --------- | ---- | ---------------------------------------------------- | -| NONE | 0 | None. | -| UFP | 1 | Upstream facing port, which functions as the sink of power supply. | -| DFP | 2 | Downstream facing port, which functions as the source of power supply. | -| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.| -| NUM_MODES | 4 | Not supported currently. | - -## PowerRoleType - -Enumerates power role types. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| ------ | ---- | ---------- | -| NONE | 0 | None. | -| SOURCE | 1 | External power supply.| -| SINK | 2 | Internal power supply.| - -## DataRoleType - -Enumerates data role types. - -**System API**: This is a system API. - -**System capability**: SystemCapability.USB.USBManager - -| Name | Value | Description | -| ------ | ---- | ------------ | -| NONE | 0 | None. | -| HOST | 1 | USB host.| -| DEVICE | 2 | USB device.| diff --git a/en/application-dev/reference/arkui-ts/figures/coordinates.png b/en/application-dev/reference/arkui-ts/figures/coordinates.png new file mode 100644 index 0000000000000000000000000000000000000000..839f765b9f62dd9efcf1d2ee891a191c9a5ba053 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/coordinates.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/progressMask.PNG b/en/application-dev/reference/arkui-ts/figures/progressMask.PNG new file mode 100644 index 0000000000000000000000000000000000000000..fac3dda28c11979572ff69ed3005be5d40e62b3b Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/progressMask.PNG differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md index 7bb73dc7db50b38fee5e68bd44a254291d27a8fc..b2ab19b168a0415f8ddd82cee4a41faa3282848d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkbox.md @@ -21,7 +21,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type| Mandatory | Description| | --------| --------| ------ | -------- | | name | string | No| Name of the check box.| -| group | string | No| Group name of the check box.| +| group | string | No| Group name of the check box.
**NOTE**
If not used with the **\** component, this parameter is invalid.| ## Attributes @@ -32,6 +32,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | ------------- | ------- | -------- | | select | boolean | Whether the check box is selected.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the check box when it is selected.
Since API version 9, this API is supported in ArkTS widgets.| +| unselectedColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Border color of the check box when it is not selected.| +| mark10+ | [MarkStyle](#markstyle10) | Internal icon style of the check box.| ## Events @@ -41,6 +43,14 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | -------------------------------------------- | ------------------------------------------------------------ | | onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes due to a manual operation.
- The value **true** means that the check box is selected.
- The value **false** means that the check box is not selected.
Since API version 9, this API is supported in ArkTS widgets.| +## MarkStyle10+ + +| Name | Type | Mandatory| Default Value | Description | +| ----------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------------------------ | +| strokeColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color.White | Color of the internal mark. | +| size | number \| string | No | - | Size of the internal mark, in vp. The default size is the same as the width of the check box.
This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.| +| strokeWidth | number \| string | No | 2 | Stroke width of the internal mark, in vp. This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.| + ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index 0ff6c9dcf8bdf3c8e0cf55aaf3f68c439bdec48f..d6beb514c6590f6b4f977b37052d78f180ff8f51 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -14,7 +14,7 @@ Not supported CheckboxGroup(options?: { group?: string }) -Creates a check box group so that you can select or deselect all check boxes in the group at the same time. Check boxes and the check box group that share the group name belong to the same group. +Creates a check box group so that you can select or deselect all check boxes in the group at the same time. Check boxes and the check box group that share a group name belong to the same group. Since API version 9, this API is supported in ArkTS widgets. @@ -30,8 +30,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| selectAll | boolean | Whether to select all.
Default value: **false**
If **select** is explicitly set for check boxes in the group, the check box settings are prioritized.
Since API version 9, this API is supported in ArkTS widgets.| +| selectAll | boolean | Whether to select all.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If the **select** attribute is set for a [\](ts-basic-components-checkbox.md) component in the same group, the setting of the **\** has a higher priority.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.
Since API version 9, this API is supported in ArkTS widgets.| +| unselectedColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Border color of the check box when it is not selected.| +| mark10+ | [MarkStyle](#markstyle10) | Internal icon style of the check box.| ## Events @@ -60,6 +62,13 @@ Since API version 9, this API is supported in ArkTS widgets. | Part | Some check boxes in the group are selected.| | None | None of the check boxes in the group are selected.| +## MarkStyle10+ + +| Name | Type | Mandatory| Default Value | Description | +| ----------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------------------------ | +| strokeColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color.White | Color of the internal mark. | +| size | number \| string | No | - | Size of the internal mark, in vp. The default size is the same as the width of the check box group component.
This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.| +| strokeWidth | number \| string | No | 2 | Stroke width of the internal mark, in vp. This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md index f65895eba487b20b68d4dc26f74f5c5493f3dccb..41db34a3c7167bc08af84c54586af4981a265efc 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datapanel.md @@ -28,15 +28,6 @@ Since API version 9, this API is supported in ArkTS widgets. | max | number | No | - When set to a value greater than 0, this parameter indicates the maximum value in the **values** list.
- When set to a value equal to or smaller than 0, this parameter indicates the sum of values in the **values** list. The values are displayed in proportion.
Default value: **100**| | type8+ | [DataPanelType](#datapaneltype) | No| Type of the data panel (dynamic modification is not supported).
Default value: **DataPanelType.Circle**| -## Attributes - -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. - -| Name | Type | Description | -| ----------- | ------- | -------------------------------------------- | -| closeEffect | boolean | Whether to disable the rotation effect for the component.
Default value: **false**| - - ## DataPanelType @@ -48,6 +39,50 @@ Since API version 9, this API is supported in ArkTS widgets. | Circle | Circle data panel.| +## Attributes + +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + + +| Name | Type| Mandatory| Description| +| ------------- | ------- | ---- | -------- | +| closeEffect | boolean | Yes| Whether to disable the rotation effect for the component.
Default value: **false**.| +| valueColors10+ | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | Yes| Array of data segment colors. A value of the **ResourceColor** type indicates a solid color, and A value of the **LinearGradient** type indicates a color gradient.| +| trackBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Yes| Background color.| +| strokeWidth10+ | [Length](ts-types.md#Length) | Yes| Stroke width of the border.| +| trackShadow10+ | [DataPanelShadowOption](#datapanelshadowoption10) | Yes| Shadow style. If this attribute is not set, the shadow effect is disabled.| + + +## DataPanelShadowOption10+ +| Name | Type| Mandatory| Description| +| ------------- | ------- | ---- | -------- | +| radius | number \| [Resource](ts-types.md#resource)| No| Shadow blur radius.
Default value: **5vp**| +| colors | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | No| Array of shadow colors for data segments.
Default value: same as the value of **valueColors**.| +| offsetX | number \| [Resource](ts-types.md#resource)| No| Offset on the x-axis.
Default value: **5vp**| +| offsetY | number \| [Resource](ts-types.md#resource)| No| Offset on the y-axis.
Default value: **5vp**| + +## LinearGradient10+ + +Describes the linear gradient. + +LinearGradient(colorStops: ColorStop[]) + +| Name | Type| Mandatory| Description| +| ------------- | ------- | ---- | -------- | +| colorStops | [ColorStop](#colorstop10)[] | Yes| Gradient colors and color stops.| + + +## ColorStop10+ + +Describes the gradient color stop. + +| Name | Type| Mandatory| Description| +| ------------- | ------- | ---- | -------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | Yes| Color value.| +| offset | [Length](ts-types.md#Length) | Yes| Gradient color stop (proportion value between 0 and 1).| + + + ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index 5ba70754a095b5cc00d3f317e62b9a9b7cb6471d..1b4f2c165ed231af18e4ad15a9588247fd60d161 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -4,7 +4,7 @@ The **\** component allows users to select a date from the given ran > **NOTE** > -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. ## Child Components @@ -20,33 +20,45 @@ Creates a date picker in the given date range. **Parameters** -| Name| Type| Mandatory | Description| -| -------- | -------- | ------------- | -------- | -| start | Date | No | Start date of the picker.
Default value: **Date('1970-1-1')**| -| end | Date | No | End date of the picker.
Default value: **Date('2100-12-31')**| -| selected | Date | No | Date of the selected item.
Default value: current system date | - +| Name | Type| Mandatory | Description | +| -------- | ---- | ---- | -------------------------------------- | +| start | Date | No | Start date of the picker.
Default value: **Date('1970-1-1')** | +| end | Date | No | End date of the picker.
Default value: **Date('2100-12-31')**| +| selected | Date | No | Date of the selected item.
Default value: current system date | ## Attributes -| Name | Type | Description | -| ------| -------------- | -------- | -| lunar | boolean | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.
Default value: **false**| +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + +| Name | Type | Description | +| -------------------------------- | ---------------------------------------- | ---------------------------------------- | +| lunar | boolean | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.
Default value: **false**| +| disappearTextStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width for the top and bottom items. | +| textStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items. | +| selectedTextStyle10+ | [PickerTextStyle](#pickertextstyle10) | Font color, font size, and font width of the selected item. | +## PickerTextStyle10+ + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------------------------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | No | Font color. | +| font | [Font](ts-types.md#font) | No | Text style. Only the font size and font width are supported.| ## Events -| Name| Description| -| -------- | -------- | +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. + +| Name | Description | +| ---------------------------------------- | ----------- | | onChange(callback: (value: DatePickerResult) => void) | Triggered when a date is selected.| ## DatePickerResult -| Name| Type| Description| -| -------- | -------- | -------- | -| year | number | Year of the selected date.| +| Name | Type | Description | +| ----- | ------ | --------------------------- | +| year | number | Year of the selected date. | | month | number | Month of the selected date. The value ranges from 0 to 11. The value **0** indicates January, and **11** indicates December.| -| day | number | Day of the selected date.| +| day | number | Day of the selected date. | ## Example @@ -63,7 +75,7 @@ struct DatePickerExample { build() { Column() { Button('Switch Calendar') - .margin({ top: 30 }) + .margin({ top: 30, bottom: 30 }) .onClick(() => { this.isLunar = !this.isLunar }) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index ed564ed02da8ab3d1c7332aaeb4e4a05543685b9..c14914b75ae50d9a2c78ee01514261e60aecfcef 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -19,7 +19,7 @@ Not supported ## APIs -Image(src: string | PixelMap | Resource) +Image(src: PixelMap | ResourceStr | DrawableDescriptor) Obtains an image from the specified source for subsequent rendering and display. @@ -27,34 +27,35 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** path prefix are supported, which are used to access the image path provided by a Data ability. Before loading images, the application must [request the required permissions](../../file-management/medialibrary-overview.md#requesting-permissions).
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
- ArkTS widgets do not support the **http://**, **datashare://**, or **file://data/storage** path prefixes.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | ---- | ---------------------------------------- | +| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \|ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** path prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
**NOTE**
- ArkTS widgets support GIF images, but the images are played only once when they are displayed.
- ArkTS widgets do not support the **http://**, **datashare://**, or **file://data/storage** path prefixes.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | -| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported.
Since API version 9, this API is supported in ArkTS widgets.| -| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover**
Since API version 9, this API is supported in ArkTS widgets.| -| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.
Default value: **ImageRepeat.NoRepeat**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| -| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| -| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.
Default value: **ImageRenderMode.Original**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| -| sourceSize | {
width: number,
height: number
} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to **PixelMap** objects or SVG images.| -| matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.
Since API version 9, this API is supported in ArkTS widgets.| -| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| -| syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| -| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.
This API is supported in ArkTS widgets.| -| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.| +| Name | Type | Description | +| ------------------------ | ---------------------------------------- | ---------------------------------------- | +| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported.
Since API version 9, this API is supported in ArkTS widgets.| +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover**
Since API version 9, this API is supported in ArkTS widgets.| +| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.
Default value: **ImageRepeat.NoRepeat**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| +| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| +| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.
Default value: **ImageRenderMode.Original**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| +| sourceSize | {
width: number,
height: number
} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to **PixelMap** objects or SVG images.| +| matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.
Since API version 9, this API is supported in ArkTS widgets.| +| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| +| syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| +| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.
This API is supported in ArkTS widgets. | +| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.| > **NOTE** > > To use shortcut keys to copy the image, the image must be in focus. To enable the image to gain focus, set both the **focusable** and **focusOnTouch** attributes to **true**. +> > For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, and **animate**. ### ImageInterpolation @@ -81,11 +82,11 @@ Since API version 9, this API is supported in ArkTS widgets. In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status. The value **1** means that the image is successfully loaded, and **0** means the opposite.
Since API version 9, this API is supported in ArkTS widgets. | -| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
Since API version 9, this API is supported in ArkTS widgets. | -| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.
Since API version 9, this API is supported in ArkTS widgets. | +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value **1** means that the image is successfully loaded, and **0** means the opposite.| +| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
Since API version 9, this API is supported in ArkTS widgets.| +| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.
Since API version 9, this API is supported in ArkTS widgets.| ## Example @@ -163,7 +164,7 @@ struct ImageExample1 { ### Loading Online Images -The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, use the [HTTP](../../connectivity/http-request.md) module in the SDK to send a network request, and then decode the returned data into a **PixelMap** in the **\** component. For details about image development, see [Image Development](../../media/image.md). The code snippet is as follows: +The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, you can use the [HTTP](../../connectivity/http-request.md) tool provided in the SDK to send a network request, and then decode the returned data into **PixelMap** objects in the **\** component. For details about image development, see [Image Processing](../../media/image-overview.md). The code snippet is as follows: ```tsx // @ts-nocheck @@ -371,7 +372,7 @@ import context from '@ohos.app.ability.common'; struct LoadImageExample { @State resourcesPath: string = '' @State sandboxPath: string = '' - context: context.UIAbility = getContext(this) as context.UIAbilityContext + context: context.UIAbilityContext = getContext(this) as context.UIAbilityContext build() { Column() { @@ -398,6 +399,12 @@ struct LoadImageExample { Image(this.resourcesPath) .width(100) .height(100) + .colorFilter([ + 0.30, 0.59, 0.11, 0, 0, + 0.30, 0.59, 0.11, 0, 0, + 0.30, 0.59, 0.11, 0, 0, + 0, 0, 0, 1.0, 0 + ]) Text(`Sandbox image path: ${this.sandboxPath}`) .fontSize(20) .margin({ bottom: 10 }) @@ -409,3 +416,4 @@ struct LoadImageExample { } } ``` + \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md index 65f7d17c6cc5f494896482669b720539aa07ad41..594bf9fe6a1e8107e29a4dffc3b4b8c444ff92af 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md @@ -22,7 +22,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | -------- | ------------------------- | ---------------------------------------------------------------- | -| fontSize | [Length](ts-types.md#length) | Font size that applies to all texts in the menu. When **Length** is of the number type, the unit is fp.| +| fontSizedeprecated | [Length](ts-types.md#length) | Font size of the menu text. When **Length** is of the number type, the unit is fp.
This API is deprecated since API version 10. You are advised to use **font** instead.| +| font10+ | [Font](ts-types.md#font) | Font style of the menu text.| +| fontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the menu text.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md index cce67b34b9d5c4b50f1ac55dcfffcc2fda09e3ee..a4616a22ad0712d5fe1d419f5d3a981c1fb6876f 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menuitem.md @@ -22,22 +22,26 @@ MenuItem(value?: MenuItemOptions| CustomBuilder) ## MenuItemOptions -| Name | Type | Mandatory| Description | -| --------- | ---------------------------------------- | ---- | -------------------------------------- | +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------- | ---- | -------------------------------------- | | startIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the left of the menu item. | -| content | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the menu item. | +| content | [ResourceStr](ts-types.md#resourcestr) | No | Content of the menu item. | | endIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the right of the menu item. | -| labelInfo | [ResourceStr](ts-types.md#resourcestr) | No | Information about the ending label, for example, shortcut **Ctrl+C**. | +| labelInfo | [ResourceStr](ts-types.md#resourcestr) | No | Information about the ending label, for example, shortcut **Ctrl+C**.| | builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Builder for a level-2 menu. | ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type| Description | -| ---------- | -------- | ---------------------------------------- | -| selected | boolean | Whether the menu item is selected.
Default value: **false** | -| selectIcon | boolean | Whether to display the icon of the menu item being selected.| +| Name | Type | Description | +| ------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| selected | boolean | Whether the menu item is selected.
Default value: **false** | +| selectIcon | boolean \| [ResourceStr](ts-types.md#resourcestr)10+ | Whether to display the selected icon for a menu item is selected.
Default value: **false**
**true**: When a menu item is selected, the default tick icon is displayed.
**false**: When a menu item is selected, no icon is displayed.
**ResourceStr**: When a menu item is selected, the specified icon is displayed.| +| contentFont10+ | [Font](ts-types.md#font) | Font style of the menu item content. | +| contentFontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the menu item content. | +| labelFont10+ | [Font](ts-types.md#font) | Font style of the menu item label. | +| labelFontColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Font color of the menu item label. | ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md index 85745ba42d26583d369fe5f652c756ae318440f5..90705e2c5a20844a2346e45dee5835c128054aec 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md @@ -5,6 +5,8 @@ The **\** component is used to display a QR code. > **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> +> The number of pixels of the **\** component is subject to the content. If the component size is not large enough, the content may fail to be displayed. In this case, you need to resize the component. ## Child Components @@ -22,7 +24,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | string | Yes| Content of the QR code.| +| value | string | Yes| Content of the QR code. A maximum of 256 characters are supported. If the number of characters exceeds 256, the first 256 characters are used.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index 0a05c9ce7311a0ab826543540dc95dda25699987..244b6990bba8d9ccc0817e5eb96b8769d38530df 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -20,8 +20,8 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | -------------- | -| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. | +| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. It is not displayed once there is any input. | +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated. | | controller8+ | [TextAreaController](#textareacontroller8) | No | Text area controller.| @@ -29,30 +29,31 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ------------------------ | ---------------------------------------- | ---------------------------------------- | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | -| placeholderFont | [Font](ts-types.md#font) | Placeholder text style. | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | +| Name | Type | Description | +| ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | +| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**| +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| > **NOTE** > -> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows: { top: 8 vp, right: 16 vp, bottom: 16 vp, left: 8 vp } +> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 8 vp,
right: 16 vp,
bottom: 8 vp,
left: 16 vp
} ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.
- **value**: text entered. | -| onCopy8+(callback:(value: string) => void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be copied.| -| onCut8+(callback:(value: string) => void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be cut.| -| onPaste8+(callback:(value: string) => void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be pasted.| +| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.
- **value**: text entered. | +| onEditChange(callback: (isEditing: boolean) => void)10+ | Triggered when the input status changes. When the cursor is placed in the text box, it is in the editing state. Otherwise, it is in the non-editing state. If the value of **isEditing** is **true**, text input is in progress. | +| onCopy8+(callback:(value: string) => void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be copied. | +| onCut8+(callback:(value: string) => void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be cut. | +| onPaste8+(callback:(value: string) => void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
- **value**: text to be pasted. | ## TextAreaController8+ @@ -102,6 +103,7 @@ struct TextAreaExample { build() { Column() { TextArea({ + text: this.text, placeholder: 'The text area can hold an unlimited amount of text. input your word...', controller: this.controller }) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 4a6457aeda349129f035fa428710b36f32e68d3b..cf42e030a17593607b5d4ff4a5c0711ed9dc22ad 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -21,7 +21,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | --------------- | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. | +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated. | | controller8+ | [TextInputController](#textinputcontroller8) | No | Text input controller.| @@ -34,7 +34,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | type | [InputType](#inputtype) | Input box type.
Default value: **InputType.Normal** | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.| | placeholderFont | [Font](ts-types.md#font) | Placeholder text font.| -| enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key. Only the default value is supported.
Default value: **EnterKeyType.Done**| +| enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.
Default value: **EnterKeyType.Done**| | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | | maxLength | number | Maximum number of characters in the text input. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| @@ -43,12 +43,12 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | style9+ | [TextInputStyle](#textinputstyle9) | Text input style.
Default value: **TextInputStyle.Default**| | textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Alignment mode of the text in the text box.
Default value: **TextAlign.Start** | | selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.| -| caretStyle10+ | {
caretWidth: [Length](ts-types.md#length)
} | Caret style. | +| caretStyle10+ | {
width: [Length](ts-types.md#length)
} | Caret style. | | caretPosition10+ | number | Caret position.| > **NOTE** > -> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 8 vp,
right: 16 vp,
bottom: 16 vp,
left: 8 vp
} +> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows: { top: 8 vp, right: 16 vp, bottom: 8 vp, left: 16 vp } ## EnterKeyType @@ -65,8 +65,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Description | | ------------------ | ------------- | | Normal | Normal input mode.
The value can contain digits, letters, underscores (_), spaces, and special characters.| -| Password | Password input mode. | -| Email | Email address input mode.| +| Password | Password input mode. The value can contain digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default.| +| Email | Email address input mode. The value can contain digits, letters, underscores (_), and at signs (@). Only one at sign (@) is allowed.| | Number | Digit input mode. | | PhoneNumber9+ | Phone number input mode.
The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.| @@ -81,15 +81,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onChange(callback: (value: string) => void) | Triggered when the input changes.
**value**: text content.| -| onSubmit(callback: (enterKey: EnterKeyType) => void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key.
**enterKeyType**: type of the Enter key. For details, see [EnterKeyType](#enterkeytype).| -| onEditChanged(callback: (isEditing: boolean) => void)(deprecated) | Triggered when the input status changes. Since API version 8, **onEditChange** is recommended.| -| onEditChange(callback: (isEditing: boolean) => void)8+ | Triggered when the input status changes. If the value of **isEditing** is **true**, text input is in progress. | -| onCopy(callback:(value: string) => void)8+ | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be copied.| -| onCut(callback:(value: string) => void)8+ | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be cut.| -| onPaste(callback:(value: string) => void)8+ | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be pasted.| +| onChange(callback: (value: string) => void) | Triggered when the input changes.
**value**: text content.
This event is triggered when any of the following conditions is met:
1. Keyboard input is received.
2. Paste and cut is performed.
3. Ctrl+V is pressed. | +| onSubmit(callback: (enterKey: EnterKeyType) => void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key.
**enterKeyType**: type of the Enter key. For details, see [EnterKeyType](#enterkeytype). | +| onEditChanged(callback: (isEditing: boolean) => void)(deprecated) | Triggered when the input status changes. Since API version 8, **onEditChange** is recommended. | +| onEditChange(callback: (isEditing: boolean) => void)8+ | Triggered when the input status changes. When the cursor is placed in the text box, it is in the editing state. Otherwise, it is in the non-editing state. If the value of **isEditing** is **true**, text input is in progress. | +| onCopy(callback:(value: string) => void)8+ | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be copied. | +| onCut(callback:(value: string) => void)8+ | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be cut. | +| onPaste(callback:(value: string) => void)8+ | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be pasted. | ## TextInputController8+ @@ -135,7 +135,7 @@ struct TextInputExample { build() { Column() { - TextInput({ placeholder: 'input your word...', controller: this.controller }) + TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller }) .placeholderColor(Color.Grey) .placeholderFont({ size: 14, weight: 400 }) .caretColor(Color.Blue) @@ -144,6 +144,9 @@ struct TextInputExample { .margin(20) .fontSize(14) .fontColor(Color.Black) + .inputFilter('[a-z]', (e) => { + console.log(JSON.stringify(e)) + }) .onChange((value: string) => { this.text = value }) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md index 33a7c78171bc139b35cdb326c91dc9c325f33799..f644f8d30d81df0d011cd05c4f88339edccca5a1 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md @@ -14,7 +14,7 @@ Not supported ## APIs -TextPicker(options?: {range: string[]|Resource, selected?: number, value?: string}) +TextPicker(options?: {range: string[]|Resource|TextPickerRangeContent[], selected?: number, value?: string}) Creates a text picker based on the selection range specified by **range**. @@ -22,15 +22,27 @@ Creates a text picker based on the selection range specified by **range**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | string[] \| [Resource](ts-types.md#resource)| Yes| Data selection range of the picker.| +| range | string[] \| [Resource](ts-types.md#resource)\|[TextPickerRangeContent](#textpickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed. If it is dynamically changed to an empty array, the current value remains displayed.| | selected | number | No| Index of the default item in the range.
Default value: **0**| -| value | string | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item| +| value | string | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item
**NOTE**\
This parameter works only for a text list. It does not work for an image list or a list consisting of text and images.| + +## TextPickerRangeContent10+ + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------------------- | ---- | ---------- | +| icon | string \| [Resource](ts-types.md#resource) | Yes | Image resource.| +| text | string \| [Resource](ts-types.md#resource) | No | Text information.| ## Attributes +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. + | Name| Type| Description| | -------- | -------- | -------- | | defaultPickerItemHeight | number \| string | Height of each item in the picker.| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items.| +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item.| ## Events @@ -38,7 +50,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onChange(callback: (value: string, index: number) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item.
- **index**: index of the selected item.| +| onChange(callback: (value: string, index: number) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item.
**NOTE**
For a text list or a list consisting of text and images, **value** indicates the text value of the selected item. For an image list, **value** is empty.
- **index**: index of the selected item. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index d8ba7caae7fda819684c2b6ac53133c8bbebbacb..831d427ccc5e558a6119408f105a0277a888323b 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -1,6 +1,6 @@ # TimePicker -The **\** component allows users to select a time from the given range. +The **\** component allows users to select a time (with the hour and minute) from the given range. > **NOTE** > @@ -20,20 +20,25 @@ Creates a time picker, which is in 24-hour format by default. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| selected | Date | No| Time of the selected item.
Default value: current system time| - +| Name | Type| Mandatory | Description | +| -------- | ---- | ---- | ------------------------ | +| selected | Date | No | Time of the selected item.
Default value: current system time| ## Attributes -| Name| Type| Description| -| -------- | -------- | -------- | -| useMilitaryTime | boolean | Whether to display time in 24-hour format. The value cannot be modified dynamically.
Default value: **false**| +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +| Name | Type | Description | +| -------------------------------- | ---------------------------------------- | ----------------------------------- | +| useMilitaryTime | boolean | Whether to display time in 24-hour format. The value cannot be modified dynamically.
Default value: **false**| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width for the top and bottom items. | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of all items except the top, bottom, and selected items. | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Font color, font size, and font width of the selected item. | ## Events +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. + | Name | Description | | ---------------------------------------- | ----------- | | onChange(callback: (value: TimePickerResult ) => void) | Triggered when a time is selected.| @@ -48,9 +53,6 @@ Creates a time picker, which is in 24-hour format by default. ## Example - -### Time Picker - ```ts // xxx.ets @Entry diff --git a/en/application-dev/reference/arkui-ts/ts-container-gridcol.md b/en/application-dev/reference/arkui-ts/ts-container-gridcol.md index cff58a0505258230f3bb60a45ffba2a2c2553c7a..8bf95c5cac475e7f0ecfdcadd77c7d322a25bf63 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-gridcol.md +++ b/en/application-dev/reference/arkui-ts/ts-container-gridcol.md @@ -28,7 +28,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | ------------------------------------------------------------ | | span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| -| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| +| gridColOffset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| | order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| ## GridColColumnOption diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index 6b6a994a6f4e5ea976e96c87a366c501479383c4..190118b6a7f136146d6a7d3e5853255439920d43 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -11,6 +11,10 @@ The **\** component is used only in the **\** component. It co This component supports only one child component. +> **NOTE** +> +> System components and custom components can be built in, and rendering control types ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) are supported. + ## APIs @@ -23,37 +27,95 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. | -| tabBar9+ | [SubTabBarStyle](#subtabbarstyle) \| [BottomTabBarStyle](#bottomtabbarstyle) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.| +| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| +| tabBar9+ | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an underline.
When an icon display error occurs, a gray blank block is displayed.| > **NOTE** -> - The **\** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\** component. -> - The **\** component does not support setting of the common height attribute. Its height is determined by the height of the parent **\** component and the **\** component. -> - **\** does not support page scrolling. If page scrolling is required, consider nesting a list. +> +> - The **\** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\** component. +> - The **\** component does not support setting of the common height attribute. Its height is determined by the height of the parent **\** component and the **\** component. +> - If the **vertical** attribute is **false**, the width and height descriptions are swapped in the preceding two restrictions. +> - **\** does not support page scrolling. If page scrolling is required, consider nesting a list. ## SubTabBarStyle9+ Implements the subtab style. -### constructor9+ +### constructor constructor(content: string | Resource) -A constructor used to create a **SubTabBarStyle** instance. +Constructor used to create a **SubTabBarStyle** instance. **Parameters** | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| content | string \| [Resource](ts-types.md#resource) | Yes| Text for the tab.| +| content | string \| [Resource](ts-types.md#resource) | Yes| Text for the tab. Since API version 10, the type of **content** is **ResourceStr**.| + +### of10+ + +static of(content: ResourceStr) + +Static constructor used to create a **SubTabBarStyle** instance. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | ------------------ | +| content | [ResourceStr](ts-types.md#resourcestr) | Yes | Text for the tab.| + +### Attributes + +The following attributes are supported. + +| Name | Type | Description | +| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| indicator10+ | [IndicatorStyle](#indicatorstyle10)| Underline indicator style of the selected subtab. It is valid only in the horizontal layout.
| +| selectedMode10+ | [SelectedMode](#selectedmode10) | Display mode of the selected subtab.
Default value: **SelectedMode.INDICATOR**| +| board10+ | [BoardStyle](#boardstyle10) | Board style of the selected subtab.| +| labelStyle10+ | [LabelStyle](#labelstyle10) | Label text and font style of the selected subtab.| + +## IndicatorStyle10+ + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------------------------------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | No| Underline indicator color and board color.
Default value: **#FF007DFF**| +| height | [Length](ts-types.md#length) | No| Height of the underline indicator.
Default value: **2.0**
Unit: vp| +| width | [Length](ts-types.md#length) | No| Width of the underline indicator.
Default value: **0.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator.
Default value: **0.0**
Unit: vp| +| marginTop | [Length](ts-types.md#length) | No| Spacing between the underline indicator and text.
Default value: **8.0**
Unit: vp| + +## SelectedMode10+ +| Name | Description | +| ---------- | ------------------------ | +| INDICATOR | Underline indicator mode. | +| BOARD | Board mode. | + +## BoardStyle10+ + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | ------------------------------------ | +| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator.
Default value: **8.0**
Unit: vp| + +## LabelStyle10+ + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | No | Display mode when the label text is too long. By default, an ellipsis (...) is used to represent text overflow.| +| maxLines | number | No | Maximum number of lines in the label text. By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.| +| minFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | No | Minimum font size of the label text. For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings.| +| maxFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | No | Maximum font size of the label text. For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings.| +| heightAdaptivePolicy | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | No | How the adaptive height is determined for the label text. | +| font | [Font](ts-types.md#font) | No | Font of the label text. | ## BottomTabBarStyle9+ Implements the bottom and side tab style. -### constructor9+ +### constructor -constructor(icon: string | Resource, text: string | Resource) +constructor(icon: string | Resource, content: string | Resource) A constructor used to create a **BottomTabBarStyle** instance. @@ -61,8 +123,20 @@ A constructor used to create a **BottomTabBarStyle** instance. | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | string \| [Resource](ts-types.md#resource) | Yes| Image for the tab.| -| text | string \| [Resource](ts-types.md#resource) | Yes| Text for the tab.| +| icon | string \| [Resource](ts-types.md#resource) | Yes| Image for the tab. Since API version 10, the type of **icon** is **ResourceStr**.| +| text | string \| [Resource](ts-types.md#resource) | Yes| Text for the tab. Since API version 10, the type of **text** is **ResourceStr**.| + +### of10+ + +static of(icon: ResourceStr, text: ResourceStr) +Static constructor used to create a **BottomTabBarStyle** instance. + +**Parameters** + +| Name| Type | Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | [ResourceStr](ts-types.md#resourcestr) | Yes| Image for the tab.| +| text | [ResourceStr](ts-types.md#resourcestr) | Yes| Text for the tab.| ## Example @@ -325,3 +399,4 @@ struct TabBarStyleExample { ``` ![tabbarStyle](figures/TabBarStyle.jpeg) + \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index e1d90464b363777239c670b679a0cf1e2c5d711d..db9325e998325495db17eb915dbd888f834c4ecc 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -2,7 +2,7 @@ The **\** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view. -> **NOTE**
+> **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -18,47 +18,58 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| barPosition | BarPosition | No| Position of the **\** component.
Default value: **BarPosition.Start**| -| index | number | No| Initial tab index.
Default value: **0**| -| controller | [TabsController](#tabscontroller) | No| Tab controller.| +| Name | Type | Mandatory | Description | +| ----------- | --------------------------------- | ---- | ---------------------------------------- | +| barPosition | BarPosition | No | Position of the **\** component.
Default value: **BarPosition.Start** | +| index | number | No | Initial tab index.
Default value: **0**
**NOTE**

A value less than 0 evaluates to the default value.
The value ranges from 0 to the number of **\** subnodes minus 1.
When this parameter is set to different values, the slide animation for tab switching is enabled by default. To disable the animation, set **animationDuration** to **0**.| +| controller | [TabsController](#tabscontroller) | No | Tab controller. | ## BarPosition -| Name| Description| -| -------- | -------- | +| Name | Description | +| ----- | ---------------------------------------- | | Start | If the **vertical** attribute is set to **true**, the tab is on the left of the container. If the **vertical** attribute is set to **false**, the tab is on the top of the container.| -| End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container.| +| End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| vertical | boolean | Whether to use vertical tabs. The value **true** means to use vertical tabs, and **false** means to use horizontal tabs.
Default value: **false**| -| scrollable | boolean | Whether the tabs are scrollable. The value **true** means that the tabs are scrollable, and **false** means the opposite.
Default value: **true**| -| barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.
Default value: **BarMode.Fixed**| -| barWidth | number \| Length8+ | Width of the tab bar. | -| barHeight | number \| Length8+ | Height of the tab bar. | -| animationDuration | number | Duration of the slide animation for tab switching. If this parameter is set, the tab switching animation is played when the user switches between tabs by sliding or clicking. If this parameter is not set, the tab switching animation is played only when the user switches between tabs by sliding.
Default value: **200**| +| Name | Type | Description | +| ------------------------ | ---------------------------------------- | ---------------------------------------- | +| vertical | boolean | Whether to use vertical tabs. The value **true** means to use vertical tabs, and **false** means to use horizontal tabs.
Default value: **false**| +| scrollable | boolean | Whether the tabs are scrollable. The value **true** means that the tabs are scrollable, and **false** means the opposite.
Default value: **true**| +| barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.
Default value: **BarMode.Fixed**| +| barWidth | number \| Length8+ | Width of the tab bar.
**NOTE**

A value less than 0 or greater than the width of the **\** component evaluates to the default value.| +| barHeight | number \| Length8+ | Height of the tab bar.
**NOTE**

A value less than 0 or greater than the width of the **\** component evaluates to the default value.| +| animationDuration | number | Duration of the slide animation for tab switching. If this parameter is set, the tab switching animation is played when the user switches between tabs by sliding or clicking. If this parameter is not set, the tab switching animation is played only when the user switches between tabs by sliding.
Default value: **300**
**NOTE**
A value less than 0 or in percentage evaluates to the default value. | +| divider10+ | [DividerStyle](#dividerstyle10) \| null | Whether the divider is displayed for the **\** and **\** components and the divider style. By default, the divider is not displayed.
**DividerStyle**: divider style.
**null**: The divider is not displayed.| +| FadingEdge10+ | boolean | Whether the tab fades out when it exceeds the container width.
Default value: **true** | + +## DividerStyle10+ + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ----------------------------------- | +| strokeWidth | [Length](ts-types.md#length) | Yes | Width of the divider. | +| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider.
Default value: **#33182431** | +| startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar.
Default value: **0.0**
Unit: vp| +| endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar.
Default value: **0.0**
Unit: vp| ## BarMode -| Name| Description| -| -------- | -------- | +| Name | Description | +| ---------- | ---------------------------------------- | | Scrollable | The width of each tab is determined by the actual layout. The tabs are scrollable in the following case: In horizontal layout, the total width exceeds the tab bar width; in horizontal layout, the total height exceeds the tab bar height.| -| Fixed | The width of each tab is determined by equally dividing the number of tabs by the bar width (or the bar height in vertical layout).| +| Fixed | The width of each tab is determined by equally dividing the number of tabs by the bar width (or bar height in the vertical layout).| ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name| Description| -| -------- | -------- | -| onChange(event: (index: number) => void) | Event triggered when a tab is switched.| +| Name | Description | +| ------------------------------------------- | ------------------------------------------------------------ | +| onChange(event: (index: number) => void) | Triggered when a tab is switched.
- **index**: index of the active tab. The index starts from 0.
This event is triggered when any of the following conditions is met:
1. The **\** component supports sliding, and the user slides on the tab bar.
2. The [Controller](#tabscontroller) API is called.
3. The attribute value is updated using a [state variable](../../quick-start/arkts-state.md).
4. A tab is clicked. | ## TabsController @@ -66,9 +77,8 @@ Defines a tab controller, which is used to control switching of tabs. One **Tabs ### Objects to Import -``` +```ts controller: TabsController = new TabsController() - ``` ### changeIndex @@ -79,9 +89,9 @@ Switches to the specified tab. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | number | Yes| Index of the tab. The value starts from 0.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| value | number | Yes | Index of the tab. The value starts from 0.
**NOTE**

If this parameter is set to a value less than 0 or greater than the maximum number, the event will be invalid.| ## Example @@ -148,3 +158,4 @@ struct TabsExample { ``` ![tabs2](figures/tabs2.gif) + \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md index c69ca31dbccaa9f3246500d1b5baa92cc50718bc..47c8c41f78db5961fb831835c0b73fd8b91e129e 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-circle.md @@ -37,10 +37,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeDashArray | Array<Length> | Stroke dashes.
Default value: **[]**
Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | Offset of the start point for drawing the stroke.
Default value: **0**
Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the stroke.
Default value: **LineCapStyle.Butt**
Since API version 9, this API is supported in ArkTS widgets.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.
Default value: **LineJoinStyle.Miter**
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.
Default value: **LineJoinStyle.Miter**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not work for the **\** component, which does not have corners.| | strokeMiterLimit | number \| string | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.
Default value: **4**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect for the **\** component, because it does not have a miter join.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| Stroke opacity.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | Stroke width.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | Stroke width.
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | Whether anti-aliasing is enabled.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md index c8249cf5a97811d42832fd262c1eee1d3bc2e985..95d6e04adb6cdac5a36d57cc6013c3eb98434491 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md @@ -37,10 +37,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not work for the **\** component, which does not have corners.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect for the **\** component, because it does not have a miter join.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md index a8097c5e449d613a378643fef8902abe41be6bba..fec90d36ae1f8b6ebdd3464142a29dbe9bbfd2e7 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md @@ -39,10 +39,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeDashArray | Array<Length> | [] | Stroke dashes.
Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not work for the **\** component, which does not have corners. | | strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute does not take effect because the **\** component cannot be used to draw a shape with a sharp angle.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| -| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Example @@ -58,35 +58,41 @@ struct LineExample { Column({ space: 10 }) { // The coordinates of the start and end points of the line are determined relative to the coordinates of the drawing area of the component. Line() + .width(200) + .height(150) .startPoint([0, 0]) .endPoint([50, 100]) .stroke(Color.Black) .backgroundColor('#F5F5F5') Line() .width(200) - .height(200) + .height(150) .startPoint([50, 50]) .endPoint([150, 150]) .strokeWidth(5) .stroke(Color.Orange) .strokeOpacity(0.5) .backgroundColor('#F5F5F5') - // If the coordinates of a point are beyond the width and height range of the component, the line will exceed the drawing area. - Line({ width: 50, height: 50 }) + // strokeDashOffset is used to define the offset when the associated strokeDashArray array is rendered. + Line() + .width(200) + .height(150) .startPoint([0, 0]) .endPoint([100, 100]) .stroke(Color.Black) .strokeWidth(3) .strokeDashArray([10, 3]) + .strokeDashOffset(5) .backgroundColor('#F5F5F5') - // strokeDashOffset is used to define the offset when the associated strokeDashArray array is rendered. - Line({ width: 50, height: 50 }) + // If the coordinates of a point are beyond the width and height range of the component, the line will exceed the drawing area. + Line() + .width(50) + .height(50) .startPoint([0, 0]) .endPoint([100, 100]) .stroke(Color.Black) .strokeWidth(3) .strokeDashArray([10, 3]) - .strokeDashOffset(5) .backgroundColor('#F5F5F5') } } @@ -151,12 +157,16 @@ struct LineExample { build() { Column() { Line() + .width(300) + .height(30) .startPoint([50, 30]) .endPoint([300, 30]) .stroke(Color.Black) .strokeWidth(10) // Set the interval for strokeDashArray to 50. Line() + .width(300) + .height(30) .startPoint([50, 20]) .endPoint([300, 20]) .stroke(Color.Black) @@ -164,6 +174,8 @@ struct LineExample { .strokeDashArray([50]) // Set the interval for strokeDashArray to 50, 10. Line() + .width(300) + .height(30) .startPoint([50, 20]) .endPoint([300, 20]) .stroke(Color.Black) @@ -171,6 +183,8 @@ struct LineExample { .strokeDashArray([50, 10]) // Set the interval for strokeDashArray to 50, 10, 20. Line() + .width(300) + .height(30) .startPoint([50, 20]) .endPoint([300, 20]) .stroke(Color.Black) @@ -178,6 +192,8 @@ struct LineExample { .strokeDashArray([50, 10, 20]) // Set the interval for strokeDashArray to 50, 10, 20, 30. Line() + .width(300) + .height(30) .startPoint([50, 20]) .endPoint([300, 20]) .stroke(Color.Black) diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md index 313e416b8be00dff249f60ff55af2337a81c889c..25ba06a014b013ed97219d21cca40cca8f8e90c3 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -41,7 +41,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the stroke.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeWidth | Length | 1 | Width of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Width of the stroke.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| The supported commands are as follows: @@ -74,9 +74,10 @@ struct PathExample { .fontSize(11) .fontColor(0xCCCCCC) .width('90%') - // Draw a straight line whose length is 900 px and width is 3 vp. + // Draw a straight line whose length is 600 px and width is 3 vp. Path() - .height(10) + .width('600px') + .height('10px') .commands('M0 0 L600 0') .stroke(Color.Black) .strokeWidth(3) @@ -88,16 +89,22 @@ struct PathExample { // Draw a straight line. Flex({ justifyContent: FlexAlign.SpaceBetween }) { Path() + .width('210px') + .height('310px') .commands('M100 0 L200 240 L0 240 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() + .width('210px') + .height('310px') .commands('M0 0 H200 V200 H0 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() + .width('210px') + .height('310px') .commands('M100 0 L0 100 L50 200 L150 200 L200 100 Z') .fillOpacity(0) .stroke(Color.Black) @@ -108,16 +115,22 @@ struct PathExample { // Draw an arc. Flex({ justifyContent: FlexAlign.SpaceBetween }) { Path() + .width('250px') + .height('310px') .commands("M0 300 S100 0 240 300 Z") .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() + .width('210px') + .height('310px') .commands('M0 150 C0 100 140 0 200 150 L100 300 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() + .width('210px') + .height('310px') .commands('M0 100 A30 20 20 0 0 200 100 Z') .fillOpacity(0) .stroke(Color.Black) diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md index d126f92b224838ffb413cd58b0ad1f287300d184..8a0450ff17a692d98170a9dca96d7acb65250660 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md @@ -42,7 +42,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Point diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md index 4e5d746283be0023fe1951fa12a81d8cfdec398a..6681e790aeb02e3bcfb706cf0162e9c0376e7906 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md @@ -42,7 +42,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| ## Point diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md index f6ce5646c2893449a91080a30eeb635949d42f50..c7fac4fa35067c4e9be6e6e7aca05f0d7e25bdb1 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md @@ -48,7 +48,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | Length | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index 0444767799d78e070b7d2bb1aec631189587c5b2..d97d69beb73a8ac5c3a0a1c52c701287f056f827 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | -| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | View port of the shape.
Since API version 9, this API is supported in ArkTS widgets.| +| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | View port of the shape.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If of the string type, the value cannot be a percentage.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.
Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.
Since API version 9, this API is supported in ArkTS widgets.| @@ -46,7 +46,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.
Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.
**NOTE**
This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.
Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.
**NOTE**
The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Since API version 9, this API is supported in ArkTS widgets.| -| strokeWidth | number \| string | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.| +| strokeWidth | number \| string | 1 | Stroke width.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If of the string type, the value cannot be a percentage.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.
Since API version 9, this API is supported in ArkTS widgets.| | mesh8+ | Array<number>,number,number | [],0,0 | Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.
Since API version 9, this API is supported in ArkTS widgets.| @@ -70,6 +70,8 @@ struct ShapeExample { Ellipse().width(300).height(50).offset({ x: 0, y: 60 }) Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 }) } + .width(350) + .height(140) .viewPort({ x: -2, y: -2, width: 304, height: 130 }) .fill(0x317AF7) .stroke(Color.Black) @@ -83,6 +85,8 @@ struct ShapeExample { Shape() { Rect().width(300).height(50) } + .width(350) + .height(80) .viewPort({ x: 0, y: 0, width: 320, height: 70 }) .fill(0x317AF7) .stroke(Color.Black) @@ -91,6 +95,8 @@ struct ShapeExample { Shape() { Rect().width(300).height(50) } + .width(350) + .height(80) .viewPort({ x: -5, y: -5, width: 320, height: 70 }) .fill(0x317AF7) .stroke(Color.Black) @@ -101,6 +107,8 @@ struct ShapeExample { Shape() { Path().width(300).height(10).commands('M0 0 L900 0') } + .width(350) + .height(20) .viewPort({ x: 0, y: -5, width: 300, height: 20 }) .stroke(0xEE8443) .strokeWidth(10) @@ -109,6 +117,8 @@ struct ShapeExample { Shape() { Path().width(300).height(10).commands('M0 0 L900 0') } + .width(350) + .height(20) .viewPort({ x: 0, y: -5, width: 300, height: 20 }) .stroke(0xEE8443) .strokeWidth(10) @@ -118,6 +128,8 @@ struct ShapeExample { Shape() { Path().width(300).height(10).commands('M0 0 L900 0') } + .width(350) + .height(20) .viewPort({ x: 0, y: -5, width: 300, height: 20 }) .stroke(0xEE8443) .strokeWidth(10) @@ -126,6 +138,8 @@ struct ShapeExample { Shape() { Path().width(300).height(10).commands('M0 0 L900 0') } + .width(350) + .height(20) .viewPort({ x: 0, y: -5, width: 300, height: 20 }) .stroke(0xEE8443) .strokeWidth(10) @@ -135,7 +149,9 @@ struct ShapeExample { Shape() { Path().width(200).height(60).commands('M0 0 L400 0 L400 150 Z') } - .viewPort({ x: -80, y: -5, width: 310, height: 90 }) + .width(300) + .height(200) + .viewPort({ x: -20, y: -5, width: 310, height: 90 }) .fill(0x317AF7) .stroke(0xEE8443) .strokeWidth(10) @@ -147,3 +163,4 @@ struct ShapeExample { ``` ![en-us_image_0000001184628104](figures/en-us_image_0000001184628104.png) + diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index cdede4871a208b9007ca23842e293d309b1c1481..c1ad40842425ca4cdf7c66635cee70623b1c4509 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -21,6 +21,11 @@ Shows a date picker dialog box. | end | Date | No| Date('2100-12-31') | End date of the picker.| | selected | Date | No| Current system date| Selected date.| | lunar | boolean | No| false | Whether to display the lunar calendar.| +| showTime10+ | boolean | No| false | Whether to display the time item.| +| useMilitaryTime10+ | boolean | No| false | Whether to display time in 24-hour format.| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width for the top and bottom items.| +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| - | Font color, font size, and font width of the selected item.| | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| | onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.| diff --git a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index fed5193d5ea62277bf3ed86f4dfcdb5e18f56299..4da30a11300a3c5e2ab2cf3f622384f207bbf415 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -17,10 +17,13 @@ Shows a text picker in the given settings. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | string[] \| [Resource](ts-types.md#resource) | Yes| Data selection range of the picker.| +| range | string[] \| [Resource](ts-types.md#resource)\|[TextPickerRangeContent](ts-basic-components-textpicker.md#textpickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed.| | selected | number | No| Index of the selected item.
Default value: **0**| | value | string | No | Text of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.| | defaultPickerItemHeight | number \| string | No| Height of the picker item.| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| | onAccept | (value: [TextPickerResult](#textpickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| | onChange | (value: [TextPickerResult](#textpickerresult)) => void | No| Callback invoked when the selected item changes.| @@ -29,7 +32,7 @@ Shows a text picker in the given settings. | Name| Type| Description| | -------- | -------- | -------- | -| value | string | Text of the selected item.| +| value | string | Text of the selected item.
**NOTE**
For a text list or a list consisting of text and images, **value** indicates the text value of the selected item.
For an image list, **value** is empty.| | index | number | Index of the selected item in the range.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 32e6ad27c45532a17222a78b47cdde2c19dcff5b..246beaf9da869b68aa059efe66b7570f042ff205 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -19,6 +19,9 @@ Shows a time picker dialog box. | -------- | -------- | -------- | -------- | | selected | Date | No| Selected time.
Default value: current system time| | useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.
Default value: **false**| +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.| +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.| +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.| | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md index cfa2a0310f83db2933638297865c0f1674ea07b5..8098c34b6e8d1f8afe2f97cbddae20cae5934772 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-foreground-color.md @@ -47,12 +47,11 @@ struct ColoringStrategyExample { // Draw a circle with a diameter of 150 and set its foreground color to the inverse of the component background color. Circle({ width: 150, height: 200 }) .backgroundColor(Color.Black) - .foregroungColor(ColoringStrategy.Invert) + .foregroundColor(ColoringStrategy.INVERT) }.width('100%') } } ``` - ![foregroundColor_circle](figures/ColoringStrategy_circle.png) ### Example 3 @@ -64,9 +63,9 @@ struct ColoringStrategyExample { struct foregroundColorInherit { build() { Column() { - Button('Foreground Color Set to Orange').fontSize(20).foregroundColor(Color.Orange).backgroundColor(Color.Gray) + Button('Foreground Color: Set to Orange').fontSize(20).foregroundColor(Color.Orange).backgroundColor(Color.Gray) Divider() - Button ('Foreground Color Inherited from Parent Component When Not Set').fontSize(20).backgroundColor(Color.Gray) + Button ('Foreground Color: Inherited from Parent Component When Not Set').fontSize(20).backgroundColor(Color.Gray) }.foregroundColor(Color.Red) } } diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md index cf02ba55e1483bf32b09caf519f603183ea6064e..c58595fb1861bfb73d5f7700af3cf7d0c130c53e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md @@ -1,6 +1,6 @@ # Menu Control -A menu – a vertical list of items – can be bound to a component and displayed by long-pressing, clicking, or right-clicking the component. +A context menu – a vertical list of items – can be bound to a component and displayed by long-pressing, clicking, or right-clicking the component. > **NOTE** > @@ -10,18 +10,37 @@ A menu – a vertical list of items – can be bound to a component and displaye ## Attributes -| Name | Type | Description | +| Name | Type | Description | | ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| bindMenu | Array<[MenuItem](#menuitem)> \| [CustomBuilder](ts-types.md#custombuilder8) | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported.| -| bindContextMenu8+ | content: [CustomBuilder](ts-types.md#custombuilder8),
responseType: [ResponseType](ts-appendix-enums.md#responsetype8) | Context menu bound to the component, which is displayed when you long-press or right-click the component. Only custom menu items are supported.| +| bindMenu | content: Array<[MenuItem](#menuitem)> \| [CustomBuilder](ts-types.md#custombuilder8),
options: [MenuOptions](#menuoptions10) | Menu bound to the component, which is displayed when you click the component. A menu item can be a combination of text and icons or a custom component.
**content**: array of menu item text and icons or custom components.
**options**: parameters of the context menu. Optional.| +| bindContextMenu8+ | content: [CustomBuilder](ts-types.md#custombuilder8),
responseType: [ResponseType](ts-appendix-enums.md#responsetype8)
options: [ContextMenuOptions](#contextmenuoptions10) | Context menu bound to the component, which is displayed when the user long-presses or right-clicks the component. Only custom menu items are supported.
**responseType**: how the context menu triggered, which can be long-press or right-click. Mandatory.
**options**: parameters of the context menu. Optional.| ## MenuItem -| Name | Type | Description | -| ------ | ----------------------- | ----------- | -| value | string | Menu item text. | -| action | () => void | Action triggered when a menu item is clicked.| - +| Name | Type | Mandatory| Description | +| ------------------ | -------------------------------------- | ---- | ---------------------- | +| value | string | Yes | Menu item text. | +| icon10+ | [ResourceStr](ts-types.md#resourcestr) | No | Menu item icon. | +| action | () => void | Yes | Action triggered when a menu item is clicked.| + +## MenuOptions10+ + +| Name | Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ------------------------------------------------------ | +| title | string | No | Menu title. | +| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen.| +| placement | [Placement](ts-appendix-enums.md#placement8) | No| Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.
Default value: **Placement.Bottom**| +| onAppear | () => void | No| Callback triggered when the menu is displayed.| +| onDisappear | () => void | No| Callback triggered when the menu is hidden.| + +## ContextMenuOptions10+ + +| Name | Type | Mandatory| Description | +| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. | +| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.
Default value: **Placement.Bottom**| +| onAppear | () => void | No | Callback triggered when the menu is displayed. | +| onDisappear | () => void | No | Callback triggered when the menu is hidden. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md index a62a7a53b11336ce58448233fe4b1765580b9265..e154c2dfe63000e75d2525a02237a4852e1b5d54 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-sharp-clipping.md @@ -13,11 +13,56 @@ Shape clipping changes the visible portion of a component through clipping or ma | Name | Type | Description | | -----| ------------------------------------------ | ------------------------------------ | | clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | Clip mode. If the value is a shape, the component is clipped based on the specified shape. If the value is of the Boolean type, it specifies whether to clip the component based on the edge outline of the parent container.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | Mask of the specified shape to add to the component.
Since API version 9, this API is supported in ArkTS widgets.| +| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md)\| [ProgressMask](##progressmask10) | Mask of the specified shape to add to the component.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 10, this API supports the **ProgressMask** parameter.| + +## ProgressMask10+ + +Implements a **ProgressMask** object to set the progress, maximum value, and color of the mask. + +### constructor10+ + +constructor(value: number, total: number, color: ResourceColor) + +Constructs a **ProgressMask** object. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------ | +| value | number | Yes | Current value of the progress mask.| +| total | number | Yes | Maximum value of the progress mask.| +| color | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the progress mask. | + +### updateProgress10+ + +updateProgress(value: number): void + +Updates the progress value of the progress mask. + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| value | number | Yes | Current value of the progress mask.| + +### updateColor10+ + +updateColor(value: ResourceColor): void + +Updates the color of the progress mask. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------- | +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the progress mask.| + ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -54,3 +99,61 @@ struct ClipAndMaskExample { ``` ![clipAndMask](figures/clipAndMask.PNG) + +### Example 2 + +```ts +@Entry +@Component +struct ProgressMask { + @State progressflag1: boolean = true; + @State color: Color = 0x01006CDE; + @State value: number = 10.0; + @State progress: ProgressMask = new ProgressMask(10.0, 100.0, Color.Gray); + build() { + Column({ space: 15 }) { + Text('progress mask').fontSize(12).width('75%').fontColor('#DCDCDC') + // Add a 280px x 280px progress mask to the image. + Image($r('app.media.testImg')) + .width('500px').height('280px') + .mask(this.progress) + .animation({ + duration: 2000, // Animation duration. + .curve(Curve.Linear) // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation playback mode. + }) // Animation configuration for the width and height attributes of the + + + + ``` + +2. 在ArkTs中使用JavaScriptProxy方法将ArkTs里的对象注册到H5的window对象中,然后在h5中使用window对象调用该方法。比如下面例子,在ArkTs中将testObj这个对象以别名objName注册到h5的window对象上,在上面的h5中就可以使用window.objName去访问这个对象。 + + ``` + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + controller: web_webview.WebviewController = new web_webview.WebviewController() + testObj = { + test: (data1, data2, data3) => { + console.log("data1:" + data1); + console.log("data2:" + data2); + console.log("data3:" + data3); + return "AceString"; + }, + toString: () => { + console.log('toString' + "interface instead."); + } + } + build() { + Row() { + Column() { + Web({ src:$rawfile('index.html'), controller:this.controller }) + .javaScriptAccess(true) + .javaScriptProxy({ + object: this.testObj, + name: "objName", + methodList: ["test", "toString"], + controller: this.controller, + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + + +**参考链接** + +[javaScriptProxy](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy) + +## Web组件domStorageAccess属性设置 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启,控制web网页中localStorage的使用,对sessionStorage未做控制 + +**参考链接** + +[domStorageAccess](../reference/arkui-ts/ts-basic-components-web.md#domstorageaccess) diff --git a/zh-cn/application-dev/faqs/faqs-arkui.md b/zh-cn/application-dev/faqs/faqs-arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..b6da3c76c3de9a0623c2128d4e81a60250c79bfb --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-arkui.md @@ -0,0 +1,1466 @@ +# ArkUI框架开发常见问题 + +## 如何动态替换掉资源文件中的“%s”占位符 + +适用于OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +引用String资源,如何动态替换资源文件中的“%s”占位符。 + +**解决措施** + +在应用中,通过`$r('app.string.xx')`的形式引用应用资源,\$r的第二个参数可用于替换%s占位符。 + +**代码示例** + +``` +build() { + //do something + //引用的string资源,$r的第二个参数用于替换%s + Text($r('app.string.entry_desc','aaa')) + .fontSize(100) + .fontColor(Color.Black) + //do something +} +``` + +## 自定义弹窗能否在ts文件中定义和使用 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +自定义弹窗的定义和初始化需要用到属于ArkTS语法内容,必须在ets后缀文件中定义使用,不能在ts后缀文件中定义使用。 + +**参考链接** + +[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## 自定义弹窗中的变量如何传递给页面 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +在自定义弹窗内定义的变量内容,在关闭弹窗或变量变化时需要及时传递给页面,可以通过何种方式传递? + +**解决措施** + +- 方式一:使用组件的状态变量传递。 +- 方式二:在初始化弹窗时,传递一个方法给自定义弹窗,在自定义弹窗中触发该方法,弹窗中变量作为方法的参数。 +- 方式三:使用AppStorage或LocalStorage方式管理页面状态,实现自定义弹窗和页面之间状态的共享。 + +**代码示例** + +- 方式一: + + ``` + @CustomDialog + struct CustomDialog01 { + @Link inputValue: string + controller: CustomDialogController + build() { + Column() { + Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 }) + TextInput({ placeholder: '', text: this.inputValue }).height(60).width('90%') + .onChange((value: string) => { + this.inputValue = value + }) + } + } + } + + @Entry + @Component + struct DialogDemo01 { + @State inputValue: string = 'click me' + dialogController: CustomDialogController = new CustomDialogController({ + builder: CustomDialog01({ + inputValue: $inputValue + }) + }) + + build() { + Column() { + Button(this.inputValue) + .onClick(() => { + this.dialogController.open() + }).backgroundColor(0x317aff) + }.width('100%').margin({ top: 5 }) + } + } + + ``` + +- 方式二: + + ``` + @CustomDialog + struct CustomDialog02 { + private inputValue: string + changeInputValue: (val: string) => void + controller: CustomDialogController + build() { + Column() { + Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 }) + TextInput({ placeholder: '', text: this.inputValue }).height(60).width('90%') + .onChange((value: string) => { + this.changeInputValue(value) + }) + } + } + } + + @Entry + @Component + struct DialogDemo02 { + @State inputValue: string = 'click me' + dialogController: CustomDialogController = new CustomDialogController({ + builder: CustomDialog02({ + inputValue: this.inputValue, + changeInputValue: (val: string) => { + this.inputValue = val + } + }) + }) + + build() { + Column() { + Button(this.inputValue) + .onClick(() => { + this.dialogController.open() + }).backgroundColor(0x317aff) + }.width('100%').margin({ top: 5 }) + } + } + + ``` + +- 方式三: + + ``` + let storage = LocalStorage.GetShared() + @CustomDialog + struct CustomDialog03 { + @LocalStorageLink('inputVal') inputValue: string = '' + controller: CustomDialogController + build() { + Column() { + Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 }) + TextInput({ placeholder: '', text: this.inputValue }).height(60).width('90%') + .onChange((value: string) => { + this.inputValue = value; + }) + } + } + } + + @Entry(storage) + @Component + struct DialogDemo03 { + @LocalStorageLink('inputVal') inputValue: string = '' + dialogController: CustomDialogController = new CustomDialogController({ + builder: CustomDialog03() + }) + + build() { + Column() { + Button(this.inputValue) + .onClick(() => { + this.dialogController.open() + }).backgroundColor(0x317aff) + }.width('100%').margin({ top: 5 }) + } + } + + ``` + + +## 如何获取组件的宽高 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +组件的宽高信息用于计算布局区域大小以及偏移量等内容,如何获取宽高信息? + +**解决措施** + +- 方式一:使用组件区域变化事件onAreaChange,在组件初始化或组件尺寸发生变化时触发。 +- 方式二:在点击或触摸事件中,事件的回调信息中存在目标元素的区域信息。 + +**参考链接** + +[组件区域变化事件](../reference/arkui-ts/ts-universal-component-area-change-event.md),[点击事件](../reference/arkui-ts/ts-universal-events-click.md),[触摸事件](../reference/arkui-ts/ts-universal-events-touch.md) + +## 如何一键清空TextInput、TextArea组件内容 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +TextInput,TextArea组件输入多字符后,需要实现点击清空。 + +**解决措施** + +将状态变量赋值给TextInput或TextArea组件的text属性,在做点击清空事件时为状态变量赋值空字符串。 + +**代码示例** + +``` +struct Index { +@State text: string = 'Hello World' +controller: TextInputController = new TextInputController() + build() { + Row() { + Column() { + TextInput({ placeholder: 'Please input your words.', text: this.text, + controller:this.controller}).onChange((value) => { + this.text = value + }) + Button("Clear TextInput").onClick(() => { + this.text = ""; + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +## 如何设置自定义弹窗位置 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +自定义弹窗当前默认在窗口居中显示,当自定义弹窗需要与窗口边框对齐是需要设置自定义弹窗的对齐方式。 + +**解决措施** + +初始化自定义弹窗时,通过alignment参数设置对齐方式,通过offset设置弹窗偏移量。 + +**参考链接** + +[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## 如何隐藏容器组件的溢出内容 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +当容器组件内容溢出时,表现为子组件边缘超出容器组件,需要进行隐藏设置。 + +**解决措施** + +将通用属性-形状裁剪clip属性设置为true,表示按照容器边缘轮廓进行裁剪。此属性默认为false,表示不进行裁剪隐藏。 + +**参考链接** + +[形状裁剪](../reference/arkui-ts/ts-universal-attributes-sharp-clipping.md) + + +## 自定义弹窗大小如何自适应内容 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +当自定义弹窗中存在可变化区域大小的子组件时,弹窗大小需要跟随自适应。 + +**解决措施** + +- 方式一:采用弹窗容器默认样式。在默认样式中,弹窗容器高度自适应子节点,最大可为窗口高度的90%;弹窗容器的宽度根据栅格系统自适应,不跟随子节点变化。 +- 方式二:当显示设置customStyle为true时,弹窗宽高跟随子节点内容适应。 + +**参考链接** + +[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## 如何理解自定义弹窗中的gridCount参数 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +gridCount参数是指弹窗宽度占栅格列数的个数。系统把窗口宽等分,等分的份数即为栅格列数,不同设备栅格列数不同。比如手机屏幕密度值在320vp<=水平宽度<600vp,所以栅格列数是4,则gridCount的有效值在\[1, 4\]。 + +注意:仅采用弹窗默认样式时设置有效。 + +**参考链接** + +[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## 如何去除自定义弹窗的白色背景 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +使用自定义弹窗时,默认样式中存在白色背景。 + +**解决措施** + +需要采用自定义样式来消除自定义弹窗的白色背景: + +1. 在初始化自定义弹窗时设置customStyle为true。 +2. 在定义弹窗时设置组件背景色backgroundColor。 + +**参考链接** + +[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## TextInput组件密码模式下,右边的眼睛图标能否支持自定义 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +TextInput组件设置type为InputType.Password时,右侧出现眼睛图标,不能修改图标样式。 + +**解决措施** + +当前图标不支持自定义,可使用TextInput的showPasswordIcon属性隐藏图标,使用Image组件替代控制TextInput组件的type。 + +**参考链接** + +[TextInput组件](../reference/arkui-ts/ts-basic-components-textinput.md) + +## TextInput的onSubmit事件如何使用 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +TextInput的onSubmit事件怎么触发,以及事件回调的参数类型代表的含义。 + +**解决措施** + +onSubmit事件在外接键盘或软键盘回车时触发该回调,回调的参数为当前软键盘回车键类型。通过TextInput的enterKeyType属性可以设置输入法回车键类型,软键盘回车键样式需要输入法的支持。 + +**参考链接** + +[TextInput组件](../reference/arkui-ts/ts-basic-components-textinput.md) + +## TextInput在聚焦时如何使光标回到起点 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +TextInput组件在聚焦时,光标位置会自动根据触摸点位置变化,如何使得聚焦时光标固定显示在起点位置? + +**解决措施** + +1. TextInput组件绑定onEditChange事件,该事件TextInput可进行输入时触发。 +2. 在事件回调用TextInputController.caretPosition方法设置光标位置,不过需要用到setTimeout延迟方法。 + +**代码示例** + +``` +@Entry +@Component +struct TextInputDemo { + controller: TextInputController = new TextInputController() + + build() { + Column() { + TextInput({ controller: this.controller }) + .onEditChange((isEditing: boolean) => { + if (isEditing) { + setTimeout(() => { + this.controller.caretPosition(0) + }, 100) + } + }) + } + } +} +``` + +**参考链接** + +[TextInput组件](../reference/arkui-ts/ts-basic-components-textinput.md) + +## 如何获取组件的属性信息 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**解决措施** + +组件所有属性信息可通过通用属性-组件标识内getInspectorByKey获取。 + +**参考链接** + +[组件标识](../reference/arkui-ts/ts-universal-attributes-component-id.md) + +## 如何获取可滚动组件的当前滚动偏移量 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +可滚动组件包含List,Grid,Scroll等,在发生滚动时如何获取滚动偏移量? + +**解决措施** + +1. 可滚动组件在初始化时可设置scroller参数,绑定滚动控制器。 +2. 通过控制器的currentOffset方法可获取水平和竖直方向的滚动偏移量。 + +**参考链接** + +[Scroll](../reference/arkui-ts/ts-container-scroll.md#currentoffset) + +## 如何实现文本竖向排列 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +使用Text组件时,无法将文本排列方向设置为竖向排列。 + +**解决措施** + +Text组件当前文本排列方向固定为横向排列,要设置为竖向排列,可将文件拆分,使用Flex容器组件装填,设置主轴方向为竖向。 + +**代码示例** + +``` +@Entry +@Component +struct Index15 { + private message: string = '本文档适用于HarmonyOS应用开发的初学者。通过构建一个简单的具有页面跳转/返回功能的应用,快速了解工程目录的主要文件,熟悉HarmonyOS应用开发流程。'; + build() { + Flex({ direction: FlexDirection.Column, wrap: FlexWrap.Wrap }) { + ForEach(this.message.split(''), (item, index) => { + Text(item) + .fontSize(30) + .flexShrink(0) + }) + } + } +} +``` + +## 如何创建Toast窗口 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +应用做弱提示时,需要采用Toast窗口。 + +**解决措施** + +可使用系统提供的@ohos.promptAction接口创建Toast窗口。 + +**参考链接** + +[@ohos.promptAction \(弹窗\)](../reference/apis/js-apis-promptAction.md) + +## Toast弹窗是否支持自定义背景或者字体颜色 + +适用于 OpenHarmony 3.2 Beta5 API 9 Stage模型 + +当前版本不支持Toast弹窗自定义背景和字体颜色。 + +**参考链接** + +[@ohos.promptAction \(弹窗\)](../reference/apis/js-apis-promptAction.md) + +## 如何将Ability的UI界面设置成透明 + +适用于:OpenHarmony SDK 3.2,API9 + +**问题现象** + +如何设置Ability的UI界面为透明 + +**解决措施** + +将最上层容器组件背景色设置为透明,然后通过设置XComponent组件的opacity属性值为0.01来实现。 + +示例: + +``` +build() { + Stack() { + XComponent({ + id: 'componentId', + type: 'surface', + }) + .width('100%') + .height('100%') + .opacity(0.01) + // 页面内容 + } + .width('100%') + .height('100%') + .backgroundColor('rgba(255,255,255, 0)') +} +``` + +## constraintSize尺寸设置不生效 + +适用于:Openharmony 3.2 Beta5 API 9 stage模型 + +**问题现象** + +constraintSize约束组件尺寸时,子组件内设置百分比宽度,例如width\('100%'\)会采用constraintSize约束中的最大宽乘百分比,导致撑开组件,看起来constraintSize设置没生效。 + +**解决措施** + +可以在外层使用Scroll组件,设置constraintSize,当子组件占用空间超过设置的约束值时,会显示滚动条。 + +## 如何将背景颜色设置为透明 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +将backgroundColor设置为 '\#00000000'。 + +## Scroll组件滚动到达不了最底部 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +Scroll组件在未设置高度情况下,默认为窗口高度,当滚动区域外存在其他组件时,滚动底部区域会出现遮挡。 + +**解决措施** + +Scroll组件需要设置Scroll高度,或者使用Flex布局限制Scroll高度。 + +## backgroundImage如何设置CenterCrop + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +CenterCrop是android中imageView,scaletype的设置,主要保证图片等比缩放裁剪,位置保持居中,要达到相同效果,应该怎么处理? + +**解决措施** + +可以使用通用属性backgroundImageSize\(ImageSize.cover\)和backgroundImagePosition\(Alignment.Center\)达到相同效果。 + +## 如何自定义Video组件控制栏样式 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**解决措施** + +1. 通过设置属性controls为false关闭默认控制栏。 + +2. 设置Video组件的controller。 + +3. 通过ArkTS实现自定义的控制栏,并通过VideoController控制视频播放。 + +**代码示例** + +``` +// xxx.ets +@Entry@Componentstruct VideoCreateComponent { + @State videoSrc: Resource = $rawfile('video1.mp4') + @State previewUri: Resource = $r('app.media.poster1') + @State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X + @State isAutoPlay: boolean = false + @State showControls: boolean = true + controller: VideoController = new VideoController() + build() { + Column() { + Video({ + src: this.videoSrc, + previewUri: this.previewUri, + currentProgressRate: this.curRate, + controller: this.controller + }).width('100%').height(600) + .autoPlay(this.isAutoPlay) + .controls(this.showControls) + .onStart(() => { + console.info('onStart') + }) + .onPause(() => { + console.info('onPause') + }) + .onFinish(() => { + console.info('onFinish') + }) + .onError(() => { + console.info('onError') + }) + .onPrepared((e) => { + console.info('onPrepared is ' + e.duration) + }) + .onSeeking((e) => { + console.info('onSeeking is ' + e.time) + }) + .onSeeked((e) => { + console.info('onSeeked is ' + e.time) + }) + .onUpdate((e) => { + console.info('onUpdate is ' + e.time) + }) + Row() { + Button('src').onClick(() => { + this.videoSrc = $rawfile('video2.mp4') // 切换视频源 + }).margin(5) + Button('previewUri').onClick(() => { + this.previewUri = $r('app.media.poster2') // 切换视频预览海报 + }).margin(5) + + Button('controls').onClick(() => { + this.showControls = !this.showControls // 切换是否显示视频控制栏 + }).margin(5) + } + Row() { + Button('start').onClick(() => { + this.controller.start() // 开始播放 + }).margin(5) + Button('pause').onClick(() => { + this.controller.pause() // 暂停播放 + }).margin(5) + Button('stop').onClick(() => { + this.controller.stop() // 结束播放 + }).margin(5) + Button('setTime').onClick(() => { + this.controller.setCurrentTime(10, SeekMode.Accurate) // 精准跳转到视频的10s位置 + }).margin(5) + } + Row() { + Button('rate 0.75').onClick(() => { + this.curRate = PlaybackSpeed.Speed_Forward_0_75_X // 0.75倍速播放 + }).margin(5) + Button('rate 1').onClick(() => { + this.curRate = PlaybackSpeed.Speed_Forward_1_00_X // 原倍速播放 + }).margin(5) + Button('rate 2').onClick(() => { + this.curRate = PlaybackSpeed.Speed_Forward_2_00_X // 2倍速播放 + }).margin(5) + } + } + }} +``` + +**参考链接** + +[Video](../reference/arkui-ts/ts-media-components-video.md#start) + +## 如何设置组件不同状态下的样式 + +**问题现象** + +对应组件的不同状态(如无状态、按下、禁用、聚焦、点击),显示不同的样式。 + +**解决措施** + +使用多态样式,在组件的StateStyles接口中,定义组件不同状态下的样式。 + +**代码示例** + +``` +//xxx.ts +@Entry +@Component +struct StyleExample { + @State isEnable: boolean = true; + + @Styles pressedStyles() { + .backgroundColor("#ED6F21") + .borderRadius(10) + .borderStyle(BorderStyle.Dashed) + .borderWidth(2) + .borderColor('#33000000') + .width(120) + .height(30) + .opacity(1) + } + build() { + Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center}) { + Text("pressed") + .backgroundColor('#0A59F7') + .borderRadius(20) + .borderStyle(BorderStyle.Dotted) + .borderWidth(2) + .borderColor(Color.Red) + .width(100) + .height(25) + .opacity(1) + .fontSize(14) + .fontColor(Color.White) + .stateStyles({ + pressed: this.pressedStyles + }) + .margin({ + bottom: 20 + }) + .textAlign(TextAlign.Center) + } + .width(350) + .height(300) + } +} +``` + +**参考链接** + +[多态样式](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) + +## Scroll内Flex加宽高与滑动冲突 + +适用于:OpenHarmony 3.2 Beta5 API 9 Stage模型 + +**问题现象** + +当在Scroll组件中添加容器组件,并设置该容器组件的尺寸时,会破坏滚动布局。 + +**解决措施** + +Scroll组件中的容器组件不设置尺寸,大小由内容撑开。 + +## ArkTS使用position之后height不生效 + +适用于 OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +ArkTS使用position之后height不生效 + +**解决措施** + +容器组件在使用position之后会脱离文本流,导致容器脱离外层容器束缚,导致height不生效,可以将外层容器换成Stack可以解决这个问题。 + +## 焦点事件onBlur/onFocus回调无法触发 + +适用于 OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +焦点事件onBlur/onFocus回调无法触发 + +**解决措施** + +焦点事件默认情况下需要外接键盘的Tab键,或方向键触发,点击触发焦点事件需要添加焦点控制属性focusOnTouch。 + +**参考链接** + +[焦点控制](../reference/arkui-ts/ts-universal-attributes-focus.md) + +## scroll里面套一个grid,怎么禁用grid的滑动事件 + +适用于 OpenHarmony 3.2 Beta5 API 9 + +可以通过onScrollFrameBegin事件和scrollBy方法实现容器嵌套滚动。 + +可参考:[容器嵌套滚动样例](../reference/arkui-ts/ts-container-scroll.md#示例2) + +## 如何实现一个组件不停地旋转 + +适用于 OpenHarmony 3.2 Beta5 API 9 + +可以通过[属性动画](../reference/arkui-ts/ts-animatorproperty.md)的方式实现。 + +## 列表目前无法键盘上下滑动,是否能力不支持 + +适用于 OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +列表目前无法键盘上下滑动,是否能力不支持 + +**解决措施** + +有以下两种方案: + +1. 需要在列表子项中添加focusable\(true\)进行获焦。 +2. 在每个item的外层嵌套一个可获焦组件,例如Button。 + +## 键盘移动焦点对象按下enter,为什么不会触发点击事件? + +适用于 OpenHarmony 3.2 Beta5 API 9 + +组件的内置的点击事件和开发者自定义的onClick点击事件默认会和空格键绑定,并非与enter键绑定(UX规格) + +## 多层组件嵌套button,如何阻止事件传递 + +适用于 OpenHarmony 3.2 Beta5 API 9 + +可以通过将button组件绑定参数stopPropagation来控制冒泡传递。 + +## ArkUI如何通过代码动态创建组件 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +ArkUI使用ArkTS声明式开发范式,开发者无法持有组件实例,在声明时通过渲染控制语法以及动态构建UI元素的方式,控制组件的创建。 + +**代码示例** + +``` +// 条件渲染语句创建组件 +if(this.isTrue) { + Text("创建文本组件").fontSize(30) +} +// 循环渲染语句创建组件 +ForEach(this.nums,(item) => { + Text(item + '').fontSize(30) +},item => JSON.stringify(item)) +``` + +**参考链接** + +[渲染控制语法](../quick-start/arkts-rendering-control-overview.md) + +## 使用@Builder装饰器包含自定义组件的方法与普通方法的区别是什么 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +@Builder装饰的方法中使用了自定义组件,那么该方法每次被调用时,对应的自定义组件均会重新创建,普通方法中不使用@builder装饰,无法容纳自定义组件。 + +**参考链接** + +[@BuilderParam](../quick-start/arkts-builderparam.md) + +## 如何使用@BuilderParam装饰器进行组件传参 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +- 不带参数 + + 对@BuilderParam修饰的属性进行赋值时不带参数(如:content: this.specificParam),则此属性的类型需定义成无返回值的函数(如:@BuilderParam content: \(\) =\> void)。 + +- 带参数 + + 对@BuilderParam修饰的属性进行赋值时带参数(如:callContent: this.specificParam1\("111"\)),则此属性的类型需定义成any(如:@BuilderParam callContent: any)。 + + +**参考链接** + +[@BuilderParam](../quick-start/arkts-builderparam.md) + +## 如何监听数组内对象属性变化 + +适用于:OpenHarmony 3.2 Beta5 API9 + +**问题现象** + +数组内存储对象示例,需要对对象的属性变化进行监听。 + +**解决措施** + +通过@Observed配合@ObjectLink装饰符实现。@Observed用于类,@ObjectLink用于变量。 + +**代码示例** + +1. 在类上使用@Observed。 + + ``` + @Observed + class ClassA { + public name: string + public c: number + public id: number + + constructor(c: number, name: string = 'OK') { + this.name = name + this.c = c + } + } + ``` + +2. 在组件变量使用@ObjectLink。 + + ``` + @Component + struct ViewA { + label: string = 'ViewA1' + @ObjectLink a: ClassA + + build() { + Row() { + Button(`ViewA [${this.label}] this.a.c= ${this.a.c} +1`) + .onClick(() => { + this.a.c += 1 + }) + }.margin({ top: 10 }) + } + } + ``` + + +**参考链接** + +[Observed和ObjectLink数据管理](../quick-start/arkts-observed-and-objectlink.md) + +## 子组件使用@Link修饰成员变量时,如何通过父组件传值 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +子组件使用@Link接受父组件的值时,需要使用'\$'建立变量之间的引用关系。才能实现同步。 + +**代码示例** + +@Link语义是从`$`操作符引出,即\$isPlaying是this.isPlaying内部状态的双向数据绑定。当单击子组件PlayButton中的按钮时,@Link变量更改,PlayButton与父组件中的Text和Button将同时进行刷新,同样地,当点击父组件中的Button修改this.isPlaying时,子组件PlayButton与父组件中的Text和Button也将同时刷新。 + +1. 在父组件使用@State装饰器,传递数据使用\$符创建引用。 + + ``` + @Entry + @Component + struct Player { + @State isPlaying: boolean = false + build() { + Column() { + PlayButton({ buttonPlaying: $isPlaying }) + Text(`Player is ${this.isPlaying ? '' : 'not'} playing`).fontSize(18) + Button('Parent:' + this.isPlaying) + .margin(15) + .onClick(() => { + this.isPlaying = !this.isPlaying + }) + } + } + } + + + ``` + +2. 在子组件使用@Link接受数据。 + + ``` + @Component + struct PlayButton { + @Link buttonPlaying: boolean + + build() { + Column() { + Button(this.buttonPlaying ? 'pause' : 'play') + .margin(20) + .onClick(() => { + this.buttonPlaying = !this.buttonPlaying + }) + } + } + } + ``` + + +**参考链接** + +[@Link](../quick-start/arkts-link.md) + +## 父组件如何与孙子组件进行状态同步 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +- 方式一(推荐):使用@Provide和@Consume装饰器。在父组件使用@Provide,在孙子组件使用@Consume,可以实现父组件和孙子组件进行双向数据绑定。 + +- 方式二:使用@State和@Link装饰器。在父组件使用@State,在每一层子组件(子组件和孙子组件)都使用@Link。 + +**代码示例一** + +1. 父组件中使用子组件,通过Provide提供reviewVote参数,供跨级传递给孙子组件。 + + ``` + @Entry + @Component + struct Father{ + @Provide("reviewVote") reviewVotes: number = 0; + + build() { + Column() { + Son() + Button(`Father: ${this.reviewVotes}`) + ... + } + } + } + ``` + +2. 子组件中使用孙组件。 + + ``` + @Component + struct Son{ + build() { + Column() { + GrandSon() + } + } + } + ``` + +3. 孙子组件中使用Consume来接受reviewVote的参数。 + + ``` + @Component + struct GrandSon{ + @Consume("reviewVote") reviewVotes: number + + build() { + Column() { + Button(`GrandSon: ${this.reviewVotes}`) + ... + }.width('100%') + } + } + ``` + + +**代码示例二** + +1. 父组件Father使用@State绑定数据reviewVote。 + + ``` + @Entry + @Component + struct Father { + @State reviewVotes: number = 0; + + build() { + Column() { + Son({reviewVotes:$reviewVotes}) + Button(`Father: ${this.reviewVotes}`) + ... + } + } + } + ``` + +2. 子组件Son中使用@Link接受由父组件Father传递的参数reviewVote。 + + ``` + @Component + struct Son{ + @Link reviewVotes: number; + build() { + Column() { + Grandson({reviewVotes:$reviewVotes}) + } + } + } + + + ``` + +3. 孙子组件GrandSon使用@Link接受由Son组件传递的参数reviewVote。 + + ``` + @Component + struct Grandson{ + @Link reviewVotes: number; + + build() { + Column() { + Button(`Grandson: ${this.reviewVotes}`) + ... + }.width('100%') + } + } + ``` + + +## Js如何定义callback函数 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +定义个callback函数的样例,**示例如下:** + +1. 定义回调函数 + + ``` + // 页面中定义个2个参数,空返回的callback函数 + myCallback: (a:number,b:string) => void + ``` + +2. 在使用时进行初始化赋值 + + ``` + aboutToAppear() { + // callback函数初始化 + this.myCallback= (a,b)=>{ + console.info(`handle myCallback a=${a},b=${b}`) + }} + ``` + + +## 组件需要多次更新时如何优化性能 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +使用状态管理模块,目前已经支持最小化更新,当数据依赖变化时,不再是重新刷新整个自定义组件,而是只更新依赖数据的视图内容。 + +## 对象中函数的this如何指向外层 + +适用于:Openharmony 3.2 Beta5 API 9 + +**解决措施** + +通过箭头函数实现。 + +**代码示例** + +``` +const obj = { + start:() => { + return this.num + } +} +``` + +## 如何实现页面加载前从接口获取数据 + +适用于:Openharmony 3.2 Beta5 API 9 + +**问题现象** + +页面生命周期相关问题,在页面渲染前从接口获取数据,渲染时将数据渲染到页面上。 + +**解决措施** + +在声明周期函数aboutToAppear中使用异步接口获取页面数据,数据变量使用@State修饰,数据获取完成后根据变量自动刷新页面。 + +**代码示例** + +``` +@Entry +@Component +struct Test6Page { + // 数据获取成功,会自动刷新页面 + @State message: string = 'loading.....' + aboutToAppear(){ + // 模拟异步接口获取数据 + setTimeout(()=>{ + this.message = 'new msg' + },3000) + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +## Stage模型资源配置文件string.json是否支持配置占位符 + +适用于:Openharmony 3.2 Beta5 API 9 + +资源配置文件string.json文件本身不支持配置占位符,可以在对应的页面中通过定义变量,在实际组件使用Resources和变量拼接的方式达到实现占位符的同等效果。 + +## eTS文件和ts文件的区别 + +适用于:Openharmony 3.2 Beta5 API 9 + +**解决措施** + +ArkTS基于兼容了TS语法,继承了TS的所有特性,当前,ArkTS在TS的基础上主要扩展了声明式UI能力,让开发者能够以更简洁、更自然的方式开发高性能应用。推荐用ArtTS开发UI相关内容,TS可以用来开发业务逻辑相关内容。 + +**参考链接** + +[初识ArkTS](../quick-start/arkts-get-started.md) + +## ArkTS如何发送邮箱验证码 + +适用于:Openharmony 3.2 Beta5 API 9 + +**问题现象** + +ArkTS语言如何给邮箱发送邮箱验证码?用哪个接口? + +**解决措施** + +发送验证码需要请求服务端,然后服务端调用对应的短信验证码接口来实现该功能。可以通过短信服务实现相关功能。 + +## 如何将传感器的数据实时显示在UI的Text中 + +适用于:Openharmony 3.2 Beta5 API9 + +**问题现象** + +ArkUI(ets)如何将传感器的数据实时显示在UI的Text中。 + +**解决措施** + +传感器返回数据类型为double,可将double转为string,再显示在text中。 + +## 如何监听屏幕旋转 + +适用于:Openharmony 3.2 Beta5 API 9 + +**问题现象** + +应用想监听屏幕是否进行旋转操作。 + +**解决措施** + +屏幕旋转可使用媒体查询接口进行监听。 + +``` +import mediaquery from '@ohos.mediaquery' +let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件 +function onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + // do something here + } else { + // do something here + } +} +listener.on('change', onPortrait) // 注册回调 +listener.off('change', onPortrait) // 去注册回调 +``` + +**参考链接** + +[媒体查询](../reference/apis/js-apis-mediaquery.md) + +## DevEco Studio 升级到最新后ForEach不能遍历全部数据 + +适用于:Openharmony 3.2 Beta5 API 9 + +**问题现象** + +升级DevEco Studio后,ForEach无法遍历全部数据。 + +**解决措施** + +forEach\(\)功能进行了增强,其第三个参数keyGenerator如果传入参数时,需要确保数据源array中的每个元素生成的key不同,才能正常遍历。如果生成的key相同,则只能生成一个。 + +该第三个参数也可以不传,系统采用默认生成方式,也可以正常遍历出全部元素。 + +## 创建的单例换了页面后不生效问题 + +适用于:Openharmony 3.2 Beta5 API 9 + +**问题现象** + +单例只有在同一个流程中才有效,换了页面后之前的实例都全是undefined。 + +**解决措施** + +对于每个Page都会生成一个js文件,定义的单例会在每个js中都生成一份,所以单例的作用范围只是Page的范围。 + +如果想共享一个实例,创建范围需要提升至UIAbility或者App级别。 + +## 如何将时间格式的字符串string转换为Date对象 + +适用于:Openharmony 3.2 Beta5 API 9 + +**解决措施** + +如果字符string满足格式“yyyy-MM-dd”格式,则可直接使用函数new Date\("yyyy-MM-dd"\)来获取对应的Date对象。 + +``` +new Date("2021-05-23"); +new Date("2020/2/29"); +new Date("2020-14-03"); +new Date("14-02-2021"); +``` + +其他格式字符串可使用new Date\(year:number,month:number,day?:number,hour?:number,mintue?:number,second?:number,ms?:number\)方法来获取Date对象。 + +``` +根据参数创建日期的语法: +new Date(yearValue, IndexOfMonth, dayValue, hours, minutes, seconds) +``` + +其中每一个参数换算为对应时间参数传入即可。 + +- yearValue:应符合 ISO 8061 YYYY 格式。例如 2021。如果我们以 YY 格式指定一个值,它将会被错误地接受。例如,仅将 2021 提到 21 会被认为是 1921 年而不是 2021 年。 +- IndexOfMonth:从索引 0 开始。因此,从 Month 值中减去 1。例如,对于 3 月,该值为 3,但 monthIndex 将为 2(即 3-1 = 2)。本月指数通常应在 0-11 范围内 +- dayValue:表示一个月中的某天。它应在 1-31 范围内,具体取决于一个月中的天数。例如:对于 21-05-2021,日期值为 21 +- hours:一天中的小时。例如 10 点。 +- minutes:过去一个小时的分钟数 +- seconds:保留超过一分钟的秒数。 + +## ArkTS如何把string转为byte数组 + +适用于:Openharmony 3.2 Beta5 API 9 + +**解决措施** + +参考如下代码实现,示例: + +``` +stringToArray(str:string) { + var arr = []; + for(var i = 0,j = str.length;i { + /* 原数据,GBK编码 + + + xxxxx + xxxx + xxxx + + + xxxx + + + + xxxx + + + 1 + For Outsourcing Staff/xxxx + + xxxx + xxxx + + + */ + let src = 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iR0JLIj8+CjxkYXRhPgo8YXNzZXRfbm8+eHh4eHg8L2Fzc2V0X25vPgo8bWFjaGluZV9zbj54eHh4PC9tYWNoaW5lX3NuPgo8Ymlvc19pZD54eHh4PC9iaW9zX2lkPgo8cmVzcG9uc2libGVfZW1wX25hbWU+PCFbQ0RBVEFbeHh4eF1dPjwvcmVzcG9uc2libGVfZW1wX25hbWU+CjxyZXNwb25zaWJsZV9hY2NvdW50PjwhW0NEQVRBW3h4eHggeHh4eF1dPjwvcmVzcG9uc2libGVfYWNjb3VudD4KPHJlc3BvbnNpYmxlX2VtcF9ubz54eHh4PC9yZXNwb25zaWJsZV9lbXBfbm8+CjxyZXNwb25zaWJsZV9kZXB0PjwhW0NEQVRBW3h4eHhdXT48L3Jlc3BvbnNpYmxlX2RlcHQ+Cjx1c2VyX2RlcHQ+PCFbQ0RBVEFbeHh4eF1dPjwvdXNlcl9kZXB0Pgo8dXNlcl9uYW1lPjwhW0NEQVRBW3h4eF1dPjwvdXNlcl9uYW1lPgo8Y3VyX2RvbWFpbl9hY2NvdW50Pnh4eHg8L2N1cl9kb21haW5fYWNjb3VudD4KPGFzc2V0X2xvYz48IVtDREFUQVstLV1dPjwvYXNzZXRfbG9jPgo8YXNzZXRfbG9jX2N1cj48IVtDREFUQVtdXT48L2Fzc2V0X2xvY19jdXI+Cjxhc3NldF90eXBlPjE8L2Fzc2V0X3R5cGU+Cjxhc3NldF91c2U+Rm9yIE91dHNvdXJjaW5nIFN0YWZmL3h4eHg8L2Fzc2V0X3VzZT4KPG92ZXJkdWVfZGF0ZT48L292ZXJkdWVfZGF0ZT4KPGFzc2V0X3N0YXR1cz54eHh4PC9hc3NldF9zdGF0dXM+Cjxhc3NldF9wZXJpb2Q+eHh4eDwvYXNzZXRfcGVyaW9kPgo8bGljZW5zZT48L2xpY2Vuc2U+CjwvZGF0YT4=' + let base64 = new util.Base64Helper(); + // base解码 + let src_uint8Array = base64.decodeSync(src); + // 解码为utf-8的字符串 + let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM: true}) + let src_str = textDecoder.decodeWithStream(src_uint8Array) + //替换encoding字段 + src_str = src_str.replace("GBK","utf-8") + console.log('Test src_str: ' + JSON.stringify(src_str)); + // 转换 xml-> json + let conv = new convertxml.ConvertXML(); + let options = {trim : false, declarationKey:"_declaration", + instructionKey : "_instruction", attributesKey : "_attributes", + textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", + commentKey : "_comment", parentKey : "_parent", typeKey : "_type", + nameKey : "_name", elementsKey : "_elements"} + let src_json = JSON.stringify(conv.convertToJSObject(src_str, options)); + console.log('Test json: ' + JSON.stringify(src_json)); + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +## 通过try/catch语句获取到错误码401是什么意思 + +适用于:Openharmony 3.2 Beta5 API 9 + +**问题原因** + +1. 必选参数没有传入。 + +2. 参数类型错误。 + +3. 参数为undefined。 + +**参考链接** + +[通用错误码](../reference/errorcodes/errorcode-universal.md) diff --git a/zh-cn/application-dev/faqs/faqs-bundle-management.md b/zh-cn/application-dev/faqs/faqs-bundle-management.md new file mode 100644 index 0000000000000000000000000000000000000000..70d2dd7518b5674b41fb40d8e6c09945e3cb4bb5 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-bundle-management.md @@ -0,0 +1,126 @@ +# 包管理开发常见问题 + +## 如何判断某个应用是否为系统应用 + +适用于OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +使用bundleManager模块的getApplicationInfo接口(仅系统应用可以使用)获取待检验应用的ApplicaitonInfo,根据ApplicaitonInfo中systemApp字段判断,若为true,则是系统应用,否则为非系统应用。 + +**参考链接** + +[bundleManager模块](../reference/apis/js-apis-bundleManager.md) + +## 如何获取应用配置的versionCode和versionName + +适用于:Openharmony 3.2 Beta5 API 9 + +**解决措施** + +首先通过@ohos.bundle.bundleManager模块bundleManager.getBundleInfoForSelf\(\)接口获取包信息BundleInfo,然后分别通过BundleInfo.versionCode、BundleInfo.versionName获取所需信息。 + +**代码示例** + +``` +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; +try { + bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { + const versionCode = data.versionCode; + const versionName = data.versionName; + hilog.info(0x0000, 'testTag', `successfully. versionCode: ${versionCode}, versionName: ${versionName}`); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'failed: %{public}s', err.message); +} +``` + +**参考链接** + +[getBundleInfoForSelf](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundleinfoforself) + +## 如何获取应用自身的bundleName + +适用于:Openharmony 3.2 Beta5 API9 + +**解决措施** + +可以通过UIAbilityContext.abilityInfo.bundleName获取。 + +**代码示例** + +``` +import common from '@ohos.app.ability.common'; +const context = getContext(this) as common.UIAbilityContext +console.log(`bundleName: ${context.abilityInfo.bundleName}`) +``` + +**参考链接** + +[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontext)、[AbilityInfo](../reference/apis/js-apis-bundleManager-abilityInfo.md#abilityinfo) + +## 如何获取App版本号,版本名,屏幕分辨率等信息 + +适用于:OpenHarmony 3.2 Beta5 + +**解决措施** + +1. 通过@ohos.bundle.bundleManager模块中的bundleManager查询bundleInfo。 + + 在bundleInfo中包含App版本号、版本名信息。 + + ``` + import bundleManager from '@ohos.bundle.bundleManager'; + ... + bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo)=>{ + let versionName = bundleInfo.versionName;//应用版本名 + let versionNo = bundleInfo.versionCode;//应用版本号 + }).catch((error)=>{ + console.error("get bundleInfo failed,error is "+error) + }) + ``` + +2. 在模块@ohos.app.ability.Configuration中获取screenDensity,其中包含屏幕分辨率信息。 + + ``` + import common from '@ohos.app.ability.common'; + ... + let context = getContext(this) as common.UIAbilityContext; + let screenDensity = context.config.screenDensity; + ``` + + +## 如何获取应用自身的源文件路径 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +- 方式一:使用应用上下文context获取。 + + ``` + this.uiAbilityContext.abilityInfo.applicationInfo.codePath + ``` + +- 方式二:使用@ohos.bundle.bundleManager获取。 + + 1. 导入@ohos.bundle.bundleManager模块,使用bundleManager.getBundleInfoForSelf\(\)获取bundleInfo信息。 + 2. 使用bundleInfo.appInfo.codePath获取应用源文件路径。 + + ``` + import bundleManager from '@ohos.bundle.bundleManager'; + bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo)=>{ + this.sourcePath = bundleInfo.appInfo.codePath; + }) + ``` + + +## 能否在本应用中获取到其他应用的HAP包信息 + +适用于:OpenHarmony 3.2 Beta API 9 + +根据OpenHarmony的安全设计规范,SDK不提供接口能力给三方应用查询其他应用的包信息(包括但不限于应用名称、版本号等)。 diff --git a/zh-cn/application-dev/faqs/faqs-bundle.md b/zh-cn/application-dev/faqs/faqs-bundle.md deleted file mode 100644 index 357149d365e3d2ac59aae11414f0fc26d5c77610..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-bundle.md +++ /dev/null @@ -1,31 +0,0 @@ -# 应用程序包管理开发常见问题 - -## 如何获取应用配置的versionCode和versionName - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -通过@ohos.bundle模块bundle.getBundleInfo()接口获取包信息bundleInfo,然后分别通过bundleInfo.versionCode、bundleInfo.versionName - -参考文档:[Bundle模块](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo) - -## 如何获取应用自身的bundleName - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -通过可以context.abilityInfo.bundleName获取。 - -参考文档:[AbilityContext](../reference/apis/js-apis-ability-context.md)、[AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) - -## 如何获取应用图标 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -通过\@ohos.bundle模块 getAbilityIcon 接口获取,需要配置权限:ohos.permission.GET_BUNDLE_INFO。 - -参考文档:[Bundle模块](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo) - -## 如何判断某个应用是否为系统应用 - -使用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -使用bundle模块的getApplicationInfo接口获取待检验的应用的ApplicationInfo,根据ApplicationInfo中systemApp字段判断,若为true,则是系统应用,否则为非系统应用。 diff --git a/zh-cn/application-dev/faqs/faqs-connectivity.md b/zh-cn/application-dev/faqs/faqs-connectivity.md deleted file mode 100644 index 4da4a413145026fd5cea550b5df8fad8ee904644..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-connectivity.md +++ /dev/null @@ -1,104 +0,0 @@ -# 网络与连接开发常见问题 - -## 网络请求中extraData支持哪几种的数据格式 - -适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 - -extraData代表发送请求的额外数据,支持如下数据: - -1. 当HTTP请求为POST、PUT方法时,此字段为HTTP请求的content。 - -2. 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。 - -3. 开发者传入string对象,开发者需要自行编码,将编码后的string传入。 - -## 如何理解http请求的错误码28 - -适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 - -错误码28代表CURLE_OPERATION_TIMEDOUT,操作超时。网络请求底层使用libcurl库,更多错误码可以查看相应文档。 - -参考文档:[Response常用错误码](../reference/apis/js-apis-http.md#response常用错误码)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) - -## \@ohos.net.http.d.ts的response错误码返回6是什么意思? - -适用于:OpenHarmony SDK 3.2.3.5版本 - -6表示地址无法解析主机,可以尝试ping一下request中的url,确认是否可以ping通。 - -更多错误码参考[Response常用错误码](../reference/apis/js-apis-http.md#response常用错误码)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) - -## 调用camera拍摄的照片怎么上传到服务器 - -适用于:所有版本 - -具体开发参考文档:[上传下载](https://gitee.com/openharmony/app_samples/tree/master/Network/UploadDownload) - -## OpenHarmony的http接口如何设置cookie - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -HttpRequestOptions中的header是一个Object类型,可以直接在header里设置cookie,具体开发参考文档:[数据请求](../reference/apis/js-apis-http.md#request)。 - -## http请求的官方示例代码里的extra data部分怎么写 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -1. 鼠标移到extraData, ctrl+鼠标左键,跳转到sdk中,里面有关于extraData的传参说明。可以发现文档中对extraData的定义为 extraData?: string | Object,也就是extraData支持string 和 Object两种类型。 - -2. 这两种写法都可以实现: - a.extraData:"data to send"; - b. extraData:{ data:"data to send", }, - -## 设备连接wifi后,如何获取当前设备的IP地址 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -使用wifi模块获取ipInfo,然后转换为IP常用格式,注意wifi.getIpInfo()接口需要权限 ohos.permission.GET_WIFI_INFO。 - -示例: - - -``` -import wifi from '@ohos.wifi' -@Entry -@Component -struct Page { - @State ip: string = '点击获取ip' - - resolveIP(ip) { - if (ip < 0 || ip > 0xFFFFFFFF) { - throw ("The number is not normal!"); - } - return (ip >>> 24) + "." + (ip >> 16 & 0xFF) + "." + (ip >> 8 & 0xFF) + "." + (ip & 0xFF); - } - - build() { - Row() { - Column() { - Text(this.ip) - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(()=>{ - this.ip = this.resolveIP(wifi.getIpInfo().ipAddress) - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -## 如何判断当前是否有网络 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -通过如下hasDefaultNet接口判断是否有网络,注意需要申请 ohos.permission.GET_NETWORK_INFO 权限 - - -``` -connection.hasDefaultNet().then((has)=> { - console.log("hasDefaultNet " + JSON.stringify(has)) -}) -``` diff --git a/zh-cn/application-dev/faqs/faqs-data-management.md b/zh-cn/application-dev/faqs/faqs-data-management.md deleted file mode 100644 index 5b9e72b2dbd4af5dc6748bd6053e923de7f7a4c2..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-data-management.md +++ /dev/null @@ -1,72 +0,0 @@ -# 数据管理开发常见问题 - -## 如何将PixelMap的数据存储到数据库中 - -适用于:OpenHarmony SDK 3.2.3.5版本 - -PixelMap应该被转换成相应的ArrayBuffer再放进数据库。 - -参考文档:[readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1) - -## 如何获取rdb关系型数据库文件 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -开发者可使用hdc_std命令拷贝文件,其中文件路径为: /data/app/el2/100/database/包名/entry/db/ ,然后拷贝该路径下后缀为 .db、.db-shm、.db-wal的文件,拷贝完成后,可以通过SQLite工具打开该数据库文件。 - -示例: - -``` - hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db -``` - -## 数据库在系统层面是否有锁机制,开发过程中是否需要关系数据库加锁问题 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -系统提供的分布式数据服务、关系型数据库和首选项均有锁机制,开发者无需关注。 - -## 数据库中加事务与不加事务的区别? - -适用于:所有版本 - -在rdb中进行数据操作时,有可能会导致操作失败,出现意料之外的情况。当对数据库进行大量操作时,此种情况会导致部分数据操作失败,部分操作成功,导致部分数据丢失,可能会导致应用程序发生异常甚至崩溃。加事务后,则会将某一批操作组合成一个整体,要么同时成功,要么同时失败,则不会导致强关联的数据部分缺失的情况出现。 - -## 关系型数据库rdb支持哪些数据类型? - -适用于:OpenHarmony SDK 3.0版本以上,API9 Stage模型 - -关系型数据库rdb支持的数据类型有:number、string、boolean。其中number为数组类型,支持Double,Long,Float,Int,Int64,最大精度为十进制17位数字。 - -## 如何查看数据库db文件 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -1. 执行 hdc_std shell 命令进入系统 - -2. 找到绝对路径:/data/app/el2/<userId默认是100>/database/<bundleName> - 或找到沙箱路径: - - a. 执行 ps -ef | grep hapName 命令找到对应应用的进程ID, - - b. 数据库沙箱路径为:/proc/<应用进程ID>/root/data/storage/el2/database/。 - -3. 在数据库的绝对路径或者沙箱路径下执行 find ./ -name "\*.db" 即可找到数据库文件。 - -## 如何存储长文本数据 - -适用于:OpenHarmony SDK 3.2.5.5版本,API 9 - -- 首选项Preferences数据中的Value为string类型时最大支持8192字节。 - -- 分布式数据管理KV数据模型Value最大支持4M。 - -参考文档:[首选项概述](../database/database-preference-overview.md)、[分布式数据服务概述](../database/database-mdds-overview.md) - -## Stage模型数据共享DataShare开发 - -适用于:OpenHarmony SDK 3.2.5.5版本,API 9 - -Stage模型DataShare不可与FA模型DataAbility混用,连接的服务端应用需使用DataShareExtensionAbility实现。 - -参考文档:[数据共享开发指导](../database/database-datashare-guidelines.md) diff --git a/zh-cn/application-dev/faqs/faqs-development-board.md b/zh-cn/application-dev/faqs/faqs-development-board.md deleted file mode 100644 index 900ba10a82aabfa74029cecd45fe370f1464edc1..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-development-board.md +++ /dev/null @@ -1,49 +0,0 @@ -# 开发板使用常见问题 - -## 如何获取开发板上截屏图片? - -适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 - -- 方法一:点击开发板下拉控制中心的截屏按钮,截屏图片通过相册可以查看。 - -- 方法二:通过截屏脚本一键截屏,可以在电脑上查看。操作方法:Windows上连接开发板,然后电脑上新建文本文件,拷贝如下脚本内容,文件名后缀改为.bat文件(需要提前配置好hdc的环境变量),点击运行后,截屏图片与脚本在同一目录。 - 示例: - - ``` - set filepath=/data/%date:~0,4%%date:~5,2%%date:~8,2%%time:~1,1%%time:~3,2%%time:~6,2%.png - echo %filepath% - : pause - hdc_std shell snapshot_display -f %filepath% - : pause - hdc_std file recv %filepath% . - : pause - ``` - -## RK3568板子和previewer上展示的效果差异较大,如何把previewer的尺寸调整成实际板子一样。 - -适用于:IDE 3.0.0.991 - -1. 给预览器新建Profile - - ![zh-cn_image_0000001361254285](figures/zh-cn_image_0000001361254285.png) - -2. 新建Profile的具体参数可参考如下配置: - Device type : default - - Resolution: 720\*1280 - - DPI: 240 - -## 开发板安装驱动后设备仍然无法识别,设备管理器错误识别为其他设备:FT232R USB UART () - -可能原因:开发版的USB串口驱动没有安装。 - -解决办法:搜索FT232R USB UART确定,下载安装驱动即可。 - -## 在开发板上登录需要认证网络如何进行认证 - -适用于:OpenHarmony SDK 3.2.2.5版本 - -连接需要认证的网络后,用浏览器打开任意网址就可以进入认证页面。 - -如果开发板上没有浏览器,可以安装[浏览器Sample应用](https://gitee.com/openharmony/app_samples/tree/master/device/Browser)。 diff --git a/zh-cn/application-dev/faqs/faqs-device-management.md b/zh-cn/application-dev/faqs/faqs-device-management.md deleted file mode 100644 index 47a73b6ff7ddf778173d784399ddb8c85b26f6f4..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-device-management.md +++ /dev/null @@ -1,54 +0,0 @@ -# 设备管理开发常见问题 - -## 如何获取设备的dpi值 - -适用于:OpenHarmony 3.2 Beta5,API9 Stage模型 - -**问题现象** - -获取设备的dpi信息。 - -**解决措施** - -导入@ohos.display包,通过getDefaultDisplaySync方法获取。 - -**示例代码** - -``` -import display from '@ohos.display'; -let displayClass = null; -try { - displayClass = display.getDefaultDisplaySync(); - console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); -} catch (exception) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); -} -``` - -## 如何获取当前运行设备类型 - -适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 - -导入\@ohos.deviceInfo包,然后通过deviceInfo.deviceType获取设备类型。 - -参考文档:[设备信息](../reference/apis/js-apis-device-info.md) - -## 如何获取设备系统版本 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过[deviceInfo](../reference/apis/js-apis-device-info.md)对象的osFullName属性获取设备系统版本。 - -## OpenHarmony设备如何获取UDID? - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -1. 如果想获取连接设备的udid,可使用 hdc shell bm get --udid命令; - -2. 如果想在代码中获得,参考文档 [udid](../reference/apis/js-apis-device-info.md) 。 - -## 开发快捷键功能 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -快捷键功能开发请使用组合按键api,具体可参考[组合按键(InputConsumer)](../reference/apis/js-apis-inputconsumer.md) diff --git a/zh-cn/application-dev/faqs/faqs-dfx.md b/zh-cn/application-dev/faqs/faqs-dfx.md index 25b326f67864fee3b1dc6616c5c56bc06bdc7736..565f2de33dfad073ca60a7260ebbe0164dd1e689 100644 --- a/zh-cn/application-dev/faqs/faqs-dfx.md +++ b/zh-cn/application-dev/faqs/faqs-dfx.md @@ -1,54 +1,28 @@ # DFX开发常见问题 -## 程序打开直接崩溃了,如何定位问题 +## hilog日志如何落盘存储 -使用于:OpenHarmony SDK 3.2.5.5版本 +适用于:OpenHarmony 3.2Beta API 9 -1. 通过业务日志打印,定位崩溃的代码位置。 +**问题现象** -2. 通过Crash文件查看报错信息,Crash文件路径是:/data/log/faultlog/faultlogger/。 +hilog日志如何落盘存储 -## UiTest测试框架无法获取控件问题 +**解决措施** -使用于:OpenHarmony SDK 3.2.5.5版本 +使用命令:hilog -w start -f ckTest -l 1M -n 5 -m zlib -j 11 -检查系统配置项 persist.ace.testmode.enabled 是开启。 +文件保存在目录:/data/log/hilog/ -通过hdc_std shell param get persist.ace.testmode.enabled 查看,若配置项为0, +参数解释: -可通过命令hdc_std shell param set persist.ace.testmode.enabled 1 开启配置。 +``` +-w 开启日志落盘任务,start表示开始,stop表示停止。 +-f 设置日志文件名 +-l 设置单个日志文件大小,单位可以是:B/K/M/G +-n 设置最大日志文件编号,当文件计数超过此编号时,日志文件旋转。范围:【2,1000】 +-m 设置日志文件压缩算法 +-j 任务ID,范围:[10,0xffffffffff) +更多参数含义请使用hilog --help查看。 +``` - -## C++代码中hilog的格式参数类型为%d或者%s时,日志打印为何显示private - -直接使用%d、%s等格式化参数时,标准系统默认使用private替换真实数据进行打印,防止数据泄露。如果需要打印出真实数据,需要使用%{public}d替换%d或者%{public}s替换%s。 - -## 如何解决hilog.debug日志无法打印 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过hdc_std命令 hdc_std shell hilog -b D开启调试开关 - -## 应用如何打印日志是使用hilog还是console,hilog接口参数domain的设置范围是什么 - -适用于:OpenHarmony SDK 3.2.2.5版本 - -推荐使用[hilog日志系统](../reference/apis/js-apis-hilog.md)进行日志打印,接口参数domain的设置范围可以参考[开发指南](../reference/apis/js-apis-hilog.md#hilogisloggable)。 - -## hilog日志打印长度限制是多少,是否可以配置 - -适用于:OpenHarmony SDK 3.2.2.5版本 - -日志打印的长度限制为1024个字符,该长度不能配置。 - -## hilog接口的tag参数是否支持用空格隔开的多个字符串 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -不支持。 - -## hilog中没有使用{public}标识的数据,如何打印真实数据 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -使用命令:hdc_std shell hilog -p off diff --git a/zh-cn/application-dev/faqs/faqs-distributed-data-management.md b/zh-cn/application-dev/faqs/faqs-distributed-data-management.md new file mode 100644 index 0000000000000000000000000000000000000000..935a31ebc67a2e390812c5745cd4aa924180082c --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-distributed-data-management.md @@ -0,0 +1,110 @@ +# 数据管理开发常见问题 + + +## 关系型数据库rdb中如何进行加密 + +适用于:Openharmony 3.1 Beta5 API 9 + +**解决措施** + +创建关系型数据库,可通过StoreConfig管理关系型数据库配置,其中encrypt属性指定数据库是否加密。 + +**参考链接** + +[关系型数据库](../reference/apis/js-apis-data-relationalStore.md#storeconfig) + +## 关系型数据库rdb中使用TRUNCATE TABLE语句无法清空表数据 + +适用于:OpenHarmony SDK 3.2.9.2版本,API9 + +**问题现象** + +通过TRUNCATE TABLE语句清空表数据时报错。 + +**解决措施** + +关系型数据库rdb使用Sqlite数据库, 它不支持 TRUNCATE TABLE 语句,建议使用delete语句,如:DELETE FROM sqlite\_sequence WHERE name = 'table\_name' ,另外发生该错误会抛出空异常。 + + + +## 关系型数据库rdb支持哪些数据类型 + +适用于:OpenHarmony SDK 3.0版本以上,API 9 Stage模型 + +**解决措施** + +关系型数据库rdb支持的数据类型有:number、string、boolean。其中number为数字类型,支持Double,Long,Float,Int,Int64,最大精度为十进制17位数字。 + +## 如何将PixelMap的数据存储到数据库中 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +存储PixelMap的数据 + +**解决措施** + +PixelMap应该被转换成相应的ArrayBuffer再放进数据库。 + +**参考链接** + +[readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1) + +## 如何获取rdb关系型数据库文件 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +关系型数据库的获取问题 + +**解决措施** + +开发者可使用hdc命令拷贝文件,其中文件路径为: /data/app/el2/100/database/包名/entry/rdb/ ,然后拷贝该路径下的文件,拷贝完成后,可以通过SQLite工具打开该数据库文件。 + +示例: + +``` + hdc file recv /data/app/el2/100/database//entry/db/ ./ +``` + +## 数据库在系统层面是否有锁机制,开发过程中是否需要关系数据库加锁问题 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +关系型数据库的加锁疑问 + +**解决措施** + +系统提供的分布式数据服务、关系型数据库和首选项均有锁机制,开发者无需关注。 + +## 在@ohos.data.storage轻量级存储中,调用put方法保存数据后,再重启应用后调用get方法为什么无法获取到保存的值 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +关系型数据库的保存以及重启时的调用 + +**解决措施** + +在storage轻量级存储中,调用put方法,只是将数据保存在内存中,并不会持久化到硬盘中,在退出应用后会将内存中的数据清空。如果想持久化到硬盘中,则在调用put方法后需要再调用flush或flushSync接口才行。数据持久化后重启应用时就可以通过get方法获取到之前保存的数据。 + + +## rdb关系型数据库中TEXT类型保存超长文本失败 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +API8版本rdb关系型数据库中TEXT类型保存超长文本失败 + +**解决措施** + +API9版本之前对TEXT文本存储长度限制在1024字节,所以会存在超长文本保存失败的情况。 + +在API9的版本中已经放开了长度限制。 + diff --git a/zh-cn/application-dev/faqs/faqs-distributed-device-profile.md b/zh-cn/application-dev/faqs/faqs-distributed-device-profile.md new file mode 100644 index 0000000000000000000000000000000000000000..83817dce8476795747a43b483f856a11e042cd02 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-distributed-device-profile.md @@ -0,0 +1,10 @@ +# 分布式设备开发常见问题 + +## OpenHarmony设备如何查看IMEI号 + +适用于:Openharmony 3.2 Beta5 API 9 + +**解决方案** + +通过HuksTag接口的HUKS\_TAG\_ATTESTATION\_ID\_IMEI参数可以获取。[参考文档](../reference/apis/js-apis-huks.md) + diff --git a/zh-cn/application-dev/faqs/faqs-event-notification.md b/zh-cn/application-dev/faqs/faqs-event-notification.md index b507f8f85ca6013c75c5f0559e06b504419f52ef..f4b06e9496b2a5a0d156363a603c339012d419e7 100644 --- a/zh-cn/application-dev/faqs/faqs-event-notification.md +++ b/zh-cn/application-dev/faqs/faqs-event-notification.md @@ -1,48 +1,151 @@ -# 公共事件与通知开发常见问题 +# 事件通知开发常见问题 -## emitter数据大小限制 +## 如何封装一个通用的commonEvent工具类 -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 +适用于OpenHarmony 3.1 Beta5 API 9 -emitter数据大小限制不超过10240。 +**问题现象** -## 如何实现点击Notification通知打开对应App +封装一个通用的commonEvent工具类:希望在创建订阅者的同时注册一个自定义的回调函数,然后在收到事件通知的同时能调用这个自定义的回调函数。 -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 +**解决措施** -通过配置Notification.publish发布通知接口的参数NotificationRequest中wantAgent属性实现 +``` +import commonEvent from '@ohos.commonEventManager'; -参考文档:[Notification](../reference/apis/js-apis-notification.md#notificationpublish)、[WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) +export class SubscribeEvent { + private static subscriber = null + // 自定义的回调函数变量 + private static callback = null + /** + * 创建订阅者 + * @param subscribeInfo 订阅事件 + * @callback 用户自定义回调函数 + */ + static createSubscriber(subscribeInfo, callback:(a,b)=>void) { + this.callback = callback + commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { + if (err) { + console.error('CreateSubscriberCallBack err = ' + JSON.stringify(err)) + } else { + this.subscriber = subscriber; + this.subscribe(this.subscriber) + console.info('Create subscriber succeed') + } + }) + } -示例: + /** + * 订阅公共事件 + * @param subscriber 订阅者 + */ + private static subscribe(subscriber) { + if (subscriber != null) { + commonEvent.subscribe(subscriber, (err, data) => { + if (err) { + console.error('subscribe err = ' + JSON.stringify(err)) + } else { + console.info('SubscribeCallBack data= ' + JSON.stringify(data)) + this.callback('hello callback', data) + } + }) + } else { + console.info("Need create subscriber") + } + } +} -```ts -import WantAgent from '@ohos.app.ability.wantAgent'; +@Entry +@Component +struct Faq10_1 { + @State message: string = '' -async function publishNotification() { - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + build() { + Row() { + Column() { + Text('订阅:' + this.message) + .fontSize(30) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let subscribeInfo = { + events: ["myEvent"] + }; + let callback = (a,b) => { + this.message = a + } + SubscribeEvent.createSubscriber(subscribeInfo,callback) + }) + Text('发布') + .fontSize(30) + .fontWeight(FontWeight.Bold) + .onClick(() => { + //公共事件相关信息 + let options = { + code: 0, //公共事件的初始代码 + data: "initial data",//公共事件的初始数据 + isOrdered: true //有序公共事件 + } + //发布公共事件回调 + function publishCB(err) { + if (err) { + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("publish"); + } + } + //发布公共事件 + try { + commonEvent.publish("myEvent", options, publishCB); + } catch (err) { + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); + } + }) } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, + .width('100%') + } + .height('100%') } - const wantAgent = await WantAgent.getWantAgent(wantAgentInfo) - let contentType = Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT; - await Notification.publish({ - content: { - contentType: contentType, - normal: { - title: "测试标题", - text: "测试内容", - } - }, - id: 1, - wantAgent: wantAgent - }) - prompt.showToast({ message: "发送成功" }) } ``` + +**参考链接** + +[公共事件模块](../reference/apis/js-apis-commonEventManager.md) + +## 如何让事件只在一个UIAbility实例中传递 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +应该如何实现事件只在一个UIAbility实例中订阅和触发 + +**解决措施** + +在UIAbility中使用EventHub订阅事件,EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件的能力 + +**代码示例** + +``` +import UIAbility from '@ohos.app.ability.UIAbility'; + export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on('myEvent', this.eventFunc); + // 结果: + // eventFunc is called,undefined,undefined + this.context.eventHub.emit('myEvent'); + // 结果: + // eventFunc is called,1,undefined + this.context.eventHub.emit('myEvent', 1); + // 结果: + // eventFunc is called,1,2 + this.context.eventHub.emit('myEvent', 1, 2); + } + eventFunc(argOne, argTwo) { + console.log('eventFunc is called, ${argOne}, ${argTwo}'); + }} +``` + +**参考链接** + +[使用EventHub进行数据](../application-models/uiability-data-sync-with-ui.md#使用eventhub进行数据通信) diff --git a/zh-cn/application-dev/faqs/faqs-file-management.md b/zh-cn/application-dev/faqs/faqs-file-management.md index 25c84da0e21e29965837eb1b287f1dce35cfb274..13dfb4b635a437205cfac776d39dbbb70df0c9ac 100644 --- a/zh-cn/application-dev/faqs/faqs-file-management.md +++ b/zh-cn/application-dev/faqs/faqs-file-management.md @@ -1,113 +1,23 @@ # 文件管理开发常见问题 -## fileio.rmdir是递归删除吗? +## 如何获取系统截屏图片的保存路径 -适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 +适用于OpenHarmony 3.2 Beta5 API 9 -是递归删除。 +**解决措施** -## 如何实现如果文件不存在则创建文件 +截图图片保存路径:/storage/media/100/local/files/Pictures/Screenshots/ -适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 +## 如何修改设备中文件目录为可读写权限 -可以通过调用函数fileio.open(filePath, 0o100, 0o666)来实现,第二个参数0o100表示若文件不存在,则创建文件。使用该选项时必须指定第三个参数 mode。 +适用于OpenHarmony 3.2 Beta5 API 9 -## 使用fileio进行文件复制,传入沙箱路径报错call fail callback fail, code: 202, data: json arguments illegal) +**问题现象** -适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 +使用hdc命令向设备上发送文件时,报错:权限不足。 -使用fileio模块进行文件复制时,文件路径前缀中不能以“file:///”开头。 +**解决措施** -## fileIo将数据写入流文件writeSync接口,length传参问题 +输入命令 hdc shell mount -o remount,rw /,正确执行无提示信息。 -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 -一个中文字符length为3,英文字符为1,当前buffer为string类型时,length项需要开发者手动换算;如果要写入全部内容,可直接忽略length项,length长度超长时会导致接口报错。 - -## 如何读取应用沙箱之外的文件 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -fileio中接口入参为path时只能是从context获取到的本应用沙箱路径,若要访问其他路径的数据,如公共数据图片视频等,需要通过数据所有者打开文件返回fd进行操作。 - -比如向mediaLibrary请求读取/写入某文件,然后通过打开代表特定文件的URI后返回的fd进行操作,操作步骤如下: - -1. 通过媒体查询获取文件fileAsset对象; - -2. 通过fileAsset.open方法返回的fd; - -3. 将fd作为fileIo接口参数进行文件读写操作; - -## 如何解决文件的中文内容乱码 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -读取文件内容的buffer数据后,通过util.TextDecoder对文件内容进行解码。 - -示例: - -``` -import util from '@ohos.util' -async function readFile(path) { - let stream = fileio.createStreamSync(path, "r+"); - let readOut = await stream.read(new ArrayBuffer(4096)); - let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true }); - let buffer = new Uint8Array(readOut.buffer) - let readString = textDecoder.decode(buffer, { stream: false }); - console.log("[Demo] 读取的文件内容:" + readString); -} -``` - -## 调用媒体库getAlbums方法,没有收到返回,也没有捕获到异常是为什么 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -getAlbums方法需要权限:ohos.permission.READ_MEDIA,从[OpenHarmony权限定义列表](../security/permission-list.md)查询知道ohos.permission.READ_MEDIA权限是需要用户授权。 - -1. 在module.json5中配置权限: - - ``` - "requestPermissions": [ - { - "name": "ohos.permission.READ_MEDIA" - } - ] - ``` - -2. 在MainAbility.ts -> onWindowStageCreate页面加载前需要增加用户授权代码: - - ``` - import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; - - private requestPermissions() { - let permissionList: Array = [ - "ohos.permission.READ_MEDIA" - ]; - let atManager = abilityAccessCtrl.createAtManager(); - atManager.requestPermissionsFromUser(this.context, permissionList) - .then(data => { - console.info(`request permission data result = ${data.authResults}`) - }) - .catch(err => { - console.error(`fail to request permission error:${err}`) - }) - } - ``` - -## 如何解决多次通过媒体库FetchFileResult获取文件应用崩溃 - -适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 - -通过FetchFileResult.close()方法,在FetchFileResult对象每次调用完,释放并使其失效。 - -## 在Stage模型下调用mediaLibrary.getMediaLibrary()接口,IDE报错 - -适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 - -Stage模型下,获取媒体库实例应该调用mediaLibrary.getMediaLibrary(context: Context)。 - -## 调用mediaLibrary.getFileAssets()接口返回的内容如何排序 - -适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 - -通过[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)对象参数里面的order属性进行排序。 diff --git a/zh-cn/application-dev/faqs/faqs-globalization.md b/zh-cn/application-dev/faqs/faqs-globalization.md new file mode 100644 index 0000000000000000000000000000000000000000..9c42388f55a0a8ecd34de67d069bca30d0a70660 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-globalization.md @@ -0,0 +1,118 @@ +# 资源管理开发常见问题 + +## 如何读取rawfile中的xml文件并转化为String类型 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +通过resourceManager的getRawFileContent接口获取xml数据,再通过String.fromCharCode将获取的数据转化为String类型。 + +**代码示例** + +``` +resourceManager.getRawFileContent('test.xml', (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + let xml = String.fromCharCode.apply(null, rawFile) + } +}); +``` + +**参考链接** + +[资源管理](../reference/apis/js-apis-resource-manager.md) + +## Stage模型下如何获取资源 + +适用于:OpenHarmony 3.1 Beta5 API 9 + +**解决措施** + +Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包。此方式不适用于FA模型。 + +**代码示例** + +``` +const context = getContext(this) as any +context + .resourceManager + .getString($r('app.string.entry_desc').id) + .then(value => { + this.message = value.toString() +}) +``` + +## 如何通过接口获取resource目录的路径 + +适用于:Openharmony 3.1 Beta5 API 9 + +**问题现象** + +希望获取resource目录的路径,从而使用文件管理接口操作文件。 + +**解决措施** + +由于应用以hap形式进行安装,安装完成后不会解压hap包,所以在程序运行时无法获取resource路径。 + +可以考虑如下两种方式获取资源文件: + +1. 使用\$r或者\$rawfile访问。适合静态访问,程序运行时不改变资源路径。 + +2. 使用ResourceManage访问。适合动态访问,程序运行时可动态改变资源路径。 + +**参考链接** + +[资源分类与访问](../quick-start/resource-categories-and-access.md) [资源管理](../reference/apis/js-apis-resource-manager.md) + +## 资源管理内的getPluralString方法获取value值有误 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +getPluralString接口获取value值有误,显示复数值(other)。 + +**解决措施** + +getPluralString接口只支持英文系统,不支持中文。 + +## 如何获取resources目录中自定义的string字段 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +使用ResourceManager模块的getStringValue方法获取。 + +**参考链接** + +[资源管理](../reference/apis/js-apis-resource-manager.md#getstringvalue9) + +## AppScope中的资源如图片,文字等如何引用 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +通过\$r\('app.type.name'\)的形式来引用,type代表资源类型,如color,string,media等,name代表资源命名。 + +## Resource类型如何转为String + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +Resource为string支持限定词目录使用this.context.resourceManager.getStringSync\(\$r\('app.string.test'\).id\),可以同步转换,不支持\$r\('app.string.test', 2\)方式。 + +**参考链接** + +[ResourceManager\(资源管理\)](../reference/apis/js-apis-resource-manager.md#getstringsync9) + +## form\_config.json文件中是否可以使用$引用常量 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +form\_config.json文件中不支持使用\$引用常量。 diff --git a/zh-cn/application-dev/faqs/faqs-graphics.md b/zh-cn/application-dev/faqs/faqs-graphics.md index 229d88e8eaee62dc6f72957a982dc06427e8438c..6f2c98331f3a50ca08c1de6460b91069c1c2bc73 100644 --- a/zh-cn/application-dev/faqs/faqs-graphics.md +++ b/zh-cn/application-dev/faqs/faqs-graphics.md @@ -1,90 +1,93 @@ # 图形图像开发常见问题 -## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -状态栏字体高亮属性的本质就只是让字体变成白色。调用window实例的setSystemBarProperties接口时,如果设置了状态栏内容颜色statusBarContentColor,就以开发者设置的颜色为准,isStatusBarLightIcon状态栏字体高亮属性就不生效;同理,如果设置了导航栏内容颜色navigationBarContentColor,isNavigationBarLightIcon导航栏字体高亮属性就不生效。 - -## 如何设置系统状态栏样式 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -导入\@ohos.window模块,开发者可以使用window.setSystemBarProperties()接口设置状态栏样式属性,达到自定义样式的效果。 - -## 如何隐藏状态栏,实现沉浸式效果 - -适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 - -1. 可以在onWindowStageCreate方法获取windowClass对象。 - - ```ts - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - console.log("[Demo] EntryAbility onWindowStageCreate") - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window.') - return; - } - // 获取到窗口对象 - globalThis.windowClass = data; - }) - } - ``` - -2. 设置窗口全屏,隐藏状态栏。 - - ```ts - globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); - }); - ``` +## 如何获取设备的dpi值 + +适用于:OpenHarmony 3.2 Beta5,API 9 Stage模型 + +**解决措施** + +导入@ohos.display包,通过getDefaultDisplaySync\(\)方法获取。 + +**代码示例** + +``` +import display from '@ohos.display'; +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); + console.info('Test densityDPI:' + JSON.stringify(displayClass.densityDPI)); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +} +``` + +## 如何隐藏状态栏实现沉浸式效果 + +适用于:OpenHarmony 3.2 Beta5,API 9 Stage模型 + +**解决措施** + +1. 可以在onWindowStageCreate方法获取windowClass对象。 + + ``` + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[Demo] MainAbility onWindowStageCreate") + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window.') + return; + } + // 获取到窗口对象 + globalThis.windowClass = data; + }) + } + ``` + +2. 设置窗口全屏,隐藏状态栏。 + + ``` + globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + }); + ``` + ## 如何获取窗口的宽高信息 -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 +适用于:OpenHarmony SDK 3.2 Beta5,API 9 Stage模型 -通过\@ohos.window模块,可以使用getProperties()接口获取窗口属性,然后通过窗口属性的windowRect获取窗口宽高信息 +**解决措施** -示例: +引入窗口模块@ohos.window,获取指定窗口对象Window后,在该对象上使用getWindowProperties\(\)获取窗口各个属性,在属性windowRect中获取窗口宽高信息。 +**代码示例** -```ts -let promise = windowClass.getProperties(); -promise.then((data)=> { - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data.windowRect)); -}).catch((err)=>{ - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); -}); ``` - -## 如何设置系统状态栏颜色 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -参考如下方式实现,示例: - - -```ts -window.getTopWindow(globalThis.mainContext).then(win => { - var systemBarProperties = { - statusBarColor: '#19B6FF', // 状态栏背景颜色 - navigationBarColor: '#19B6FF', // 导航栏背景颜色 - isStatusBarLightIcon: false, // 状态栏图标是否为高亮状态。 - isNavigationBarLightIcon: true, // 导航栏图标是否为高亮状态。 - statusBarContentColor: '#0D0500', // 状态栏文字颜色 - navigationBarContentColor: '#FFA500' // 导航栏文字颜色 - }; - win.setSystemBarProperties(systemBarProperties).catch(err => { - INDEX_LOGGER.info(`set System Bar Properties failed:${err}`) - }) -}) -.catch(err => { - INDEX_LOGGER.info(`get top window failed:${err}`) -}) +import window from '@ohos.window'; +let windowClass = null; +try { + let promise = window.getLastWindow(this.context); + promise.then((data)=> { + //获取窗口对象 + windowClass = data; + try { + //获取窗口属性 + let properties = windowClass.getWindowProperties(); + let rect = properties.windowRect; + //rect.width: 窗口宽度;rect.height: 窗口高度 + } catch (exception) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception)); + } + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + });} catch (exception) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); +} ``` + diff --git a/zh-cn/application-dev/faqs/faqs-ide.md b/zh-cn/application-dev/faqs/faqs-ide.md deleted file mode 100644 index 9d2cd9b7db09275aeedd988525bf663e7440d6b0..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-ide.md +++ /dev/null @@ -1,80 +0,0 @@ -# IDE使用常见问题 - -## 如何解决报错“npm ERR! code SELF_SIGNED_CERT_IN_CHAIN” - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -1. 在Dev Eco Studio terminal中执行npm config set strict-ssl=false; - -2. 在Dev Eco Studio terminal中执行npm install。 - -## 手工更新DevEco的SDK后,编译HAP报错“Cannot find module 'xxx\ets\x.x.x.x\build-tools\ArkTS-loader\node_modules\webpack\bin\webpack.js'” - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -1. 到SDK的ets\x.x.x.x\build-tools\ets-loader目录下执行npm install; - -2. 到SDK的js\x.x.x.x\build-tools\ace-loader目录下执行npm install。 完成步骤后重新编辑。 - -## 如何通过命令行打包HAP - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -方式一:运行hvigor assembleHap。 - -方式二:在工程的package.json的scripts中,定义构建任务脚本后,运行npm buildOhosHaps。“buildOhosHaps”字段可以自定义。 - - -``` -"scripts": { - "buildOhosHaps": "hvigor assembleHap" -}, -``` - -## DevEco创建新工程为什么选不到API9 - -适用于:DevEco Studio 3.0 Beta4 3.0.0.993(B06)版本 - -创建新工程的时候,首先要选择OpenHarmony页签再创建工程就可以选到API9。 - -## 下载时收不到回调且无法返回错误码 - -适用于:OpenHarmony所有版本 - -1. 重装hdc命令: hdc_std重裝 拉起 设备连接 - -2. 关闭日志限流 :hdc_std shell hilog -Q pidoff 打开" - -## IDE点击run按钮后,报错:error: unknow option. usage: aa start <options> - -适用于:OpenHarmony SDK 3.2.5.6版本,API9 Stage模型 - -报错原因:aa命令参数错误,执行打开应用操作报错。 - -有2种处理方法: - -1. 检查SDK版本和OS版本,确保SDK版本和OS版本一致。 - -2. 点击设备上app图标,手动启动app进行使用。 - -## IDE运行app报错:The hdc_std version of the SDK does not match the hdcd version of the device. - -适用于:OpenHarmony SDK 3.2.5.6版本,API9 Stage模型 - -hdc 和 hdcd版本不匹配 ,请更新IDE至Dev Eco 3.0.1.993及以上版本。 - -旧版本IDE检测不匹配会拦截安装,新版本IDE仅提醒不影响正常使用。 - -## 如何在OpenHarmony 的SDK中加入自定义的\*.d.ts文件 - -适用于:OpenHarmony SDK 3.1.7.7版本 , API8 FA模型 - -将dts文件命名为\@ohos.xxxx.d.ts , 放入SDK的路径中,重启IDE。 - -引入时会有代码提醒。 - -## 如何替换full-SDK - -适用于:OpenHarmony SDK 3.2.7.5版本 - -参考文档[full-SDK替换指南](../quick-start/full-sdk-switch-guide.md) diff --git a/zh-cn/application-dev/faqs/faqs-international.md b/zh-cn/application-dev/faqs/faqs-international.md deleted file mode 100644 index bbef24399ad9dfd0c33389edf7b4a66827b87b60..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-international.md +++ /dev/null @@ -1,19 +0,0 @@ -# 国际化开发常见问题 - -## AppScope中的资源如图片,文字等的引用方式是什么 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过$r('app.type.name')的形式来引用,type代表资源类型,如color,string,media等,name代表资源命名 - -## Resource类型转为string - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -Resource为string支持限定词目录使用this.context.resourceManager.getStringSync(\\$r('app.string.test').id),可以同步转换,不支持\$r('app.string.test', 2)方式。更多用法请参考[ResourceManager(资源管理)](../reference/apis/js-apis-resource-manager.md#getstringsync9) - -## form_config.json文件中使用$引用常量为什么不生效 - -适用于:OpenHarmony SDK 3.2.6.5, API9 Stage模型 - -form_config.json文件中不支持使用$引用常量。 diff --git a/zh-cn/application-dev/faqs/faqs-language.md b/zh-cn/application-dev/faqs/faqs-language.md deleted file mode 100644 index ff82d25aed8c3d9abe1a6e35ddf510fc0702fe9a..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-language.md +++ /dev/null @@ -1,286 +0,0 @@ -# 开发语言常见问题 - -## TS语言在生成器函数中编译失败,有哪些使用限制 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -TS语言的使用在生成器函数中存在以下限制: - -- 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用; - -- 这些表达式中的任何一个都不能导致任何应用程序状态变量(\@State、\@Link、\@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为; - -- 生成器函数内部不能有局部变量。 - -上述限制都不适用于事件处理函数(例如onClick)的匿名函数实现。 - -错误示例: - -``` -build() { - let a: number = 1 // invalid: variable declaration not allowed - Column() { - Text('Hello ${this.myName.toUpperCase()}') // ok. - ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place - } - buildSpecial() // invalid: no function calls - Text(this.calcTextValue()) // this function call is ok. -} -``` - -## 如何动态替换掉资源文件中的“%s”占位符 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -在应用中,通过"$r('app.string.xx')"的形式引用应用资源,$r的第二个参数可用于替换%s占位符。 - - 示例: - -``` -build() { - //do something - //引用的string资源,$r的第二个参数用于替换%s - Text($r('app.string.entry_desc','aaa')) - .fontSize(100) - .fontColor(Color.Black) - //do something -} -``` - -## 如何读取Resource中的xml文件并转化为String类型 - -适用于:OpenHarmony SDK 3.2.2.5版本, API9 Stage模型 - -1. 通过resourceManager的RawFile接口获取Uint8Array格式数据。 - -2. 通过String.fromCharCode将Uint8Array格式数据转化为String类型。 - -参考文档:[资源管理](../reference/apis/js-apis-resource-manager.md) - -示例: - - -``` -resourceManager.getRawFile(path, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - let xml = String.fromCharCode.apply(null, rawFile) - } -}); -``` - -## 如何将Resource资源对象转成string类型 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -通过\@ohos.resourceManager模块 resourceManager.getString()方法获取字符串。 - -参考文档:[资源管理](../reference/apis/js-apis-resource-manager.md#getstring) - -## class全局静态变量无法使用的问题 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -Page和Ability打包后会对import的对象分别形成两个不同的闭包,即打包出两个Global对象。因此,所引用的静态变量并不是同一对象,所以无法通过class静态变量方式定义全局变量。建议使用AppStorage进行全局变量管理。 - -参考文档:[应用程序的数据存储](../quick-start/arkts-state-mgmt-application-level.md) - -## Stage模型下如何获取资源 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包,此方式FA模型不适用。 - -示例: - - -``` -const context = getContext(this) as any -context - .resourceManager - .getString($r('app.string.entry_desc').id) - .then(value => { - this.message = value.toString() -}) -``` - -## 如何实现页面加载前从接口获取数据 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -aboutToAppear函数中使用异步接口获取页面数据,使用\@State修饰变量,数据获取完成后根据变量自动刷新页面。 - - -``` -@Entry -@Component -struct Test6Page { - // 数据获取成功,会自动刷新页面 - @State message: string = 'loading.....' - aboutToAppear(){ - // 模拟异步接口获取数据 - setTimeout(()=>{ - this.message = 'new msg' - },3000) - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - } - .width('100%') - } - .height('100%') - } -} -``` - -## worker线程与主线程是否运行在相同的全局上下文中 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -worker线程与主线程不在同一个上下文中,它们使用数据通信的方式交互。 - -## OpenHarmony上url编码使用哪个接口 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -使用全局函数encodeURI进行编码,使用decodeURI进行解码。例如空格字符,编码后为%20。 - -## OpenHarmony有解析xml的接口吗 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -使用ConvertXML的convert接口可以将xml文本解析为JavaScript对象。参考文档:[convertxml API文档](../reference/apis/js-apis-convertxml.md) - -## 应用图标一多设置 - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -借助资源限定词能力,实现应用图标的一多配置,具体使用参考[资源使用](../key-features/multi-device-app-dev/resource-usage.md) - -## Stage模型资源配置文件string.json文件中支持配置占位符吗 - -适用于:OpenHarmony SDK3.2.6.3, API9 Stage模型 - -资源配置文件string.json文件本身不支持配置占位符,可以在对应的页面中通过定义变量,在实际组件使用Resources和变量拼接的方式达到实现占位符的同等效果。 - -## OpenHarmony的systemTime.getCurrentTime()接口和JS的new Date().getTime()有区别吗 - -适用于:OpenHarmony SDK3.2.6.3, API9 Stage模型 - -systemTime.getCurrentTime(false)和new Date().getTime()一样,都是返回1970年1月1日至今的毫秒数;systemTime.getCurrentTime(true)返回1970年1月1日至今的纳秒数。两种方式都是系统时间。 - -## \@BuilderParam装饰器,组件传参问题 - -适用于:OpenHarmony SDK3.2.6.5, API9 Stage模型 - -对\@BuilderParam修饰的属性进行赋值时不带参数(如:content: this.specificParam),则此属性的类型需定义成无返回值的函数(如:\@BuilderParam content: () => void);若带参数(如:callContent: this.specificParam1("111")),则此属性的类型需定义成any(如:\@BuilderParam callContent: any;),具体用法请参考[BuilderParam](../quick-start/arkts-dynamic-ui-elememt-building.md#builderparam8)。 - -## ArkTS如何把string转成byte数组 - -适用于:所有版本 - -参考如下代码实现,示例: - - -``` -function stringToByte(str) { - var bytes = new Array(); - var len,c; - len = str.length; - for(var i = 0;i= 0x010000 && c<= 0x10FFFF) { - bytes.push(((c>>18) & 0x07) | 0xf0); - bytes.push(((c>>12) & 0x3F) | 0x80); - bytes.push(((c>>6) & 0x3f) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else if(c >= 0x000800 && c<= 0x00FFF){ - bytes.push(((c>>12) & 0x07) | 0xf0); - bytes.push(((c>>6) & 0x3F) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else if(c >= 0x000800 && c<= 0x0007FF) { - bytes.push(((c>>6) & 0x3F) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else { - bytes.push(c & 0xFF) - } - } - return bytes; -} -``` - -## 创建woker时报错“Too many wokers,the number of worker exceeds the maximum”如何处理 - -使用于:OpenHarmony SDK 3.2.6.5版本 - -这是因为每个应用的worker上限为7个,因此在worker使用完成后需要通过termiate方法释放worker。参考[worker开发指南](../reference/apis/js-apis-worker.md#terminate)。 - -## OpenHarmony推荐的多线程解决方案是什么 - -使用于:OpenHarmony SDK 3.2.6.5版本 API9 Stage模型 - -OpenHarmony推荐使用worker来处理多线程场景。 - -参考文档:[启动一个worker](../reference/apis/js-apis-worker.md) - -## 使用\@Builder装饰包含自定义组件的方法与普通方法的区别是什么 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -\@Builder装饰的方法中使用了自定义组件,那么该方法每次被调用时,对应的自定义组件均会重新创建。 - -## 状态管理中\@Watch监听,数组内对象属性变化无法触发watch回调函数 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -使用\@Watch监听的对象,只能监听一层数据变化,多层次数据变更无法监听,同\@State状态管理机制一致 - -## 如何监听\@State深层数据变化 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过\@Observed配合\@ObjectLink装饰符实现。 - -参考文档:[Observed和ObjectLink数据管理](../quick-start/arkts-state-mgmt-page-level.md#observed和objectlink数据管理) - -## 如何实现字符串编解码 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过util工具函数模块中的TextEncoder和TextDecoder进行解码。 - -参考文档:[TextEncoder](../reference/apis/js-apis-util.md#textencoder)、[TextDecoder](../reference/apis/js-apis-util.md#textdecoder) - -## 如何导入和导出namespace命名空间 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -- namespace导出 - - ``` - namespace Util{ - export function getTime(){ - return Date.now() - } - } - export default Util - ``` - -- namespace导入 - - ``` - import Util from './util' - Util.getTime() - ``` - -## worker线程中能进行关系型数据库的操作吗 - -适用于:OpenHarmony SDK 3.2.5.5版本, API9 Stage模型 - -不支持。 diff --git a/zh-cn/application-dev/faqs/faqs-media.md b/zh-cn/application-dev/faqs/faqs-media.md deleted file mode 100644 index 5233b35f5a04136ac8829bdf346f7262aa856ff0..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-media.md +++ /dev/null @@ -1,132 +0,0 @@ -# 媒体开发常见问题 - -## 如何设置前置拍照 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -1. 设置相机位置camera.CameraPosition.CAMERA_POSITION_FRONT - -2. 根据相机位置和类型创建CameraInput实例 - -参考文档:[相机管理](../reference/apis/js-apis-camera.md) - -示例: - -``` -//默认设置后置相机,通过设置isFrontCamera来切换相机 -let cameraId -let cameraInput -for(let cameraIndex = 0; cameraIndex < this.cameraArray.length; cameraIndex++) { - let faceType = this.cameraArray[cameraIndex].cameraPosition - switch(faceType) { - case camera.CameraPosition.CAMERA_POSITION_FRONT://前置相机 - if(this.isFrontCamera){ - cameraId = this.cameraArray[cameraIndex].cameraId - } - break - case camera.CameraPosition.CAMERA_POSITION_BACK://后置相机 - if(!this.isFrontCamera){ - cameraId = this.cameraArray[cameraIndex].cameraId - } - break - case camera.CameraPosition.CAMERA_POSITION_UNSPECIFIED: - default: - break - } -} -cameraInput = await this.cameraManager.createCameraInput(cameraId) -``` - -## 如何进行图片剪切 - -适用于:OpenHarmony 3.2.5.6版本,API9 Stage模型 - -1. **通过传入的uri创建图片源实例ImageSource对象。** - - ``` - let path = this.context.getApplicationContext().fileDirs + "test.jpg"; - const imageSourceApi = image.createImageSource(path); - ``` - -2. **设置解码参数,通过图片解码获取PixelMap图像对象,解码过程中同时支持图像处理操作。** - - 设置desiredSize支持按尺寸缩放,如果设置为全0,则不进行缩放。 - - 设置desiredRegion支持按矩形区域裁剪,如果设置为全0,则不进行裁剪。 - - 设置rotateDegrees支持旋转角度,以图像中心点顺时针旋转。 - - ``` - const decodingOptions = { - desiredSize: { - height:0, - width:0 - }, - //按矩形区域裁剪 - desiredRegion: { - size: { - height:100, - width:100 - }, - x:0, - y:0 - }, - //旋转90度 - rotate:90 - } - imageSourceApi.createPixelMap(decodingOptions).then(pixelMap => { - this.handlePixelMap(pixelMap) - }) - ``` - -3. 解码完成获取到PixelMap对象后,可以进行后续处理,比如渲染显示等。 - -## 如何申请设备上的媒体读写权限 - -适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 - -1. 在module.json5配置文件中配置媒体读写权限ohos.permission.READ_MEDIA和ohos.permission.WRITE_MEDIA。 - 示例: - - - ``` - { - "module" : { - "requestPermissions":[ - { - "name" : "ohos.permission.READ_MEDIA", - "reason": "$string:reason" - }, - { - "name" : "ohos.permission.WRITE_MEDIA", - "reason": "$string:reason" - } - ] - } - } - ``` - -2. 这两个权限的授权方式均为user_grant,因此需要调用requestPermissionsFromUser接口,以动态弹窗的方式向用户申请授权。 - - ``` - import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; - - let permissions: Array = ['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] - let atManager = abilityAccessCtrl.createAtManager(); - // context为调用方UIAbility的UIAbilityContext - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) - }).catch((error) => { - console.log("Failed to request permission from user with error: " + JSON.stringify(error)) - }) - ``` - -## MP4格式的视频为什么播放不了 - -适用于:OpenHarmonySDK 3.2.7.5版本,API9 Stage模型 - -暂不支持h.265编码格式的MP4视频播放。 - - -## 为什么视频创建至十几个时新创建的视频无法播放甚至崩溃 - -适用于:OpenHarmonySDK 3.2.7.5版本,API9 Stage模型 - -当前限制最多创建13个媒体播放实例。 diff --git a/zh-cn/application-dev/faqs/faqs-multimedia.md b/zh-cn/application-dev/faqs/faqs-multimedia.md new file mode 100644 index 0000000000000000000000000000000000000000..d2cec03590cf9ac47434dab0d24d911c2bd89835 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-multimedia.md @@ -0,0 +1,136 @@ +# 媒体开发常见问题 + +## 使用XComponent组件显示相机的预览输出流时,如何获取相机的帧数据 + +适用于:OpenHarmony 3.2 版本 API 9 Stage模型 + +**问题现象** + +目前接口不支持实时预览相机的帧数据,只能绑定一个动作来获取,比如拍照动作。 + +**解决措施** + +通过创建双路预览来实现。 + +1. Xcomponent来创建预览流。 + + ``` + // 获取PreviewOutput(预览输出类)实例 + const surfaceId = globalThis.mxXComponentController.getXComponentSurfaceld(); + this.mPreviewOutput = await Camera.createPreviewOutput(surfaceld) ; + ``` + +2. 使用imageReceiver来监听图像信息。 + + ``` + // 添加双路预览 + const fullWidth = this.mFullScreenSize.width; + const fullHeight = this.mFullScreenSize.height; + const imageReceiver = await image.createImageReceiver(fullwidth, fullHeight, + formatImage, capacityImage) ; + const photoSurfaceId = await imageReceiver.getReceivingSurfaceld(); + this.mPreviewOutputDouble = await Camera.createPreviewOutput ( photoSurfaceld) + ``` + + +## 如何获取前置摄像头的预览图像 + +适用于:OpenHarmony 3.2版本 API 9 Stage模型 + +**解决措施** + +1. 使用系统相机框架@ohos.multimedia.camera获取物理摄像头信息。 + + ``` + let cameraManager = await camera.getCameraManager(context); + let camerasInfo = await cameraManager.getSupportedCameras(); + let cameraDevice = this.camerasInfo[0]; + ``` + +2. 创建并启动物理摄像头输入流通道。 + + ``` + let cameraInput = await cameraManager.createCameraInput(cameraDevice); + await this.cameraInput.open(); + ``` + +3. 拿到物理摄像头信息查询摄像头支持预览流支持的输出格式,结合XComponent提供的surfaceId创建预览输出通道。 + + ``` + let outputCapability = await this.cameraManager.getSupportedOutputCapability(cameraDevice); + let previewProfile = this.outputCapability.previewProfiles[0]; + let previewOutput = await cameraManager.createPreviewOutput(previewProfile, previewId); + ``` + +4. 创建相机会话,在会话中添加摄像头输入流和预览输出流,然后启动会话,预览画面就会在XComponent组件上送显。 + + ``` + let captureSession = await cameraManager.createCaptureSession(); + await captureSession.beginConfig(); + await captureSession.addInput(cameraInput); + await captureSession.addOutput(previewOutput); + await this.captureSession.commitConfig() + await this.captureSession.start(); + ``` + + +## 如何设置相机焦距 + +适用于:OpenHarmony 3.2版本 API 9 Stage模型 + +**解决措施** + +1. 判断当前摄像头是否为前置摄像头,前置摄像头不支持设置焦距。 +2. 通过captureSession.getZoomRatioRange\(\)接口获取设备焦距设置支持的最大、最小范围。 +3. 判断目标焦距参数大小是否在步骤二获取的范围内,然后通过captureSession.setZoomRatio\(\)接口设置相机焦距。 + +## 如何后台播放音乐 + +适用于:OpenHarmony 3.2版本 API 9 Stage模型 + +**问题现象** + +无法后台播放音乐。 + +**解决措施** + +AVSession对媒体播放做了管控,当三方应用从前台切入后台或者进入锁屏状态,媒体播放会被强制暂停而应用不感知,如果要开发后台播放功能,应该启动后台任务管理的长时任务中播放音乐,同时接入AVSession能力,允许控制中心的播控面板控制三方应用的播放功能。 + +**参考链接** + +[后台任务管理的长时任务开发指导参考](../task-management/continuous-task-dev-guide.md) + +[AVSession开发指导参考](../media/using-avsession-developer.md) + + +## 创建多个视频组件无法播放 + +适用于:OpenHarmony 3.2版本 API 9 Stage模型 + +**问题现象** + +创建十几个视频组件无法播放甚至崩溃。 + +**解决措施** + +当前限制最多创建13个媒体播放实例。 + + +## 如何直接调起图片库 + +适用于:OpenHarmony 3.2版本 API 9 Stage模型 + +**解决措施** + +``` +let want = { + bundleName: 'com.ohos.photos', + abilityName: 'com.ohos.photos.MainAbility', + parameters: { + uri: 'detail' + } +}; +let context = getContext(this) as common.UIAbilityContext; +context.startAbility(want); +``` + diff --git a/zh-cn/application-dev/faqs/faqs-native.md b/zh-cn/application-dev/faqs/faqs-native.md deleted file mode 100644 index b67bb4162d0c840630f11cf78148266ad9d05780..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-native.md +++ /dev/null @@ -1,79 +0,0 @@ -# Native API使用常见问题 - -## Native API是否有类似Canvas绘制接口 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -Native API中的[Drawing](../reference/native-apis/_drawing.md)接口可以提供2D绘制功能。 - -## 运行Native HAP的时候,导入的命名空间报错Obj is not a valid object - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -检查模块根目录(注意不是工程根目录)下的build-profile.json5文件,如果设备是32位,需要在abiFilters参数中配置armeabi-v7a,如果设备是64位,需要在abiFilters参数中配置arm64-v8a。 - -## 运行Native HAP的时候,报错install parse profile prop check error - -适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 - -检查模块根目录(注意不是工程根目录)下的build-profile.json5文件,如果设备是32位,需要在abiFilters参数中配置armeabi-v7a,如果设备是64位,需要在abiFilters参数中配置arm64-v8a。 - -## 在Native代码中使用OH_LOG_Print打印日志,报错undefined symbol: OH_LOG_Print - -适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 - -需要修改CMakeLists.txt文件,在target_link_libraries最后追加libhilog_ndk.z.so。 - -## 如何获取到模块 package.json 文件中的 “version” 值 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -1. 在编译工具Hvigor脚本文件hvigorfile.js中,通过subModule.getPackageJsonPath方法获取module中package.json文件位置。 - -2. 使用nodejs能力读取package.json文件中version字段,写入build-profile.json5文件buildOption.cppFlags字段。 - -示例: - - -``` -// module hvigorfile.js -const subModule = require('@ohos/hvigor')(__filename) - -const fs = require("fs-extra") -const path = require("path") - -const packageJsonPath = subModule.getPackageJsonPath() -const buildProfilePath = path.resolve(packageJsonPath, '../build-profile.json5') -const packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) -let buildProfileData = fs.readFileSync(buildProfilePath, 'utf8') -buildProfileData = buildProfileData.replace(/\"cppFlags\"\:(.*)\,/, `"cppFlags": "-D NWEBEX_VERSION=${packageJsonData.version}",`) -fs.writeFileSync(buildProfilePath, buildProfileData, 'utf8') - -const ohosPlugin = require('@ohos/hvigor-ohos-plugin').hapTasks(subModule) // 该插件执行了C++编译任务,读取了build-profile.json5文件 - -module.exports = { - ohos: ohosPlugin -} -``` - - -``` -// hello.cpp 读取 -#define _NWEBEX_VERSION(v) #v -#define _NWEBEX_VER2STR(v) _NWEBEX_VERSION(v) - -static napi_value Add(napi_env env, napi_callback_info info) -{ - - napi_value fixed_version_value = nullptr; - napi_create_string_utf8(env, _NWEBEX_VER2STR(NWEBEX_VERSION), NAPI_AUTO_LENGTH, &fixed_version_value); - - return fixed_version_value; -} -``` - -## 如何遍历rawfiles中的文件 - -适用于:OpenHarmony SDK 3.2版本以上,API9 Stage模型 - -使用Native API中的OH_ResourceManager_OpenRawDir()方法获取到rawfile的根目录,然后对其进行遍历。可参考文档:[Native开发指导](../reference/native-apis/rawfile.md) diff --git a/zh-cn/application-dev/faqs/faqs-network-management.md b/zh-cn/application-dev/faqs/faqs-network-management.md new file mode 100644 index 0000000000000000000000000000000000000000..10f16b87af9246232c846b1b2a28f222dfeea38e --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-network-management.md @@ -0,0 +1,222 @@ +# 网络管理开发常见问题 + +## http网络请求中extraData支持的数据格式有哪些 + +适用于:OpenHarmony 3.2 Beta API 9 + +**解决措施** + +extraData代表发送请求的额外数据,支持如下数据: + +- 当HTTP请求为POST、PUT方法时,此字段为HTTP请求的content。 +- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。 +- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。 + +## http请求的错误码28是什么意思 + +适用于:OpenHarmony 3.2 Beta API 9 + +**问题现象** + +发起http请求后报错,错误码28。 + +**解决措施** + +错误码28代表CURLE\_OPERATION\_TIMEDOUT,操作超时。网络请求底层使用libcurl库,更多错误码可以查看相应文档。 + +**参考链接** + +[http常见响应码](../reference/apis/js-apis-http.md#responsecode)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) + +## http请求中response错误码返回6是什么意思 + +适用于:OpenHarmony 3.2 Beta API 9 + +**问题现象** + +发起http请求后,返回信息中response错误码为6。 + +**解决措施** + +错误码6表示地址无法解析主机,可以尝试ping一下request中的URL,确认是否可以ping通。 + +**参考链接** + +更多错误码参考[Response常用错误码](../reference/apis/js-apis-http.md#responsecode)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) + +## @ohos/axios三方件post请求queryParams参数场景下如何传参 + +适用于:OpenHarmony 3.2 Beta API 9 + +**问题现象** + +三方件@ohos/axios中发起post请求,以queryParams形式传递参数(将参数拼接在URL后)。 + +**解决措施** + +- 方式一:使用axios.post接口只接收一个参数,Url.URLSearchParams需要转成字符串拼接在url后面。 + + ``` + let params:Url.URLSearchParams = new Url.URLSearchParams() + params.append('ctl', 'sug') + params.append('query', 'wangjunkai') + params.append('cfrom', '1099a') + axios.post('http://10.100.195.234:3000/save?' + params.toString()).then(res => { + this.message = "request result: " + JSON.stringify(res.data); + }).catch(err => { + this.message = "request error: " + err.message; + }) + ``` + +- 方式二:使用axios接口只接收一个config对象,请求参数写在config对象的params中。 + + ``` + axios({ + url: 'http://10.100.195.234:3000/save', + method: 'post', + params: { + ctl: 'sug', + query: 'wangjunkai', + cfrom: '1099a' + } + }).then(res => { + this.message = "request result: " + JSON.stringify(res.data); + }).catch(err => { + this.message = "request error: " + err.message; + }) + ``` + + +## connection.getNetCapabilities\(mNetHandle\)无法正常返回结果 + +适用于:OpenHarmony 3.2 beta2 API 9 + +**问题现象** + +在网络连接管理中,调用connection.getNetCapabilities\(\)函数时无法取到数据。 + +**原因分析** + +this指向存在问题,用\(err,data\)=\>\{\}可以进入回调函数并且拿到返回结果数据,不能使用function\(err,data\),因为function声明的函数内存在自己的this,无法指向全局的this。 + +**解决措施** + +getNetCapabilities的第二个参数把function\(err,data\)改成\(err,data\)。 + +## http请求如何以json形式进行传输 + +适用于:OpenHarmony 3.2 Beta API 9 + +**解决措施** + +在HTTP协议消息头中,使用Content-Type来表示媒体类型信息。它被用来告诉服务端如何处理请求的数据,以及告诉客户端(一般是浏览器)如何解析响应的数据,比如显示图片,解析html或仅仅展示一个文本等。 + +设置该参数值为application/json,请求中的数据就会以json形式进行传输。 + +``` +this.options = { + method: http.RequestMethod.GET, + extraData: this.extraData, + header: { 'Content-Type': 'application/json' }, + readTimeout: 50000, + connectTimeout: 50000 +} +``` + +## 调用camera拍摄的照片如何上传到服务器 + +适用于:OpenHarmony 3.2 Beta5 API 9 + +**问题现象** + +应用调用摄像头拍照后如何将图片上传到服务器? + +**解决措施** + +启动应用,获取权限后系统会访问远程服务器,将拍摄照片保存在本地,通过上传接口将文件从个人手机传送至远程服务器。 + +**参考链接** + +[上传下载](../reference/apis/js-apis-request.md) + +## 手机网络正常,调用connection.hasDefaultNet\(\)接口失败 + +适用于:OpenHarmony 3.2 Beta API 9 + +**问题现象** + +手机可以上网,浏览器可以正常打开网页,但是hasDefaultNet这个方法调用失败,回调函数走到了失败的回调。 + +**解决措施** + +connection.hasDefaultNet 接口需要注明需要权限ohos.permission.GET\_NETWORK\_INFO + +权限申请链接:[访问控制授权申请](../security/accesstoken-guidelines.md) + +## 如何理解connection.getDefaultNet返回对象netHandle中的netId + +适用于:OpenHarmony 3.2 Beta API 9 + +**问题现象** + +netId的值如0、100分别代表什么含义? + +**解决措施** + +正常情况下,netHandle里的netId为0时表示没联网,大于等于100时为有网状态。 + +## 如何使用http请求从网络上获取数据 + +适用于:OpenHarmony 3.2 Beta API 9 + +**解决措施** + +使用@ohos.net.http模块来发起http网络请求。 + +1. 导入http模块,创建http请求对象。 +2. 设置请求地址URLl和参数,发起http请求。 +3. 获取请求结果response,并解析数据。 + +**参考链接** + +详细信息请参考:[http数据请求](../connectivity/http-request.md) + +## 如何使用JS封装网络请求 + +适用于:OpenHarmony 3.2 Beta API 9 + +**解决措施** + +OpenHarmony网络请求支持JS语言开发方式,可直接使用。具体使用参考如下文档:[网络连接](../reference/apis/js-apis-http.md) + +## 基于JS开发智能手表应用,如何编写网络请求 + +适用于:OpenHarmony 3.2 Beta API 9 + +**解决措施** + +OpenHarmony网络请求支持JS语言开发方式,可直接使用。具体使用参考如下文档:[网络连接](../reference/apis/js-apis-http.md) + +## 应用增加权限"ohos.permission.NOTIFICATION\_CONTROLLER",编译后无法启动 + +适用于:OpenHarmony 3.2 Beta API 9 + +**问题现象** + +启动报错:error: install failed due to grant request permissions failed. + +**解决措施** + +权限"ohos.permission.NOTIFICATION\_CONTROLLER为系统级“system core”权限,第三方应用无法获取该权限。 + +## WiFi模块中使用wifi.getIpInfo\(\).ipAddress报错 + +适用于:OpenHarmony 3.2Beta API 9 + +**问题现象** + +WiFi模块中使用wifi.getIpInfo\(\).ipAddress,报错Error: assertion \(wifiDevicePtr != nullptr\) failed: Wifi device instance is null + +**解决措施** + +权限不足。请先检查是否申请了相关的操作权限,权限相关信息可参考[权限管理](../security/accesstoken-overview.md)。 diff --git a/zh-cn/application-dev/faqs/faqs-sdk.md b/zh-cn/application-dev/faqs/faqs-sdk.md new file mode 100644 index 0000000000000000000000000000000000000000..ec62b97108d16192f52ebeea388e589a7f289dfc --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-sdk.md @@ -0,0 +1,41 @@ +# SDK使用常见问题 + +## cmake中arm64-v8a/armeabi-v7a这层目录的宏定义是什么 + +适用于:OpenHarmony 3.1 Beta5 API 9 + +**解决方案** + +arm64-v8a及armeabi-v7a目录如下所示: + +``` +entry +├─ libs +│ ├─ arm64-v8a +│ │ └─ libMyDemo.so +│ └─ armeabi-v7a +│ └─ libMyDemo.so +└─ src + └─ main + └─ cpp + └─ CMakeLists.txt +``` + +访问到目录的宏定义为:\$\{CMAKE\_CURRENT\_SOURCE\_DIR\}/../../../libs/$\{OHOS\_ARCH\}/xxxx.so + +CMAKE\_CURRENT\_SOURCE\_DIR:CMakeList.txt文件所在目录。 + +OHOS\_ARCH:设置应用程序二进制接口ABI,类型为 armeabi-v7a、arm64-v8a,默认值是 arm64-v8a。 + +**使用示例** + +CMakeLists.txt 中添加链接库。 + +``` +target_link_libraries(entry PUBLIC + libace_napi.z.so + libhilog_ndk.z.so + ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/${OHOS_ARCH}/libMyDemo.so +) +``` + diff --git a/zh-cn/application-dev/faqs/faqs-security.md b/zh-cn/application-dev/faqs/faqs-security.md new file mode 100644 index 0000000000000000000000000000000000000000..a84831563487cd51fb8a1b25c7b18a7fbe7ec2e4 --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-security.md @@ -0,0 +1,42 @@ +# 安全基础能力开发常见问题 + +## HUKS中AES GCM模式加密,单次最多可对多少字节数据加密 + +适用于:OpenHarmony 3.1 Beta5 API 9 + +**解决措施** + +HUKS中AES GCM模式加密时,单次最多可对64字节的数据进行加密。 + +**代码示例** + +``` +/* 进行密钥加密操作 */ +await huks.init(srcKeyAlias, encryptOptions).then((data) => { + console.info(`test init data: ${JSON.stringify(data)}`); + handle = data.handle; +}).catch((err) => { + console.info('test init err information: ' + JSON.stringify(err)); +}); +encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(0,64)); // 截取64字节 +await huks.update(handle, encryptOptions).then(async (data) => { + console.info(`test update data ${JSON.stringify(data)}`); + encryptUpdateResult = Array.from(data.outData); +}).catch((err) => { + console.info('test update err information: ' + err); +}); +encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice(64,80)); // 剩余数据 +``` + +## 在CryptoFramework中,打印Md的digest接口返回结果为乱码 + +适用于:OpenHarmony 3.1 Beta5 API 9 + +**问题现象** + +在CryptoFramework中,打印Md的digest接口返回结果显示为乱码,无法识别。 + +**解决措施** + +digest接口返回的Md计算结果DataBlob是Uint8Array类型,需要转成十六进制字符串再打印,也可以用网页在线版MD5加密工具验证结果。 + diff --git a/zh-cn/application-dev/faqs/faqs-sensor.md b/zh-cn/application-dev/faqs/faqs-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..19a1a3a9d4061be371c6e9a410f0726dd9d0a8de --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-sensor.md @@ -0,0 +1,8 @@ +# 泛Sensor服务开发常见问题 + +## 是否对个人开发者开放PPG和ECG血压监测传感器的的数据获取接口 + +适用于OpenHarmony 3.1 Beta5 API 9 + +PPG和ECG的血压监测传感器属于可穿戴设备传感器,传感器数据设计个人隐私数据,暂未对个人开发者开放接口。 + diff --git a/zh-cn/application-dev/faqs/faqs-startup.md b/zh-cn/application-dev/faqs/faqs-startup.md new file mode 100644 index 0000000000000000000000000000000000000000..6a19051ba01a6f61ffa1825133503d10b9c639ec --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-startup.md @@ -0,0 +1,44 @@ +# 启动恢复开发常见问题 + +## 如何获取设备系统版本 + +适用于Openharmony 3.2 Beta5 API 9 + +**解决措施** + +可通过[deviceInfo](../reference/apis/js-apis-device-info.md)对象的osFullName属性获取设备系统版本。 + +**代码示例** + +``` +import deviceInfo from '@ohos.deviceInfo' +let v = deviceInfo.osFullName +``` + +## OpenHarmony设备如何获取UDID + +适用于Openharmony 3.2 Beta5 API 9 + +**解决措施** + +- 方式一:通过命令行(hdc shell bm get --udid)查询。 +- 方式二:在代码中获得,请参考文档[udid](../reference/apis/js-apis-device-info.md)。 + +## 如何获取设备信息 + +适用于Openharmony 3.2 Beta5 API 9 + +可以使用deviceInfo模块获取设备信息,如设备型号等。 + +**参考链接** + +[设备信息](../reference/apis/js-apis-device-info.md) + +## 开发中如何实现App不被屏保中断 + +适用于Openharmony 3.2 Beta5 API 9 + +**解决方案** + +输入命令hdc shell "power-shell setmode 602" 可达到不息屏的效果。 + diff --git a/zh-cn/application-dev/faqs/faqs-third-fourth-party-library.md b/zh-cn/application-dev/faqs/faqs-third-fourth-party-library.md new file mode 100644 index 0000000000000000000000000000000000000000..887f1862bb7f9a4fe5208786bfa00109bdfdbc1b --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-third-fourth-party-library.md @@ -0,0 +1,72 @@ +# 三四方库使用常见问题 + +## 如何获取可用的三方库 + +适用于OpenHarmony 3.1 Beta5 API 9 + +通过ohpm可以获取的三四方库在Gitee上做了汇总([OpenHarmony上可直接使用的三方组件汇总](https://gitee.com/openharmony-tpc/tpc_resource)),针对于不同功能三方库内容做了分类,开发者可以根据需要进行参考。 + +## 网络相关的三方库有哪些 + +适用于OpenHarmony 3.1 Beta5 API 9 + +网络相关的三方库有[Axios](https://gitee.com/openharmony-sig/axios)、httpclient、okdownload等,具体分类可以参考[三四方库网络分类](https://gitee.com/openharmony-tpc/tpc_resource?_from=gitee_search#%E7%BD%91%E7%BB%9C)。 + +## 如何使用ohpm引入三四方库 + +适用于OpenHarmony 3.1 Beta5 API 9 + +**解决措施** + +- 方式一: + 1. 打开Terminal窗口,通过如下指令进入到entry目录。 + + ``` + cd entry + ``` + + 2. 以引入“dayjs”为例,执行以下指令进行安装。 + + ``` + ohpm install dayjs + ``` + + 3. 在对应的js文件中直接引用。 + + ``` + import dayjs from 'dayjs'; + ``` + + +- 方式二: + 1. 打开工程目录下的entry目录,找到该目录下的oh-package.json5文件。 + 2. 在oh-package.json5文件中写入想要安装的三方库,以“dayjs”为例,示例如下: + + ``` + { + "dependencies": { + "dayjs": "^1.10.4", + } + } + ``` + + 3. 打开Terminal窗口,通过如下指令进入到entry目录。 + + ``` + cd entry + ``` + + 4. 执行指令进行安装。 + + ``` + ohpm install + ``` + + 5. 在对应的js文件中直接引用。 + + ``` + import dayjs from 'dayjs'; + ``` + + + diff --git a/zh-cn/application-dev/faqs/faqs-third-party-library.md b/zh-cn/application-dev/faqs/faqs-third-party-library.md deleted file mode 100644 index a15136dfb734e626c50c6fb7875c842a3f9d0764..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-third-party-library.md +++ /dev/null @@ -1,74 +0,0 @@ -# 三四方库使用常见问题 - -## 报错“Stage model module … does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed. ”如何解决 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -三四方件未适配API9 Stage模型,无法使用。 - -## 项目是否支持传递依赖 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -比如项目A依赖项目B,项目B依赖项目C,那项目A是否能直接使用项目C提供的接口? - -不支持。由于项目打包使用npm工具,npm不支持传递依赖。可以在项目A增加项目C的依赖来解决问题。 - -## 如何获取可用的三方库 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -参见:[OpenHarmony上可直接使用的三方组件汇总](https://gitee.com/openharmony-sig/third_party_app_libs)。 - -## 网络相关的三方库有哪些 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -网络相关的三方库有[Axios](https://gitee.com/openharmony-sig/axios)。 - -## 如何使用npm引入三四方库 - - 适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 -- 方法一: - 1. 打开Terminal窗口,通过如下指令进入到entry目录。 - - ``` - cd entry - ``` - 2. 以引入“dayjs”为例,执行以下指令进行安装。 - - ``` - npm install dayjs --save - ``` - 3. 在对应的js文件中直接引用。 - - ``` - import dayjs from 'dayjs'; - ``` - -- 方法二: - 1. 打开工程目录下的entry目录,找到该目录下的package.json文件。 - 2. 在package.json文件中写入想要安装的三方npm,以“dayjs”为例,示例如下: - - ``` - { - "dependencies": { - "dayjs": "^1.10.4", - } - } - ``` - 3. 打开Terminal窗口,通过如下指令进入到entry目录。 - - ``` - cd entry - ``` - 4. 执行指令进行安装。 - - ``` - npm install - ``` - 5. 在对应的js文件中直接引用。 - - ``` - import dayjs from 'dayjs'; - ``` diff --git a/zh-cn/application-dev/faqs/faqs-ui-ets.md b/zh-cn/application-dev/faqs/faqs-ui-ets.md deleted file mode 100644 index 65d9f47c91cdc8bb2d9c680c03c55723ef4ce133..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-ui-ets.md +++ /dev/null @@ -1,648 +0,0 @@ -# ArkUI组件(ArkTS)开发常见问题 - -## 在Stage模型下,如何通过router实现页面跳转 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -1. 对于通过页面路由router实现页面跳转,首先要在main_pages.json配置文件中将所有跳转的页面加入pages列表; - -2. 页面路由需要在页面渲染完成之后才能调用,在onInit和onReady生命周期中页面还处于渲染阶段,禁止调用页面路由方法。 - -参考文档:[页面路由](../reference/apis/js-apis-router.md) - -## router通过调用push方法进堆栈的page是否会被回收 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -调用push进入堆栈的page不回收,调用back方法出栈后可以被回收。 - -## 如何将容器定位到屏幕的最底部? - -适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 - -可以使用Stack堆叠容器,设置子组件在容器内的最底部。 - - 示例: - -``` -build() { - Stack({alignContent : Alignment.Bottom}) { - //容器位于最底部 - Stack() { - Column() - .width('100%') - .height('100%') - .backgroundColor(Color.Yellow) - } - .width('100%') - .height('10%') - } - .width('100%') - .height('100%') - .backgroundColor('rgba(255,255,255, 0)') -} -``` - -## CustomDialog是否支持在TS文件中使用 - -适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 - -不支持,CustomDialog当前只支持在ArkTS的Page中使用。 - -参考文档:[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) - -## 如何将CustomDialog中的变量传递给Page页面中的变量 - -适用于:OpenHarmony SDK 3.2.2.5版本,API9 Stage模型 - -利用自定义的回调函数,当点击弹窗的confirm按钮时,将data数据从自定义弹窗组件中传递给当前的page的页面。 - -示例: - - -``` -// 弹窗组件 -@CustomDialog -struct MyDialog { - controller: CustomDialogController - title: string - confirm: (data: string) => void - data: string = '' - - build() { - Row() { - Column({ space: 10 }) { - Text(this.title) - .fontSize(30) - .fontColor(Color.Blue) - TextInput({ placeholder: "输入内容", text: this.data }) - .onChange((data) => { - this.data = data // 获取输入框数据 - }) - Button('confirm') - .onClick(() => { - this.confirm(this.data) // 将输入框数据通过回调函数传给主页面 - this.controller.close() - }).backgroundColor(0xffffff).fontColor(Color.Red) - }.width("50%") - }.height("50%") - } -} - -// main页面 -@Entry -@Component -struct DialogTest { - @State dialogTitle: string = '' - @State dialogData: string = '' - dialogController: CustomDialogController = new CustomDialogController({ - builder: MyDialog({ - title: this.dialogTitle, // 绑定数据 - data: this.dialogData, - confirm: this.confirm.bind(this) // 绑定自定义的回调函数,这里要修改this的指向 - }) - }) - - confirm(data: string) { - this.dialogData = data - console.info(`recv dialog data: ${data}`) // 获取弹窗输入的信息 - } - - build() { - Row() { - Column({ space: 10 }) { - Button('点击打开弹窗') - .onClick(() => { - this.dialogTitle = '弹窗' - this.dialogController.open() - }) - Text(`接受弹窗的数据:`) - .fontSize(20) - TextInput({ placeholder: "输入内容", text: this.dialogData }) - .width("50%") - .onChange((data) => { - this.dialogData = data // 获取输入框数据 - }) - }.width("100%") - }.height("100%") - } -} -``` - -## List组件上添加了Text组件后,List组件无法拖动到底部 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -在List的父容器加上代码layoutWeight(1)。原理:List属于可滚动容器组件,默认高度是占满全屏幕高度,当出现其他固定高度的组件占领了屏幕的部分高度时,需要开发人员显性的指定List组件占满剩余高度,而不是全屏幕高度。 - -## 栅格布局子组件如何居中? - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -GridContainer内子组件默认水平左对齐,居中显示可以参考以下处理方式: - -内部嵌套布局组件Row,设置Row属性justifyContent(FlexAlign.Center),内部嵌套子组件可保持居中显示,参考[栅格布局](../reference/arkui-ts/ts-container-gridcontainer.md)文档。 - - 示例: - -``` -GridContainer({ sizeType: SizeType.SM, columns: 12 }) { - Row() { - Text('1') - .useSizeType({ - sm: { span: 4, offset: 0 }, - }) - .backgroundColor(0x46F2B4) - }.justifyContent(FlexAlign.Center) // 该属性设置使子组件居中显示 -} -``` - -## 如何获取状态栏和导航栏高度? - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -在加载窗口内容之前,采用systemAvoidAreaChange事件监听。 - - 示例: - -```ts -import Window from '@ohos.window'; -import UIAbility from '@ohos.app.ability.UIAbility'; - -/** - * 设置沉浸式窗口,并获取状态栏和导航栏高度 - * @param mainWindow 主窗口对象 - */ -async function enterImmersion(mainWindow: window.Window) { - mainWindow.on("systemAvoidAreaChange", (area: window.AvoidArea) => { - AppStorage.SetOrCreate("topHeight", area.topRect.height); - AppStorage.SetOrCreate("bottomHeight", area.bottomRect.height); - }) - await mainWindow.setFullScreen(true) - await mainWindow.setSystemBarEnable(["status", "navigation"]) - await mainWindow.sArkTSystemBarProperties({ - navigationBarColor: "#00000000", - statusBarColor: "#00000000", - navigationBarContentColor: "#FF0000", - statusBarContentColor: "#FF0000" - }) -} -export default class EntryAbility extends UIAbility { - // do something - async onWindowStageCreate(windowStage: window.WindowStage) { - let mainWindow = await windowStage.getMainWindow() - await enterImmersion(mainWindow) - windowStage.loadContent('pages/index') - } - // do something -} -``` - -## 在容器组件嵌套的场景下,如何解决手势拖拽事件出现错乱的问题 - -适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 - -gesture的属性distance默认值是5,把gesture的属性distance设成1就可以解决。 - -## 如何获取组件的高度 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -组件宽高变化可通过onAreaChange组件区域变化事件获取。 - -示例: - - -```ts -Column() { - Text(this.value) - .backgroundColor(Color.Green).margin(30).fontSize(20) - .onClick(() => { - this.value = this.value + 'Text' - }) - .onAreaChange((oldValue: Area, newValue: Area) => { - console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`) - this.size = JSON.stringify(newValue) - }) -``` - -## 如何获取List组件的偏移量 - -适用于:OpenHarmony SDK 3.2.3.5版本,API9 Stage模型 - -List组件绑定Scoller控制器,通过currentOffset方式获取当前的滚动偏移量。 - -示例: - - -```ts -Column() { - List({ space: 20, initialIndex: 0,scroller: this.scroller}) { - ForEach(this.arr, (item) => { - ListItem() { - Text('' + item) - .width('100%').height(100).fontSize(16) - .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) - }.editable(true) - }, item => item) - } - .listDirection(Axis.Vertical) // 排列方向 - .editMode(this.editFlag) - .onScroll((xOffset: number, yOffset: number) => { - console.info("yOffset======="+this.scroller.currentOffset().yOffset) - }) -}.width('100%') -``` - -## 页面使用router携带param跳转后,下一个页面如何获取param - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - - -```ts -// 3.1.5.5版本之前,取值方式为:router.getParams().key -private value: string = router.getParams().value; -// 从3.1.6.5版本起,取值方式为:router.getParams()['key'] -private value: string = router.getParams()['value']; -``` - -## RichText组件是否支持跳转到本地page页面 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -不支持。 - -## 使用router或Navigator实现页面跳转时,如何关闭页面间转场动效 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -1. 参考[页面间转场示例](../reference/arkui-ts/ts-page-transition-animation.md#示例)在当前页面和目标页面中定义pageTransition方法。 - -2. 将页面入场组件PageTransitionEnter和页面退场组件PageTransitionExit的动效参数duration都设置为0。 - -## UI开发中,像素单位如何选择 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -Vp保证了不同分辨率下 视觉效果的等价性,比如一个图标,在不同分辨率下都是视觉效果是等价。 - -lpx相当于百分比视图,按比例扩大或者缩小。 - -如果关注Item等效性的,比如按钮、文字、列表基本上都是VP;比如关注布局,比如1/2之类的网格,lpx更好。 - -## ArkTS中颜色的格式说明 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -颜色可以使用两种格式,例如 0x7F000000 或者 '\#7F000000' ,其中前两位是透明度,后六位是RGB。 - - -```ts -fontColor(0x7F000000) -fontColor( '#7F000000' ) -``` - -## 如何在Page页面中监听返回操作 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -在Page页面返回时,系统会调用\@Entry修饰的自定义组件的onBackPress()回调,可以在回调函数中实现相关业务诉求。参考[自定义组件生命周期回调函数](../ui/ui-ts-custom-component-lifecycle-callbacks.md) - -## TextInput组件密码模式下,右边的眼睛图标是否支持自定义? - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -TextInput组件设置type为InputType.Password时,右侧出现眼睛图标,showPasswordIcon控制图标显示隐藏,不支持自定义。更多信息可参考文档:[TextInput组件](../reference/arkui-ts/ts-basic-components-textinput.md) - -## Image图片加载目前只能加载https的,不能加载http的 - -适用于:OpenHarmony SDK3.2.5.5, API9 Stage模型 - -http是不安全的,会被白名单过滤掉,建议使用https。 - -## TextView布局设置间距与显示界面不符合 - -适用于:OpenHarmony SDK3.2.5.5, API9 Stage模型 - -TextView默认设置align属性为居中,文本从左到右显示,需要设置align属性为Start。 - -## constraintSize尺寸设置不生效 - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -constraintSize约束组件尺寸时,子组件内设置百分比宽度,例如width('100%')会采用constraintSize约束中的最大宽乘百分比,导致撑开组件,看起来constraintSize设置没生效 - -## 如何将背景颜色设置为透明 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -将backgroundColor设置为 '\#00000000' 。 - -## Scroll组件滚动到达不了最底部 - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -Scroll组件在未设置高度情况下,默认为窗口高度,当滚动区域外存在其他组件时,滚动底部区域会出现遮挡,需要设置Scroll高度,或者使用Flex布局限制Scroll高度 - -## 输入框组件TextInput回车事件onSubmit使用 - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -onSubmit事件在回车键或软键盘回车触发该回调,参数为当前软键盘回车键类型,通过enterKeyType属性可以设置输入法回车键类型,软键盘回车键样式需要输入法的支持,具体文档参考[Textinput组件](../reference/arkui-ts/ts-basic-components-textinput.md) - -## 页面路由时,页面栈内的数量限制是多少 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -页面路由栈支持的最大页面数量是32,当超出此限制时,使用router.push接口页面无法完成跳转 。 - -## ArkUI是否支持通过代码动态创建组件 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -支持使用[条件渲染](../quick-start/arkts-rendering-control.md#条件渲染)和[循环渲染](../quick-start/arkts-rendering-control.md#循环渲染)等方式进行动态创建组件。 - -## 页面路由携带PixelMap对象参数,跳转页面无法获取 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -页面路由只支持普通对象类型,普通JSON数据结构,可以采用localStorage存储PixelMap对象,在跳转页面获取 - -## TextInput组件在onEditChange激活的时候通过.caretPosition(0)让光标回到起点 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -onEditChange事件在输入框聚焦时触发,这时光标位置和手势触发位置有关,在使用caretPosition同步处理无法改变光标位置,需要使用异步处理,在setTimeout中执行可以进行 - -## TextInput是否有方法设置内容为全部选中 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -TextInput组件暂不支持设置内容全选。 - -## input的输入框的type属性是date,但无法选择时间 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -input 组件的 type 设置为 date,只是会有相关格式提示,本质上还是输入控件,如果需要实现日期选择效果,需要使用 picker 组件。 - -## ArkTS TextInput输入时,弹出的输入法框把页面布局挤压变形 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -用Flex布局就会有挤压变形情况,改成Column布局就不会产生挤压 - -## 子组件使用\@Link修饰成员变量时,父组件传值如何传值 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -子组件使用\@Link修饰时,父组件传值需要添加"$" - -示例: - - -``` -@Component -struct FoodImageDisplay { - @Link imageSrc: Resource - - build() { - Stack({ alignContent: Alignment.BottomStart }) { - Image(this.imageSrc) - .objectFit(ImageFit.Contain) - Text('Tomato') - .fontSize(26) - .fontWeight(500) - .margin({ left: 26, bottom: 17.4 }) - } - .backgroundColor('#FFedf2f5') - .height(357) - } -} - -@Entry -@Component -struct FoodDetail { - - @State imageSrc: Resource = $r('app.media.Tomato') - - build() { - Column() { - FoodImageDisplay({imageSrc:$imageSrc}) - } - .alignItems(HorizontalAlign.Center) - } -} -``` - -## 如何多个pageAbility之间共享变量 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -1. 可以使用轻量级数据库 - -2. 可以使用持久化数据管理 - -3. 可以使用emitter事件通信 - - -## 如何自定义Video组件控制栏样式 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -1. 通过设置属性controls为false关闭默认控制栏 - -2. 设置Video组件的controller - -3. 通过ArkTS实现自定义的控制栏,并通过VideoController控制视频播放 - -## 对ArkTS组件多次更新时如何优化性能 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过将需要更新的ArkTS组件抽离成自定义组件,并更新该自定义组件内\@State绑定的变量,以此实现组件的局部刷新。 - -## 如何优化Tab组件性能 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -Tab组件处于某一页签时。其他页签并不会被系统卸载,所以会占用部分内存。可以通过if渲染控制判断当前页签是否是需要显示的页签,若不是则不加载,以此来实现卸载其他不显示的页签并释放这部分内存。 - -## 如何设置组件不同状态下的样式 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过设置组件的多态样式,实现组件不同状态(无状态、按下、禁用、聚焦、点击)的样式 - -参考文档:[多态样式](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) - -## 焦点事件onBlur/onFocus回调无法触发 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -焦点事件默认情况下需要外接键盘的Tab键,或方向键触发,点击触发焦点事件需要添加焦点控制属性focusOnTouch - -参考文档:[焦点控制](../reference/arkui-ts/ts-universal-attributes-focus.md) - -## Scroll内Flex加宽高与滑动冲突 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -Scroll支持单个子组件,子组件高度应由内容高度决定,当内容中存在异步加载的图片组件导致滚动布局异常时,可约束子组件最小高度constraintSize({ minHeight: '100%' }) - -## 页面路由跳转后如何阻止其返回原页面 - -适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 - -通过router.clear()接口清空页面栈中的所有历史页面,保留当前页面作为栈顶页面。 - -参考文档:[页面路由](../reference/apis/js-apis-router.md) - -## 如何实现将TextInput组件内容进行一次性清空 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -可以参考如下实现: - - -``` -struct Index { -@State text: string = 'Hello World' -controller: TextInputController = new TextInputController() - build() { - Row() { - Column() { - TextInput({ placeholder: 'Please input your words.', text: this.text, - controller:this.controller}).onChange((value) => { - this.text = value - }) - Button("Clear TextInput").onClick(() => { - this.text = ""; - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -## Tabs组件在点击Tab项时是否支持禁止切换 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -不支持。 - -## 使用 \@state修饰成员变量“id”会报错,报错原因:TypeError: cannot read property 'get' of undefined - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -id添加为唯一值,成为关键字。 - -## 基于OpenHarmony开发的应用,是否支持使用fontFamily属性设置不同的字体 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -基于OpenHarmony开发的应用,默认字体'HarmonyOS Sans',且当前只支持这种字体。 - -## Ability与UI页面推荐的数据交互方式是什么 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -推荐使用[LocalStorage](../quick-start/arkts-state-mgmt-application-level.md#localstorage)。 - -## 父组件如何与其孙子组件进行状态同步 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -- 方式一(推荐):使用\@Provide和\@Consume装饰器。在父组件使用\@Provide,在孙子组件使用\@Consume,可以实现父组件和孙子组件进行双向数据绑定。 - -- 方式二:使用\@State和\@Link装饰器。在父组件使用\@State,在每一层子组件(子组件和孙子组件)都使用\@Link。 - -## 字符超长中间显示省略号 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -代码示例 - - -``` -beautySub(str,len) { - var reg = /[\u4e00-\u9fa5]/g; - //减少字符,达到优化 - var slice = str.substring(0,len) - var charNum = (~~(slice.match(reg) && slice.match(reg).length)) - //减1是为了处理万一超过字符串,不显示多一个不是汉字的字符, - var realen = slice.length*2 - charNum-1 - return str.substr(0,realen) + (realen < str.length ? "..." : "") +str.substr(str.length-realen,str.length) -} -``` - -## richText 组件怎么加上滚动条 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -RichText底层是web,可以参考html的语法,在div上加上的overflow:auto的滚动样式。 - -## scroll里面套一个grid,怎么禁用grid的滑动事件? - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -可以通过onScrollBegin事件和scrollBy方法实现容器嵌套滚动。 - -参考:[容器嵌套滚动样例](../reference/arkui-ts/ts-container-scroll.md#示例2) - -## 能否去除自定义弹窗组件的白色背景 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -当前不支持。原因是当前的UI样式在框架后端写死了,无法更改。 - -## 组件背景图片设置backgroundImage方法是否支持svg图片格式 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -当前不支持。 - -## 自定义弹窗组件如何设置弹窗位置 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -自定义弹窗组件中参数alignment可以指定弹窗的位置。比如设置弹窗在底部:alignment : DialogAlignment.Bottom。 - -参考文档:[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) - -## scroller如何判断回弹动画的结束误差 - -适用于:OpenHarmony SDK 3.2.5.3版本,API8 FA模型 - -目前可以在触摸结束之后,计算同方向的变化,如果变化方向相反,说明出现回弹了,就规避不处理了。 - - -## 如何实现应用数据持久化存储 - -通过PersistentStorage类实现管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据。 - -参考文档:[持久化数据管理](../quick-start/arkts-state-mgmt-application-level.md#persistentstorage) - -示例: - - -``` -AppStorage.Link('varA') -PersistentStorage.PersistProp("varA", "111"); -@Entry -@Componentstruct Index { - @StorageLink('varA') varA: string = '' - build() { - Column() { - Text('varA: ' + this.varA).fontSize(20) - Button('Set').width(100).height(100).onClick(() => { - this.varA += '333' - }) - } - .width('100%') - .height('100%') - } -} -``` diff --git a/zh-cn/application-dev/faqs/faqs-ui-js.md b/zh-cn/application-dev/faqs/faqs-ui-js.md deleted file mode 100644 index 39e7c8ac2a5885f516e7e2f04f17e4976887f22b..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-ui-js.md +++ /dev/null @@ -1,94 +0,0 @@ -# UI框架(JS)开发常见问题 - -## 如何取出xml文件中对应的字段 - -适用于:OpenHarmony SDK 3.2.3.5版本, API9 Stage模型 - -convertxml中convert方法提供了转换xml文本为JavaScript对象的能力。 - -示例: - - -``` -import convertxml from '@ohos.convertxml'; -// xml格式的字符串 -let xml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; -let conv = new convertxml.ConvertXML(); -// 转换选项, 参考文档使用 -let options = { - trim: false, - declarationKey: "_declaration", - instructionKey: "_instruction", - attributesKey: "_attributes", - textKey: "_text", - cdataKey: "_cdata", - doctypeKey: "_doctype", - commentKey: "_comment", - parentKey: "_parent", - typeKey: "_type", - nameKey: "_name", - elementsKey: "_elements" -} -let result: any = conv.convert(xml, options) // 将xml文本转为JS对象 -console.log('Test: ' + JSON.stringify(result)) -console.log('Test: ' + result._declaration._attributes.version) // xml字符串中version字段信息 -console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // xml字符串中title字段内容 -``` - -参考文档:[xml转换JavaScript](../reference/apis/js-apis-convertxml.md) - -## 如何将时间转为时分秒格式 - -示例: - - -``` -export default class DateTimeUtil{ - /** - * 时分秒 - */ - getTime() { - const DATETIME = new Date() - return this.concatTime(DATETIME.getHours(),DATETIME.getMinutes(),DATETIME.getSeconds()) - } - /** - * 年月日 - */ - getDate() { - const DATETIME = new Date() - return this.concatDate(DATETIME.getFullYear(),DATETIME.getMonth()+1,DATETIME.getDate()) - } - /** - * 日期不足两位补充0 - * @param value-数据值 - */ - fill(value:number) { - return (value> 9 ? '' : '0') + value - } - /** - * 年月日格式修饰 - * @param year - * @param month - * @param date - */ - concatDate(year: number, month: number, date: number){ - return `${year}${this.fill(month)}${this.fill(date)}` - } - /** - * 时分秒格式修饰 - * @param hours - * @param minutes - * @param seconds - */ - concatTime(hours:number,minutes:number,seconds:number){ - return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}` - } -} - -``` \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-web-arkts.md b/zh-cn/application-dev/faqs/faqs-web-arkts.md deleted file mode 100644 index e295e4146d16fc5a890b694dd8ce410a7e1ae3c7..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/faqs/faqs-web-arkts.md +++ /dev/null @@ -1,79 +0,0 @@ -# ArkUI Web组件(ArkTS)开发常见问题 - -## Web组件domStorageAccess属性设置 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启,控制web网页中localStorage的使用,对sessionStorage未做控制 - -## Web组件加载的html页面内如何检测网络状态 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -1. 配置应用权限:ohos.permission.INTERNET 、 ohos.permission.GET_NETWORK_INFO - -2. html中通过window.navigator.onLine获取网络状态 - -## Web组件加载h5页面,首次加载无法设置拼接UserAgent参数 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -默认UserAgent通过WebController获取。一个WebController对象只能控制一个Web组件,且必须在Web组件和WebController绑定后,才能调用WebController上的方法,因此在初次加载前设置默认UserAgent + 自定义字符串拼接,可采用此方式: - -1. 使用\@State定义初始userAgent,绑定到Web组件; - -2. 在web组件的onUrlLoadIntercept回调中,通过WebController获取默认userAgent,修改Web组件绑定的userAgent。 - 参考代码如下: - - - ``` - @Entry - @Component - struct Index { - private controller: WebController = new WebController() - @State userAgentPa: string = '' - build() { - Row() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - .width('100%') - .userAgent(this.userAgentPa) - .onUrlLoadIntercept((event) => { - let userAgent = this.controller.getDefaultUserAgent(); - this.userAgentPa = userAgent + ' 111111111' - console.log("userAgent onUrlLoadIntercept: " + userAgent); - return false; - }) - } - .width('100%').alignItems(HorizontalAlign.Start).backgroundColor(Color.Green) - } - .height('100%') - } - } - ``` - -## 加载Lottie动画的逻辑应该写在onAppear函数中还是应该写在onReady函数中 - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -onAppear方法只是定位完Canvas的位置,onReady方法才是测量完成,加载动画的逻辑应该写在onReady函数中。 - -## 调用deleteJavaScriptRegister后是否需要调用refresh接口 - -适用于:所有版本 - -不需要。 - -## 页面如何传递数据给Web组件 - -适用于:OpenHarmony SDK 3.2.7.5版本,API9 Stage模型 - -1. 使用WebController创建两个消息端口。 - -2. 将消息端口1发送到HTML侧,由HTML侧保存并使用。 - -3. 将消息端口0在应用侧注册回调事件。 - -4. 使用应用侧的端口0给HTML侧消息端口1发送消息。 - -使用参考:[Web组件](../reference/arkui-ts/ts-basic-components-web.md#postmessage9) diff --git a/zh-cn/application-dev/faqs/faqs-window-manager.md b/zh-cn/application-dev/faqs/faqs-window-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..e2cb6b2fbd358cac246d421f01d69564800c880c --- /dev/null +++ b/zh-cn/application-dev/faqs/faqs-window-manager.md @@ -0,0 +1,65 @@ +# 窗口管理开发常见问题 + +## 如何获取状态栏和导航栏高度 + +适用于OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +在加载窗口内容之前,采用systemAvoidAreaChange事件监听。 + +**代码示例** + +``` +// MainAbility.ts +import window from '@ohos.window'; + +/** + * 设置沉浸式窗口,并获取状态栏和导航栏高度 + * @param mainWindow 主窗口对象 + */ +async function enterImmersion(mainWindow: window.Window) { + mainWindow.on("systemBarTintChange", (data) => { + let avoidAreaRect = data.regionTint[0].region; //data.regionTint是个数组,包含状态栏、导航栏的矩形区域坐标。 + }) + await mainWindow.setFullScreen(true) + await mainWindow.setSystemBarEnable(["status", "navigation"]) + await mainWindow.systemBarProperties({ + navigationBarColor: "#00000000", + statusBarColor: "#00000000", + navigationBarContentColor: "#FF0000", + statusBarContentColor: "#FF0000" + }) +} +export default class MainAbility extends Ability { + // do something + async onWindowStageCreate(windowStage: window.WindowStage) { + let mainWindow = await windowStage.getMainWindow() + await enterImmersion(mainWindow) + windowStage.loadContent('pages/index') + } + // do something +} +``` + +## 应用如何设置隐藏顶部的状态栏 + +适用于OpenHarmony 3.2 Beta5 API 9 + +**解决措施** + +在UIAbility的onWindowStageCreate的生命周期中设置setWindowSystemBarEnable接口即可。 + +**代码示例** + +``` +onWindowStageCreate(windowStage){ + windowStage.getMainWindowSync().setWindowSystemBarEnable([]) + ...... +} +``` + +**参考链接** + +[窗口基础能力文档](../reference/apis/js-apis-window.md) + diff --git a/zh-cn/application-dev/file-management/app-file-access.md b/zh-cn/application-dev/file-management/app-file-access.md index 40bccca794a8d096000d6f874d7e9ea441b4be59..e974394d85fb090deb66210fa3dd66a3958421af 100644 --- a/zh-cn/application-dev/file-management/app-file-access.md +++ b/zh-cn/application-dev/file-management/app-file-access.md @@ -138,6 +138,7 @@ async function readWriteFileWithStream() { ``` > **说明:** +> > 使用流接口时,需注意流的及时关闭。同时流的异步接口应严格遵循异步接口使用规范,避免同步、异步接口混用。流接口不支持并发读写。 ### 查看文件列表 diff --git a/zh-cn/application-dev/file-management/app-file-upload-download.md b/zh-cn/application-dev/file-management/app-file-upload-download.md index c63f4c52a15c7389d45641977402f50bb9b46472..6e04ff93d8700c4357172d72db1720eaa315cab8 100644 --- a/zh-cn/application-dev/file-management/app-file-upload-download.md +++ b/zh-cn/application-dev/file-management/app-file-upload-download.md @@ -7,8 +7,9 @@ 开发者可以使用上传下载模块([ohos.request](../reference/apis/js-apis-request.md))的上传接口将本地文件上传。文件上传过程使用系统服务代理完成。 > **说明:** +> > 当前上传应用文件功能,仅支持上传应用缓存文件路径(cacheDir)下的文件。 -> +> > 使用上传下载模块,需[申请相关权限](../security/accesstoken-guidelines.md):ohos.permission.INTERNET。 以下示例代码演示了如何将应用缓存文件路径下的文件上传至网络服务器。 @@ -64,13 +65,14 @@ try { 开发者可以使用上传下载模块([ohos.request](../reference/apis/js-apis-request.md))的下载接口将网络资源文件下载到应用文件目录。对已下载的网络资源文件,开发者可以使用基础文件IO接口([ohos.file.fs](../reference/apis/js-apis-file-fs.md))对其进行访问,使用方式与[应用文件访问](app-file-access.md)一致。文件下载过程使用系统服务代理完成。 > **说明:** +> > 当前网络资源文件仅支持下载至应用文件目录。 -> +> > 使用上传下载模块,需[申请相关权限](../security/accesstoken-guidelines.md):ohos.permission.INTERNET。 以下示例代码演示了如何将网络资源文件下载到应用文件目录: -``` +```ts // pages/xxx.ets // 将网络资源文件下载到应用文件目录并读取一段内容 import common from '@ohos.app.ability.common'; diff --git a/zh-cn/application-dev/file-management/app-sandbox-directory.md b/zh-cn/application-dev/file-management/app-sandbox-directory.md index f0724bdefac2eacbe3adbec572d27a237ba77c50..e5ead98a48c1e53f31760686c7bc6060d35c0932 100644 --- a/zh-cn/application-dev/file-management/app-sandbox-directory.md +++ b/zh-cn/application-dev/file-management/app-sandbox-directory.md @@ -10,7 +10,8 @@ 下图展示了应用沙箱下,应用可访问的文件范围和方式。 -**图1** 应用沙箱文件访问关系图   +**图1** 应用沙箱文件访问关系图 + ![Application sandbox file access relationship](figures/application-sandbox-file-access-relationship.png) ## 应用沙箱目录与应用沙箱路径 @@ -23,7 +24,8 @@ - 从实际物理路径推导物理路径与沙箱路径并不是1:1的映射关系,沙箱路径总是少于系统进程视角可见的物理路径。有些调试进程视角下的物理路径在对应的应用沙箱目录是无法找到的,而沙箱路径总是能够找到其对应的物理路径。 -**图2** 应用沙箱路径(不同权限与角色的进程下可见的文件路径不同)   +**图2** 应用沙箱路径(不同权限与角色的进程下可见的文件路径不同) +   ![Application sandbox path](figures/application-sandbox-path.png) ## 应用文件目录与应用文件路径 @@ -34,7 +36,8 @@ 在此主要介绍应用文件目录,如下图所示。应用文件目录下某个文件或某个具体目录的路径称为应用文件路径。应用文件目录下的各个文件路径,具备不同的属性和特征。 -**图3** 应用文件目录结构图   +**图3** 应用文件目录结构图 + ![Application file directory structure](figures/application-file-directory-structure.png) 1. 一级目录data/:代表应用文件目录。 @@ -54,17 +57,17 @@ Context上下文获取及上述应用文件路径的获取,详见[应用上下文Context](../application-models/application-context-stage.md)。 > **说明:** + > > - 禁止直接使用上图中四级目录之前的目录名组成的路径字符串,否则可能导致后续应用版本因应用文件路径变化导致不兼容问题。 - > > - 应通过Context属性获取应用文件路径,包括但不限于上图中绿色背景的路径。 应用文件路径具体说明及生命周期如下表所示。 **表1** 应用文件路径详细说明 - + | 目录名 | Context属性名称 | 类型 | 说明 | | -------- | -------- | -------- | -------- | - | bundle | bundleCodeDir | 安装文件路径 | 应用安装后的app的hap资源包所在目录;随应用卸载而清理。 | + | bundle | bundleCodeDir | 安装文件路径 | 应用安装后的app的hap资源包所在目录;随应用卸载而清理。不能拼接路径访问资源文件,请使用[资源管理接口](../reference/apis/js-apis-resource-manager.md)访问资源。 | | base | NA | 本设备文件路径 | 应用在本设备上存放持久化数据的目录,子目录包含files/、cache/、temp/和haps/;随应用卸载而清理。 | | database | databaseDir | 数据库路径 | 应用在el1加密条件下存放通过分布式数据库服务操作的文件目录;随应用卸载而清理。 | | distributedfiles | distributedFilesDir | 分布式文件路径 | 应用在el2加密条件下存放分布式文件的目录,应用将文件放入该目录可分布式跨设备直接访问;随应用卸载而清理。 | diff --git a/zh-cn/application-dev/file-management/dev-user-file-manager.md b/zh-cn/application-dev/file-management/dev-user-file-manager.md index 2875ae94323847cb2292cadcceefb66af40eea1e..6b122912ea91e184428f3e4e85654bc7d9daf3ba 100644 --- a/zh-cn/application-dev/file-management/dev-user-file-manager.md +++ b/zh-cn/application-dev/file-management/dev-user-file-manager.md @@ -14,11 +14,11 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 > **说明:** > > ohos.permission.FILE_ACCESS_MANAGER是使用文件访问框架接口的基础权限。 - > + > > ohos.permission.GET_BUNDLE_INFO_PRIVILEGED权限可以用于查询系统内当前支持的文件管理服务端应用信息。 2. 导入依赖模块。 - + ```ts import fileAccess from '@ohos.file.fileAccess'; import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; @@ -30,7 +30,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 开发者可以获取当前系统所有文件管理服务端管理的设备属性,也可以获取某个文件管理服务端管理的设备属性。应用开发者可以按需过滤设备。 在文件访问框架中,使用RootInfo用于表示设备的属性信息。以下示例可以获取所有设备的RootInfo。 - + ```ts // 创建连接系统内所有文件管理服务端的helper对象 let fileAccessHelperAllServer = null; @@ -71,7 +71,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 在文件访问框架中,使用FileInfo表示一个文件(目录)的基础信息。开发者可以使用listfile接口遍历下一级所有文件(目录)的迭代器对象;也可以通过scanfile过滤指定目录,获取满足条件的迭代器对象。 listfile和scanfile接口当前支持RootInfo对象调用,可用于支撑遍历下一级文件或过滤整个目录树。同时,接口也支持FileInfo对象调用,用于支撑遍历下一级文件或过滤指定目录。 - + ```ts // 从根目录开始 let rootInfo = rootinfos[0]; @@ -123,7 +123,6 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 5. 操作文件或目录。 开发者可以集成文件访问框架的接口,完成一些用户行为,比如删除文件(目录)、重命名文件(目录)、新建文件(目录)、移动文件(目录)等。以下示例展示了如何创建一个文件,其他接口请参见[API参考](../reference/apis/js-apis-fileAccess.md)。 - ```ts // 以本地设备为例 // 创建文件 diff --git a/zh-cn/application-dev/file-management/distributed-fs-overview.md b/zh-cn/application-dev/file-management/distributed-fs-overview.md index e9507db47ad53fe24e164ed054677adbcff24781..5777fa0b538108e1de72fc7143c5647a9abc4fe6 100644 --- a/zh-cn/application-dev/file-management/distributed-fs-overview.md +++ b/zh-cn/application-dev/file-management/distributed-fs-overview.md @@ -1,6 +1,6 @@ # 分布式文件系统概述 -分布式文件系统(hmdfs,Harmony Distributed File System)提供跨设备的文件访问能力,适用于如下场景: +分布式文件系统(hmdfs,OpenHarmony Distributed File System)提供跨设备的文件访问能力,适用于如下场景: - 两台设备组网,用户可以利用一台设备上的编辑软件编辑另外一台设备上的文档。 @@ -8,10 +8,8 @@ - 户外拍摄的照片,回家打开平板直接访问原设备拍摄的照片。 - hmdfs在分布式软总线动态组网的基础上,为网络上各个设备结点提供一个全局一致的访问视图,支持开发者通过基础文件系统接口进行读写访问,具有高性能、低延时等优点。 - ## 分布式文件系统架构 ![Distributed File System Architecture](figures/distributed-file-system-architecture.png) @@ -20,22 +18,22 @@ hmdfs在分布式软总线动态组网的基础上,为网络上各个设备结 - hmdfs:实现在内核的网络文件系统,包括缓存管理、文件访问、元数据管理和冲突管理等。 - 缓存管理 - - 设备分布式组网后,hmdfs提供文件的互访能力,但不会主动进行文件数据传输和拷贝。如果应用需要将数据保存到本地,需主动拷贝。 - - hmdfs保证Close-to-Open的一致性,即一端写关闭后,另外一端可以读取到最新数据,不保证文件内容的实时一致性。 - - 数据在远端写入,但是由于网络原因未及时回刷,文件系统会在下次网络接入时回刷本地,但是如果远端已修改则无法回刷。 + - 设备分布式组网后,hmdfs提供文件的互访能力,但不会主动进行文件数据传输和拷贝。如果应用需要将数据保存到本地,需主动拷贝。 + - hmdfs保证Close-to-Open的一致性,即一端写关闭后,另外一端可以读取到最新数据,不保证文件内容的实时一致性。 + - 数据在远端写入,但是由于网络原因未及时回刷,文件系统会在下次网络接入时回刷本地,但是如果远端已修改则无法回刷。 - 文件访问 - - 文件访问接口与本地一致([ohos.file.fs](../reference/apis/js-apis-file-fs.md))。 - - 如果文件在本地,则堆叠访问本地文件系统。 - - 如果文件在其他设备,则同步网络访问远端设备文件。 + - 文件访问接口与本地一致([ohos.file.fs](../reference/apis/js-apis-file-fs.md))。 + - 如果文件在本地,则堆叠访问本地文件系统。 + - 如果文件在其他设备,则同步网络访问远端设备文件。 > **说明:** > > symlink:不支持。 - 元数据管理 - - 分布式组网下,文件一端创建、删除、修改,另一端可以“立即”查看到最新文件,看到速度取决于网络情况。 - - 远端设备离线后,该设备数据将不再在本端设备呈现。但由于设备离线的感知具有延迟,可能会造成部分消息4s超时,因此开发者需要考虑接口的网络超时或一些文件虽然可以看到,但实际设备可能已离线的场景。 + - 分布式组网下,文件一端创建、删除、修改,另一端可以“立即”查看到最新文件,看到速度取决于网络情况。 + - 远端设备离线后,该设备数据将不再在本端设备呈现。但由于设备离线的感知具有延迟,可能会造成部分消息4s超时,因此开发者需要考虑接口的网络超时或一些文件虽然可以看到,但实际设备可能已离线的场景。 - 冲突处理 - - 本地与远端冲突 ,远端文件被重命名,看到的同名文件是本地同名文件,远端文件被重命名。 - - 远端多个设备冲突,以接入本设备ID为顺序,显示设备ID小的同名文件,其他文件被依次重命名。 - - 如果组网场景,目录树下已经有远端文件,创建同名文件,提示文件已存在。 - - 冲突文件显示_conflict_dev后依次加id,id从1自动递增。 - - 同名目录之间仅融合不存在冲突,文件和远端目录同名冲突,远端目录后缀加_remote_directory。 + - 本地与远端冲突 ,远端文件被重命名,看到的同名文件是本地同名文件,远端文件被重命名。 + - 远端多个设备冲突,以接入本设备ID为顺序,显示设备ID小的同名文件,其他文件被依次重命名。 + - 如果组网场景,目录树下已经有远端文件,创建同名文件,提示文件已存在。 + - 冲突文件显示_conflict_dev后依次加id,id从1自动递增。 + - 同名目录之间仅融合不存在冲突,文件和远端目录同名冲突,远端目录后缀加_remote_directory。 diff --git a/zh-cn/application-dev/file-management/file-access-across-devices.md b/zh-cn/application-dev/file-management/file-access-across-devices.md index 8c76f4ed742505d7255c6fe9cf00d7d054104edd..2e0443f9b0817c73cd082413e5bf40ea0931505c 100644 --- a/zh-cn/application-dev/file-management/file-access-across-devices.md +++ b/zh-cn/application-dev/file-management/file-access-across-devices.md @@ -1,9 +1,7 @@ # 跨设备文件访问 - 分布式文件系统为应用提供了跨设备文件访问的能力,开发者在多个设备安装同一应用时,通过[基础文件接口](app-file-access.md),可跨设备读写其他设备该应用分布式文件路径(/data/storage/el2/distributedfiles/)下的文件。例如:多设备数据流转的场景,设备组网互联之后,设备A上的应用可访问设备B同应用分布式路径下的文件,当期望应用文件被其他设备访问时,只需将文件移动到分布式文件路径即可。 - ## 开发步骤 1. 完成分布式组网。 @@ -14,7 +12,6 @@ 设备A上在分布式路径下创建测试文件,并写入内容。示例中的context的获取方式请参见[获取UIAbility的上下文信息](../application-models/uiability-usage.md#获取uiability的上下文信息)。 - ```ts import fs from '@ohos.file.fs'; @@ -38,7 +35,6 @@ 设备B上在分布式路径下读取测试文件。 - ```ts import fs from '@ohos.file.fs'; diff --git a/zh-cn/application-dev/file-management/file-management-overview.md b/zh-cn/application-dev/file-management/file-management-overview.md index 212697e0904ca1798c1d2804aff1f9ec910a2909..26c1f4c04bd78752520bf6414e3396f1cb11abf1 100644 --- a/zh-cn/application-dev/file-management/file-management-overview.md +++ b/zh-cn/application-dev/file-management/file-management-overview.md @@ -21,4 +21,5 @@ - [分布式文件系统](distributed-fs-overview.md):提供跨设备的文件访问能力。所谓跨设备,指文件不一定存储在本地设备或外置存储设备,而是通过计算机网络与其他分布式设备相连。 **图1** 文件分类模型示意图 + ![File classification model](figures/file-classification-model.png) diff --git a/zh-cn/application-dev/file-management/manage-external-storage.md b/zh-cn/application-dev/file-management/manage-external-storage.md index dc53a27fb2f1c07b4e6c4983ac9d6bc9a763f20b..3605bb615958975d445536bc24ff97399575171c 100644 --- a/zh-cn/application-dev/file-management/manage-external-storage.md +++ b/zh-cn/application-dev/file-management/manage-external-storage.md @@ -5,6 +5,7 @@ 外置存储设备的管理由StorageManager和StorageDaemon两个服务完成。StorageDaemon实现底层的的监听挂载等功能;StorageManager则对系统应用提供状态变更通知、查询和管理能力。 **图1** 外置存储设备管理示意图   + ![External storage device management](figures/external-storage-device-management.png) - 插入外卡时,StorageDaemon进程通过netlink监听获取到外卡插入事件,创建对应的磁盘设备以及卷设备,此时,已创建的卷设备状态为卸载状态(UNMOUNTED)。 @@ -19,7 +20,6 @@ - 当卷设备处于卸载状态时,拔出卷设备会删除相关卷设备信息,并发送COMMON_EVENT_VOLUME_REMOVED广播。 - ## 接口说明 外置存储设备管理相关API的详细介绍请参见[API参考](../reference/apis/js-apis-file-volumemanager.md)。 @@ -36,7 +36,6 @@ | usual.event.data.VOLUME_BAD_REMOVAL | id:卷设备ID
diskId:卷设备所属磁盘设备ID | | usual.event.data.VOLUME_EJECT | id:卷设备ID
diskId:卷设备所属磁盘设备ID
volumeState:卷设备状态 | - ## 开发步骤 开发者通过订阅卷设备相关的广播事件来感知外置存储的插入,通过广播传递的信息获取卷设备信息后可以对卷设备进行查询以及管理操作。 @@ -53,7 +52,6 @@ - 卷设备异常移除:"usual.event.data.VOLUME_BAD_REMOVAL" - 卷设备正在弹出:"usual.event.data.VOLUME_EJECT" - ```ts import CommonEvent from '@ohos.commonEventManager'; import volumeManager from '@ohos.file.volumeManager'; @@ -71,7 +69,7 @@ ``` 3. 收到广播通知后获取卷设备信息。 - + ```ts CommonEvent.subscribe(subscriber, function (err, data) { if (data.event === 'usual.event.data.VOLUME_MOUNTED') { diff --git a/zh-cn/application-dev/file-management/save-user-file.md b/zh-cn/application-dev/file-management/save-user-file.md index 72c3ae1d13d6372205381691527d644d166b22f3..4695c62d48a5b32e5ac22b35220d17617b6b5f53 100644 --- a/zh-cn/application-dev/file-management/save-user-file.md +++ b/zh-cn/application-dev/file-management/save-user-file.md @@ -8,13 +8,13 @@ ## 保存图片或视频类文件 1. 导入选择器模块。 - + ```ts import picker from '@ohos.file.picker'; ``` 2. 创建图库保存选项实例。 - + ```ts const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例 photoSaveOptions.newFileNames = ["PhotoViewPicker01.jpg"]; // 保存文件名(可选) @@ -22,7 +22,7 @@ 3. 创建图库选择器实例,调用[save()](../reference/apis/js-apis-file-picker.md#save)接口拉起FilePicker界面进行文件保存。 用户选择目标文件夹,用户选择与文件类型相对应的文件夹,即可完成文件保存操作。保存成功后,返回保存文档的URI。 - + ```ts const photoViewPicker = new picker.PhotoViewPicker(); photoViewPicker.save(photoSaveOptions) @@ -35,17 +35,16 @@ }) ``` - ## 保存文档类文件 1. 导入选择器模块。 - + ```ts import picker from '@ohos.file.picker'; ``` 2. 创建文档保存选项实例。 - + ```ts const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例 documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // 保存文件名(可选) @@ -58,7 +57,6 @@ > > 目前DocumentSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 - ```ts const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 documentViewPicker.save(documentSaveOptions) @@ -71,17 +69,16 @@ }) ``` - ## 保存音频类文件 1. 导入选择器模块。 - + ```ts import picker from '@ohos.file.picker'; ``` 2. 创建音频保存选项实例。 - + ```ts const audioSaveOptions = new picker.AudioSaveOptions(); // 创建文件管理器选项实例 audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // 保存文件名(可选) @@ -92,8 +89,7 @@ > **说明:** > > 目前AudioSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 - - + ```ts const audioViewPicker = new picker.AudioViewPicker(); audioViewPicker.save(audioSaveOptions) diff --git a/zh-cn/application-dev/file-management/select-user-file.md b/zh-cn/application-dev/file-management/select-user-file.md index 85169ccb70466e9f604445b72a78dd37297f1b5c..c1a9983bd0619492545269be343dd24ff7b6bb91 100644 --- a/zh-cn/application-dev/file-management/select-user-file.md +++ b/zh-cn/application-dev/file-management/select-user-file.md @@ -2,10 +2,8 @@ 终端用户有时需要分享、保存一些图片、视频等用户文件,开发者需要在应用中支持此类使用场景。此时,开发者可以使用OpenHarmony系统预置的[文件选择器(FilePicker)](../reference/apis/js-apis-file-picker.md),实现用户文件选择及保存能力。 - 根据用户文件的常见类型,文件选择器(FilePicker)分别提供以下接口: - - [PhotoViewPicker](../reference/apis/js-apis-file-picker.md#photoviewpicker):适用于图片或视频类文件的选择与保存。 - [DocumentViewPicker](../reference/apis/js-apis-file-picker.md#documentviewpicker):适用于文档类文件的选择与保存。 @@ -15,13 +13,13 @@ ## 选择图片或视频类文件 1. 导入选择器模块。 - + ```ts import picker from '@ohos.file.picker'; ``` 2. 创建图库选择选项实例。 - + ```ts const photoSelectOptions = new picker.PhotoSelectOptions(); ``` @@ -29,16 +27,15 @@ 3. 选择媒体文件类型和选择媒体文件的最大数目。 以下示例以图片选择为例,媒体文件类型请参见[PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes)。 - ```ts photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目 ``` 4. 创建图库选择器实例,调用[select()](../reference/apis/js-apis-file-picker.md#select)接口拉起FilePicker界面进行文件选择。 + 文件选择成功后,返回[PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult)结果集,可以根据结果集中URI进行文件读取等操作。 - ```ts const photoPicker = new picker.PhotoViewPicker(); photoPicker.select(photoSelectOptions) @@ -54,13 +51,13 @@ ## 选择文档类文件 1. 导入选择器模块。 - + ```ts import picker from '@ohos.file.picker'; ``` 2. 创建文档选择选项实例。 - + ```ts const documentSelectOptions = new picker.DocumentSelectOptions(); ``` @@ -70,8 +67,7 @@ > **说明:** > > 目前DocumentSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 - - + ```ts const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 documentViewPicker.select(documentSelectOptions) @@ -87,26 +83,27 @@ ## 选择音频类文件 1. 导入选择器模块。 - + ```ts import picker from '@ohos.file.picker'; ``` 2. 创建音频选择选项实例。 - + ```ts const audioSelectOptions = new picker.AudioSelectOptions(); ``` 3. 创建音频选择器实例。调用[select()](../reference/apis/js-apis-file-picker.md#select-6)接口拉起FilePicker界面进行文件选择。 + 文件选择成功后,返回被选中音频的URI结果集。开发者可以根据结果集中URI做进一步的处理。 - 例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据URI拿到音频资源的文件句柄(FD),再配合媒体服务实现音频播放的开发,具体请参考[音频播放开发指导](../media/audio-playback-overview.md)。 + 例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据URI拿到音频资源的文件句柄(FD),再配合媒体服务实现音频播放的开发,具体请参考[音频播放开发指导](../media/audio-playback-overview.md)。 + > **说明:** > > 目前AudioSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 - - + ```ts const audioViewPicker = new picker.AudioViewPicker(); audioViewPicker.select(audioSelectOptions) diff --git a/zh-cn/application-dev/file-management/send-file-to-app-sandbox.md b/zh-cn/application-dev/file-management/send-file-to-app-sandbox.md index 7d9c1e8ef69be67b2f9cdbd25470ca4316e4dfe2..d92a47c0afcd3763144debf385a318d998f5d09c 100644 --- a/zh-cn/application-dev/file-management/send-file-to-app-sandbox.md +++ b/zh-cn/application-dev/file-management/send-file-to-app-sandbox.md @@ -14,14 +14,14 @@ **表1** 应用沙箱路径与真实物理路径对应关系 -| 应用沙箱路径 | 调试进程(hdc)视角下的实际路径 | 说明 | +| 应用沙箱路径 | 调试进程(hdc)视角下的实际路径 | 说明 | | -------- | -------- | -------- | -| /data/storage/el1/bundle | /data/app/el1/bundle/public/<PACKAGENAME> | 应用安装包目录 | -| /data/storage/el1/base | /data/app/el1/<USERID>/base/<PACKAGENAME> | 应用el1级别加密数据目录 | -| /data/storage/el2/base | /data/app/el2/<USERID>/base/<PACKAGENAME> | 应用el2级别加密数据目录 | -| /data/storage/el1/database | /data/app/el1/<USERID>/database/<PACKAGENAME> | 应用el1级别加密数据库目录 | -| /data/storage/el2/database | /data/app/el2/<USERID>/database/<PACKAGENAME> | 应用el2级别加密数据库目录 | -| /data/storage/el2/distributedfiles | /mnt/hmdfs/<USERID>/account/merge_view/data/<PACKAGENAME> | 应用el2加密级别有帐号分布式数据融合目录 | +| /data/storage/el1/bundle | /data/app/el1/bundle/public/<PACKAGENAME> | 应用安装包目录 | +| /data/storage/el1/base | /data/app/el1/<USERID>/base/<PACKAGENAME> | 应用el1级别加密数据目录 | +| /data/storage/el2/base | /data/app/el2/<USERID>/base/<PACKAGENAME> | 应用el2级别加密数据目录 | +| /data/storage/el1/database | /data/app/el1/<USERID>/database/<PACKAGENAME> | 应用el1级别加密数据库目录 | +| /data/storage/el2/database | /data/app/el2/<USERID>/database/<PACKAGENAME> | 应用el2级别加密数据库目录 | +| /data/storage/el2/distributedfiles | /mnt/hmdfs/<USERID>/account/merge_view/data/<PACKAGENAME> | 应用el2加密级别有帐号分布式数据融合目录 | ## 开发示例 diff --git a/zh-cn/application-dev/file-management/set-security-label.md b/zh-cn/application-dev/file-management/set-security-label.md index 839495ade751e039f4a830f6109bf4b2d481bdee..a936e10442733389fc2c764b0a947aea57b496c7 100644 --- a/zh-cn/application-dev/file-management/set-security-label.md +++ b/zh-cn/application-dev/file-management/set-security-label.md @@ -2,7 +2,6 @@ 不同设备本身的安全能力差异较大,一些小的嵌入式设备安全能力远弱于平板等设备类型。用户或者应用不同的文件数据有不同安全诉求,例如个人的健康信息和银行卡信息等不期望被弱设备读取。因此,OpenHarmony提供一套完整的数据分级、设备分级标准,并针对不同设备制定不同的数据流转策略,具体规则请参见[数据、设备安全分级](../database/access-control-by-device-and-data-level.md)。 - ## 接口说明 API详细介绍请参见[ohos.file.securityLabel](../reference/apis/js-apis-file-securityLabel.md)。 @@ -15,8 +14,9 @@ API详细介绍请参见[ohos.file.securityLabel](../reference/apis/js-apis-file | getSecurityLabel | 获取文件安全标签 | 方法 | √ | √ | > **须知:** +> > 1. 对于不满足安全等级的文件,跨设备仍然可以看到该文件,但是无权限打开访问该文件。 -> +> > 2. 分布式文件系统的数据等级默认为S3,应用可以主动设置文件的安全等级。 ## 开发示例 diff --git a/zh-cn/application-dev/file-management/share-app-file.md b/zh-cn/application-dev/file-management/share-app-file.md index eae8df4b63d84d007ebdb748ae891a2976c9fc9f..49da5bd432da6afde84972a0f4679bffe981dcba 100644 --- a/zh-cn/application-dev/file-management/share-app-file.md +++ b/zh-cn/application-dev/file-management/share-app-file.md @@ -13,6 +13,7 @@ 文件URI的格式为: 格式为file://<bundleName>/<path>/\#networkid=<networkid> + - file:文件URI的标志。 - bundleName:该文件资源的属主。 @@ -26,7 +27,7 @@ 在分享文件给其他应用前,开发者需要先[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。 1. 获取文件在应用沙箱中的路径,并转换为文件URI。 - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import fileuri from '@ohos.file.fileuri'; @@ -49,7 +50,7 @@ > **说明:** > > 写权限分享时,同时授予读权限。 - + ```ts import fileuri from '@ohos.file.fileuri'; import window from '@ohos.window'; @@ -118,7 +119,6 @@ 通过接口want的参数获取分享文件的URI,获取文件URI后通过fs.open()接口打开文件,获取对应的file对象后,可对文件进行读写操作。 - ```ts // xxx.ets import fs from '@ohos.file.fs'; diff --git a/zh-cn/application-dev/file-management/user-file-overview.md b/zh-cn/application-dev/file-management/user-file-overview.md index 3a76a3d264ddda4b5616e16808807344f63d6f98..080a266fa346a0066605d470d50c1286cfcd7ae0 100644 --- a/zh-cn/application-dev/file-management/user-file-overview.md +++ b/zh-cn/application-dev/file-management/user-file-overview.md @@ -56,5 +56,5 @@ OpenHarmony提供[用户文件访问框架](#用户文件访问框架),用于 - File Access Framework(用户文件访问框架)的主要功能模块如下: - File Access Helper:提供给文件管理器和文件选择器访问用户文件的API接口。 - File Access ExtensionAbility:提供文件访问框架能力,由内卡文件管理服务UserFileManager和外卡文件管理服务ExternalFileManager组成,实现对应的文件访问功能。 - - UserFileManager:内卡文件管理服务,基于File Access ExtensionAbility框架实现,用于管理内置存储设备上的文件。 - - ExternalFileManager:外卡文件管理服务,基于File Access ExtensionAbility框架实现,用于管理外置存储设备上的文件。 + - UserFileManager:内卡文件管理服务,基于File Access ExtensionAbility框架实现,用于管理内置存储设备上的文件。 + - ExternalFileManager:外卡文件管理服务,基于File Access ExtensionAbility框架实现,用于管理外置存储设备上的文件。 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/case.md b/zh-cn/application-dev/key-features/multi-device-app-dev/case.md index 0792abdeb6ecd0c060cdba2794501436a6563105..25fd477a9a8c76d09163d3de8d45d7026f33074e 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/case.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/case.md @@ -526,7 +526,7 @@ struct Conversation { - 通过[Flex组件](../../reference/arkui-ts/ts-container-flex.md)将三个部分组合起来,注意justifyContent: FlexAlign.SpaceBetween配置项是将Flex组件中的元素按照主轴方向均匀分配,其中第一个元素与顶部对齐,最后一个元素与底部对齐。 -- 通过[List组件](../../reference/arkui-ts/ts-container-list.md)和[ForEach语法](../../quick-start/arkts-rendering-control.md#循环渲染),显示整个消息列表。 +- 通过[List组件](../../reference/arkui-ts/ts-container-list.md)和[ForEach语法](../../quick-start/arkts-rendering-control-foreach.md),显示整个消息列表。 | 默认设备 | 平板 | | -------- | -------- | diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md index 5bd5144d57b201b20310a141a8fed69ee55d6528..bcf284e7a455cb1ab3cfbcdc33b9db4b862bc94f 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/responsive-layout.md @@ -48,7 +48,7 @@ OpenHarmony提供了多种方法,判断应用当前处于何种断点,进而 通过窗口对象监听断点变化的核心是获取窗口对象及注册窗口尺寸变化的回调函数。 -1. 在Ability的[onWindowStageCreate](../../application-models/uiability-lifecycle.md)生命周期回调中,通过[窗口](../../reference/apis/js-apis-window.md)对象获取启动时的应用窗口宽度并注册回调函数监听窗口尺寸变化。将窗口尺寸的长度单位[由px换算为vp](../../key-features/multi-device-app-dev/visual-basics.md#视觉基础)后,即可基于前文中介绍的规则得到当前断点值,此时可以使用[状态变量](../../quick-start/arkts-state-mgmt-application-level.md)记录当前的断点值方便后续使用。 +1. 在Ability的[onWindowStageCreate](../../application-models/uiability-lifecycle.md)生命周期回调中,通过[窗口](../../reference/apis/js-apis-window.md)对象获取启动时的应用窗口宽度并注册回调函数监听窗口尺寸变化。将窗口尺寸的长度单位[由px换算为vp](../../key-features/multi-device-app-dev/visual-basics.md#视觉基础)后,即可基于前文中介绍的规则得到当前断点值,此时可以使用[状态变量](../../quick-start/arkts-state.md)记录当前的断点值方便后续使用。 ```ts // MainAbility.ts @@ -133,7 +133,7 @@ OpenHarmony提供了多种方法,判断应用当前处于何种断点,进而 在实际应用开发过程中,开发者常常需要针对不同类型设备或同一类型设备的不同状态来修改应用的样式。媒体查询提供了丰富的媒体特征监听能力,可以监听应用显示区域变化、横竖屏、深浅色、设备类型等等,因此在应用开发过程中使用的非常广泛。 -本小节仅介绍**媒体查询跟断点的结合**,即如何借助媒体查询能力,监听断点的变化,读者可以自行查阅官网中关于[媒体查询](../../ui/ui-ts-layout-mediaquery.md)的相关介绍了解更详细的用法。 +本小节仅介绍**媒体查询跟断点的结合**,即如何借助媒体查询能力,监听断点的变化,读者可以自行查阅官网中关于[媒体查询](../../ui/arkts-layout-development-media-query.md)的相关介绍了解更详细的用法。 > **说明:** diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md b/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md index aab0b9802480e7d4f07adbccd32df8a82f0bb761..40ec326319b50820ad9c608128894203959a80bc 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/settings-application-page.md @@ -1,6 +1,6 @@ # 设置应用页面 -本小节以“设置”应用页面为例,介绍如何使用自适应布局能力和响应式布局能力适配不同尺寸窗口。本示例已经在[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Settings)中开源,读者可以根据需要自行下载源码并运行及查看效果。 +本小节以“设置”应用页面为例,介绍如何使用自适应布局能力和响应式布局能力适配不同尺寸窗口。本示例已经在[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Settings)中开源,读者可以根据需要自行下载源码并运行及查看效果。 ## 页面设计 diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md b/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md index ebc5f5f701fa3e994f0bc973d9fd9f73f444622b..a20bc3c2e594a40ab62323378add0c66753a4255 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md @@ -78,13 +78,13 @@ ## 页面开发 -天气应用中涉及较多的页面和弹窗,本小节以天气主页为例,简单介绍不同设备下的页面实现思路。天气应用已经在[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather中开源,感兴趣的读者可以自行下载及了解详细代码实现。 +天气应用中涉及较多的页面和弹窗,本小节以天气主页为例,简单介绍不同设备下的页面实现思路。天气应用已经在[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather)中开源,感兴趣的读者可以自行下载及了解详细代码实现。 观察天气主页在不同设备上的UX设计图,可以进行如下设计: - 将天气主页划分为9个基础区域,如: ![home_full](figures/home_full.png) -- 基础区域9仅在大设备上显示,基础区域1-8虽然在各设备上始终展示但其尺寸及区域内的布局基本保持不变,可以结合[自适应布局](adaptive-layout.md)能力以[自定义组件](../../quick-start/arkts-basic-ui-description.md)的形式分别实现这9个基础区域。 +- 基础区域9仅在大设备上显示,基础区域1-8虽然在各设备上始终展示但其尺寸及区域内的布局基本保持不变,可以结合[自适应布局](adaptive-layout.md)能力以[自定义组件](../../quick-start/arkts-create-custom-components.md)的形式分别实现这9个基础区域。 | | 小设备 | 中设备 | 大设备 | | -------- | -------- | -------- | -------- | | 主页 | ![Home_sm](figures/Home_sm.png) | ![Home_md_mark](figures/Home_md_mark.png) | ![Home_lg_mark](figures/Home_lg_mark.png) | diff --git a/zh-cn/application-dev/media/audio-call-development.md b/zh-cn/application-dev/media/audio-call-development.md index fc3fa68da197a5fc1d72b6009328c20e07b65ad6..949707dc814c6c53673369bdc57e58460064eb06 100644 --- a/zh-cn/application-dev/media/audio-call-development.md +++ b/zh-cn/application-dev/media/audio-call-development.md @@ -8,18 +8,18 @@ ## 使用AudioRenderer播放对端的通话声音 - 该过程与[使用AudioRenderer开发音频播放功能](using-audiorenderer-for-playback.md)过程相似,关键区别在于audioRenderInfo参数和音频数据来源。audioRenderInfo参数中,音频内容类型需设置为语音,CONTENT_TYPE_SPEECH,音频流使用类型需设置为语音通信,STREAM_USAGE_VOICE_COMMUNICATION。 + 该过程与[使用AudioRenderer开发音频播放功能](using-audiorenderer-for-playback.md)过程相似,关键区别在于audioRendererInfo参数和音频数据来源。audioRendererInfo参数中,音频内容类型需设置为语音,CONTENT_TYPE_SPEECH,音频流使用类型需设置为语音通信,STREAM_USAGE_VOICE_COMMUNICATION。 ```ts import audio from '@ohos.multimedia.audio'; import fs from '@ohos.file.fs'; const TAG = 'VoiceCallDemoForAudioRenderer'; -// 与使用AudioRenderer开发音频播放功能过程相似,关键区别在于audioRenderInfo参数和音频数据来源 +// 与使用AudioRenderer开发音频播放功能过程相似,关键区别在于audioRendererInfo参数和音频数据来源 export default class VoiceCallDemoForAudioRenderer { private renderModel = undefined; private audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // 采样率 - channels: audio.AudioChannel.CHANNEL_2, // 通道数 + channels: audio.AudioChannel.CHANNEL_2, // 通道 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // 采样格式 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // 编码格式 } @@ -60,7 +60,7 @@ export default class VoiceCallDemoForAudioRenderer { // 开始一次音频渲染 async start() { let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; - if (stateGroup.indexOf(this.renderModel.state) === -1) { // 当且仅当状态为prepared、paused和stopped之一时才能启动渲染 + if (stateGroup.indexOf(this.renderModel.state) === -1) { // 当且仅当状态为STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一时才能启动渲染 console.error(TAG + 'start failed'); return; } @@ -91,7 +91,7 @@ export default class VoiceCallDemoForAudioRenderer { } }); }); - if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为released,停止渲染 + if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为STATE_RELEASED,停止渲染 fs.close(file); await this.renderModel.stop(); } @@ -105,7 +105,7 @@ export default class VoiceCallDemoForAudioRenderer { } // 暂停渲染 async pause() { - // 只有渲染器状态为running的时候才能暂停 + // 只有渲染器状态为STATE_RUNNING的时候才能暂停 if (this.renderModel.state !== audio.AudioState.STATE_RUNNING) { console.info('Renderer is not running'); return; @@ -119,7 +119,7 @@ export default class VoiceCallDemoForAudioRenderer { } // 停止渲染 async stop() { - // 只有渲染器状态为running或paused的时候才可以停止 + // 只有渲染器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 if (this.renderModel.state !== audio.AudioState.STATE_RUNNING && this.renderModel.state !== audio.AudioState.STATE_PAUSED) { console.info('Renderer is not running or paused.'); return; @@ -133,7 +133,7 @@ export default class VoiceCallDemoForAudioRenderer { } // 销毁实例,释放资源 async release() { - // 渲染器状态不是released状态,才能release + // 渲染器状态不是STATE_RELEASED状态,才能release if (this.renderModel.state === audio.AudioState.STATE_RELEASED) { console.info('Renderer already released'); return; @@ -161,7 +161,7 @@ export default class VoiceCallDemoForAudioCapturer { private audioCapturer = undefined; private audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, // 采样率 - channels: audio.AudioChannel.CHANNEL_1, // 通道数 + channels: audio.AudioChannel.CHANNEL_1, // 通道 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // 采样格式 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // 编码格式 } @@ -198,7 +198,7 @@ export default class VoiceCallDemoForAudioCapturer { // 开始一次音频采集 async start() { let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; - if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 当且仅当状态为prepared、paused和stopped之一时才能启动采集 + if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 当且仅当状态为STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一时才能启动采集 console.error(`${TAG}: start failed`); return; } diff --git a/zh-cn/application-dev/media/audio-call-overview.md b/zh-cn/application-dev/media/audio-call-overview.md index 93eaace16a24a560c7ff09c0d990e81d8f99489e..0a021c1a2fbc103a7a84acfb889e1dd907a4ac2e 100644 --- a/zh-cn/application-dev/media/audio-call-overview.md +++ b/zh-cn/application-dev/media/audio-call-overview.md @@ -14,7 +14,7 @@ 应用使用音频通话相关功能时,系统会切换至与通话相关的音频场景模式([AudioScene](../reference/apis/js-apis-audio.md#audioscene8)),当前预置了多种音频场景,包括响铃、通话、语音聊天等,在不同的场景下,系统会采用不同的策略来处理音频。 -如在蜂窝通话场景中会更注重人声的清晰度。系统会使用3A算法对音频数据进行预处理,抑制通话回声,消除背景噪音,调整音量范围,从而达到清晰人声的效果。3A算法,指声学回声消除(Acoustic Echo Cancelling, AEC)、背景噪声抑制(Acitve Noise Control, ANC)、自动增益控制(Automatic Gain Control, AGC)三种音频处理算法。 +如在蜂窝通话场景中会更注重人声的清晰度。系统会使用3A算法对音频数据进行预处理,抑制通话回声,消除背景噪音,调整音量范围,从而达到清晰人声的效果。3A算法,指声学回声消除(Acoustic Echo Cancellation, AEC)、背景噪声抑制(Active Noise Control, ANC)、自动增益控制(Automatic Gain Control, AGC)三种音频处理算法。 当前预置的四种音频场景: diff --git a/zh-cn/application-dev/media/audio-output-device-management.md b/zh-cn/application-dev/media/audio-output-device-management.md index 45d9fd3d68a9dd0efe346ce6b0fc65272bc71b9e..192efbfa08c217912ee4ebc2bdbcb9a0538d382e 100644 --- a/zh-cn/application-dev/media/audio-output-device-management.md +++ b/zh-cn/application-dev/media/audio-output-device-management.md @@ -1,6 +1,6 @@ # 音频输出设备管理 -有时设备同时连接多个音频输出设备,需要指定音频输出设备进行音频播放,此时需要使用AudioRoutingManager接口进行输出设备的管理,API说明可以参考[AudioRoutingManager API文档](../reference/apis/js-apis-audio.md#audiomanager)。 +有时设备同时连接多个音频输出设备,需要指定音频输出设备进行音频播放,此时需要使用AudioRoutingManager接口进行输出设备的管理,API说明可以参考[AudioRoutingManager API文档](../reference/apis/js-apis-audio.md#audioroutingmanager9)。 ## 创建AudioRoutingManager实例 diff --git a/zh-cn/application-dev/media/audio-recording-overview.md b/zh-cn/application-dev/media/audio-recording-overview.md index 6b9dca9f9c6b40d7f0dc6c5a983df851d22d71b2..0fc4a867eb37a17bb77a75441ab5aa41e03eabba 100644 --- a/zh-cn/application-dev/media/audio-recording-overview.md +++ b/zh-cn/application-dev/media/audio-recording-overview.md @@ -6,7 +6,7 @@ - [AVRecorder](using-avrecorder-for-recording.md):功能较完善的音频、视频录制ArkTS/JS API,集成了音频输入录制、音频编码和媒体封装的功能。开发者可以直接调用设备硬件如麦克风录音,并生成m4a音频文件。 -- [AudioCapturer](using-audiocapturer-for-recording.md):用于音频输入的的ArkTS/JS API,仅支持PCM格式,需要应用持续读取音频数据进行工作。应用可以在音频输出后添加数据处理,要求开发者具备音频处理的基础知识,适用于更专业、更多样化的媒体播放应用开发。 +- [AudioCapturer](using-audiocapturer-for-recording.md):用于音频输入的的ArkTS/JS API,仅支持PCM格式,需要应用持续读取音频数据进行工作。应用可以在音频输出后添加数据处理,要求开发者具备音频处理的基础知识,适用于更专业、更多样化的媒体录制应用开发。 - [OpenSLES](using-opensl-es-for-recording.md):一套跨平台标准化的音频Native API,目前阶段唯一的音频类Native API,同样提供音频输入原子能力,仅支持PCM格式,适用于从其他嵌入式平台移植,或依赖在Native层实现音频输入功能的录音应用使用。 diff --git a/zh-cn/application-dev/media/audio-recording-stream-management.md b/zh-cn/application-dev/media/audio-recording-stream-management.md index 801876008a7824085479664edd8e721695591b19..f7739a00c474f1a1f21ad4c0629f8d453a91d862 100644 --- a/zh-cn/application-dev/media/audio-recording-stream-management.md +++ b/zh-cn/application-dev/media/audio-recording-stream-management.md @@ -1,10 +1,10 @@ # 音频录制流管理 -对于播放音频类的应用,开发者需要关注该应用的音频流的状态以做出相应的操作,比如监听到状态为结束时,及时提示用户录制已结束。 +对于录制音频类的应用,开发者需要关注该应用的音频流的状态以做出相应的操作,比如监听到状态为结束时,及时提示用户录制已结束。 ## 读取或监听应用内音频流状态变化 -参考[使用AudioCapturer开发音频录制功能](using-audiocapturer-for-recording.md)或[audio.createAudioCapturer](../reference/apis/js-apis-audio.md#audiocreateaudiocapturer8),完成AudioRenderer的创建,然后可以通过以下两种方式查看音频流状态的变化: +参考[使用AudioCapturer开发音频录制功能](using-audiocapturer-for-recording.md)或[audio.createAudioCapturer](../reference/apis/js-apis-audio.md#audiocreateaudiocapturer8),完成AudioCapturer的创建,然后可以通过以下两种方式查看音频流状态的变化: - 方法1:直接查看AudioCapturer的[state](../reference/apis/js-apis-audio.md#属性): diff --git a/zh-cn/application-dev/media/avplayer-avrecorder-overview.md b/zh-cn/application-dev/media/avplayer-avrecorder-overview.md index 0e62bb3abb603855e244653023c88ba11f6bf13c..9bad52367caba377b345fd5632a696f69c4621d9 100644 --- a/zh-cn/application-dev/media/avplayer-avrecorder-overview.md +++ b/zh-cn/application-dev/media/avplayer-avrecorder-overview.md @@ -35,7 +35,7 @@ AVPlayer提供功能完善一体化播放能力,应用只需要提供流媒体 应用通过调用JS接口层提供的AVPlayer接口实现相应功能时,框架层会通过播放服务(Player Framework)解析成单独的音频数据流和视频数据流,音频数据流经过软件解码后输出至音频服务(Audio Framework),再至硬件接口层的音频HDI,实现音频播放功能。视频数据流经过硬件(推荐)/软件解码后输出至图形渲染服务(Graphic Framework),再输出至硬件接口层的显示HDI,完成图形渲染。 -完整的视频播放需要:应用、XComponemt、Player Framework、Graphic Framework、Audio Framework、显示HDI和音频HDI共同实现。 +完整的视频播放需要:应用、XComponent、Player Framework、Graphic Framework、Audio Framework、显示HDI和音频HDI共同实现。 图2中,数字标注表示需要数据与外部模块的传递。 diff --git a/zh-cn/application-dev/media/avsession-overview.md b/zh-cn/application-dev/media/avsession-overview.md index 77736a5f9e2779f5f5097f0d74c5be37fe26763c..446e027ad0d8c1d745c7941ee47d4a371cf7bbfe 100644 --- a/zh-cn/application-dev/media/avsession-overview.md +++ b/zh-cn/application-dev/media/avsession-overview.md @@ -4,23 +4,30 @@ 音视频类应用接入媒体会话后,可以发送应用的数据(比如正在播放的歌曲、歌曲的播放状态等),用户可以通过系统播控中心、语音助手等应用切换多个应用、多个设备播放。音视频类应用如果不接入媒体会话,将无法在后台播放,在应用进入后台时,会被强制停止播放。 +实现后台播放,还需申请长时任务避免进入挂起(Suspend)状态。具体参考[长时任务开发指导](../task-management/continuous-task-dev-guide.md)。 + ## 基础概念 在开发前,需要先了解以下基础概念: - 媒体会话(AVSession) + 媒体会话的一端连接被控的音视频应用,另一端连接音视频应用的控制端(如播控中心、语音助手等)。媒体会话提供了音视频应用和音视频应用控制端之间进行信息交换的通道。 - 媒体会话提供方 + 媒体会话提供方指接入媒体会话的音视频应用。音视频应用接入媒体会话后,需要向媒体会话提供播放的媒体信息,例如播放曲目名称、播放状态等。同时,音视频应用需要通过媒体会话接收控制端发出的控制命令并进行正确响应。 - 媒体会话控制方 + 媒体会话控制方指接入媒体会话并具有全局管控音视频行为功能的应用,例如系统播控中心、语音助手等。为便于开发者理解,下文将多处使用OpenHarmony系统应用播放中心,作为媒体会话控制方举例。播控中心等系统应用接入媒体会话后,可以通过监听媒体会话获取最新的媒体信息,也可以通过媒体会话向音视频应用发出控制命令。 - 媒体会话控制器(AVSessionController) + 媒体会话控制器的持有者,一般指媒体会话控制方,可以控制媒体会话提供方的应用播放行为,也可以获取应用的播放信息,还可以监听音视频应用播放状态的变化,用于确保媒体会话信息在音视频应用和播控中间之间的同步。 - 媒体会话管理器(AVSessionManager) + 媒体会话管理器提供了管理媒体会话的能力,可以创建媒体会话、创建媒体会话控制器、发送系统控制事件,也支持对媒体会话的状态进行监听。 @@ -31,9 +38,11 @@ ![AVSession Interaction Process](figures/avsession-interaction-process.png) - 本地媒体会话 + 本地媒体会话在本地设备中的媒体会话提供方和媒体会话控制方之间建立连接,实现系统中音视频应用统一的媒体播放控制和媒体信息显示。 - 分布式媒体会话 + 分布式媒体会话在跨设备场景中的媒体会话提供方和媒体会话控制方之间建立连接,实现音视频应用跨设备的媒体播放控制和媒体信息显示。例如,将设备A中播放的内容投播到设备B,并在设备B中进行播放控制。 ## 约束和限制 diff --git a/zh-cn/application-dev/media/camera-metadata.md b/zh-cn/application-dev/media/camera-metadata.md index a24fb072d52589a246e774991c2e826774841ffa..c4c5f32656a403af4bb13062bfbafe77fec46489 100644 --- a/zh-cn/application-dev/media/camera-metadata.md +++ b/zh-cn/application-dev/media/camera-metadata.md @@ -57,7 +57,7 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 > > 当前的元数据类型仅支持人脸检测(FACE_DETECTION)功能。元数据信息对象为识别到的人脸区域的矩形信息(Rect),包含矩形区域的左上角x坐标、y坐标和矩形的宽高数据。 -- 通过注册回调函数,获取监听metadata流的错误结果,callback返回metadata输出接口。使用错误时返回对应错误码,错误码类型参见CameraErrorCode。 +- 通过注册回调函数,获取监听metadata流的错误结果,callback返回metadata输出接口使用错误时返回的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 ```ts metadataOutput.on('error', (metadataOutputError) => { diff --git a/zh-cn/application-dev/media/camera-preview.md b/zh-cn/application-dev/media/camera-preview.md index ba0cf1d030451fea3337cc8e97e4bb9b263b835e..ec2f45a39cc887d96551acbb6c33a65dfcb1c9e3 100644 --- a/zh-cn/application-dev/media/camera-preview.md +++ b/zh-cn/application-dev/media/camera-preview.md @@ -7,6 +7,7 @@ 详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md)。 1. 创建Surface。 + XComponent组件为预览流提供的Surface,而XComponent的能力由UI提供,相关介绍可参考[XComponent组件参考](../reference/arkui-ts/ts-basic-components-xcomponent.md)。 ```ts @@ -69,7 +70,7 @@ }) ``` -- 通过注册固定的frameEnd回调函数获取监听预览启动结果,previewOutput创建成功时即可监听,预览完成最后一帧时触发,有该事件返回结果则认为预览流已结束。 +- 通过注册固定的frameEnd回调函数获取监听预览结束结果,previewOutput创建成功时即可监听,预览完成最后一帧时触发,有该事件返回结果则认为预览流已结束。 ```ts previewOutput.on('frameEnd', () => { @@ -77,7 +78,7 @@ }) ``` -- 通过注册固定的cameraStatus回调函数获取监听预览输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 +- 通过注册固定的error回调函数获取监听预览输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)。 ```ts previewOutput.on('error', (previewOutputError) => { diff --git a/zh-cn/application-dev/media/camera-recording.md b/zh-cn/application-dev/media/camera-recording.md index dd82b50cbbb133eb075d9414a92a717a9ae1413e..fbf05105b2dbe395e47de3aa27650a1234fb1d27 100644 --- a/zh-cn/application-dev/media/camera-recording.md +++ b/zh-cn/application-dev/media/camera-recording.md @@ -6,7 +6,7 @@ 详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md)。 -1. 创建拍照输出流的SurfaceId以及拍照输出的数据,都需要用到系统提供的[media接口](../reference/apis/js-apis-media.md)能力,导入media接口的方法如下。 +1. 导入media模块。创建拍照输出流的SurfaceId以及拍照输出的数据,都需要用到系统提供的[media接口](../reference/apis/js-apis-media.md)能力,导入media接口的方法如下。 ```ts import media from '@ohos.multimedia.media'; @@ -138,7 +138,7 @@ }) ``` -- 通过注册固定的frameEnd回调函数获取监听预览启动结果,videoOutput创建成功时即可监听,录像完成最后一帧时触发,有该事件返回结果则认为录像流已结束。 +- 通过注册固定的frameEnd回调函数获取监听录像结束结果,videoOutput创建成功时即可监听,录像完成最后一帧时触发,有该事件返回结果则认为录像流已结束。 ```ts videoOutput.on('frameEnd', () => { diff --git a/zh-cn/application-dev/media/camera-shooting.md b/zh-cn/application-dev/media/camera-shooting.md index 13dda3f3ff954bbf774db60d24468e5d9f110f16..1b868fb8ba241472f95e2b3011dede1810bd8435 100644 --- a/zh-cn/application-dev/media/camera-shooting.md +++ b/zh-cn/application-dev/media/camera-shooting.md @@ -6,13 +6,14 @@ 详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md)。 -1. 创建拍照输出流的SurfaceId以及拍照输出的数据,都需要用到系统提供的image接口能力,导入image接口的方法如下。 +1. 导入image接口。创建拍照输出流的SurfaceId以及拍照输出的数据,都需要用到系统提供的image接口能力,导入image接口的方法如下。 ```ts import image from '@ohos.multimedia.image'; ``` 2. 获取SurfaceId。 + 通过image的createImageReceiver方法创建ImageReceiver实例,再通过实例的getReceivingSurfaceId方法获取SurfaceId,与拍照输出流相关联,获取拍照输出流的数据。 ```ts @@ -30,6 +31,7 @@ ``` 3. 创建拍照输出流。 + 通过CameraOutputCapability类中的photoProfiles()方法,可获取当前设备支持的拍照输出流,通过createPhotoOutput()方法传入支持的某一个输出流及步骤一获取的SurfaceId创建拍照输出流。 ```ts @@ -46,6 +48,7 @@ ``` 4. 参数配置。 + 配置相机的参数可以调整拍照的一些功能,包括闪光灯、变焦、焦距等。 ```ts @@ -107,6 +110,7 @@ ``` 5. 触发拍照。 + 通过photoOutput类的capture()方法,执行拍照任务。该方法有两个参数,第一个参数为拍照设置参数的setting,setting中可以设置照片的质量和旋转角度,第二参数为回调函数。 ```ts @@ -129,7 +133,7 @@ 在相机应用开发过程中,可以随时监听拍照输出流状态,包括拍照流开始、拍照帧的开始与结束、拍照输出流的错误。 -- 通过注册固定的captureStart回调函数获取监听拍照开始结果,photoOutput时即可监听,拍照第一次曝光时触发,该事件返回此次拍照的captureId。 +- 通过注册固定的captureStart回调函数获取监听拍照开始结果,photoOutput创建成功时即可监听,拍照第一次曝光时触发,该事件返回此次拍照的captureId。 ```ts photoOutput.on('captureStart', (captureId) => { @@ -137,7 +141,7 @@ }) ``` -- 通过注册固定的frameShutter回调函数获取监听拍照结束结果,photoOutput时即可监听,该事件返回结果为拍照完全结束后的相关信息[CaptureEndInfo](../reference/apis/js-apis-camera.md#captureendinfo)。 +- 通过注册固定的captureEnd回调函数获取监听拍照结束结果,photoOutput创建成功时即可监听,该事件返回结果为拍照完全结束后的相关信息[CaptureEndInfo](../reference/apis/js-apis-camera.md#captureendinfo)。 ```ts photoOutput.on('captureEnd', (captureEndInfo) => { diff --git a/zh-cn/application-dev/media/image-overview.md b/zh-cn/application-dev/media/image-overview.md index 29747a33d28834532e7250c39b14a8c8d5caa8a0..7806a34f384fd8b36077a186aeba2f9888643733 100644 --- a/zh-cn/application-dev/media/image-overview.md +++ b/zh-cn/application-dev/media/image-overview.md @@ -5,15 +5,19 @@ 在学习图片开发前,需要熟悉以下基本概念。 - 图片解码 + 指将所支持格式的存档图片解码成统一的PixelMap,以便在应用或系统中进行图片显示或图片处理。当前支持的存档图片格式包括JPEG、PNG、GIF、RAW、WebP、BMP、SVG。 - PixelMap + 指图片解码后无压缩的位图,用于图片显示或图片处理。 - 图片处理 + 指对PixelMap进行相关的操作,如旋转、缩放、设置透明度、获取图片信息、读写像素数据等。 - 图片编码 + 指将PixelMap编码成不同格式的存档图片(当前仅支持JPEG和WebP),用于后续处理,如保存、传输等。 图片开发的主要流程如下图所示。 diff --git a/zh-cn/application-dev/media/image-transformation.md b/zh-cn/application-dev/media/image-transformation.md index bab88068a6979b882066b271be6f3b1a7d304fe7..ed09128d16a072e85847c193eeb43aaea720e83b 100644 --- a/zh-cn/application-dev/media/image-transformation.md +++ b/zh-cn/application-dev/media/image-transformation.md @@ -28,10 +28,10 @@ - 裁剪 ``` - // x:裁剪起始点横坐标0 - // y:裁剪起始点纵坐标0 - // height:裁剪高度400,方向为从上往下 - // width:裁剪宽度400,方向为从左到右 + // x:裁剪起始点横坐标0 + // y:裁剪起始点纵坐标0 + // height:裁剪高度400,方向为从上往下(裁剪后的图片高度为400) + // width:裁剪宽度400,方向为从左到右(裁剪后的图片宽度为400) pixelMap.crop({x: 0, y: 0, size: { height: 400, width: 400 } }); ``` diff --git a/zh-cn/application-dev/media/mic-management.md b/zh-cn/application-dev/media/mic-management.md index f8fe096ee24b6484066135bf9fada876d60c839c..575271681514dcadfda8e2ed8047324a66000c9a 100644 --- a/zh-cn/application-dev/media/mic-management.md +++ b/zh-cn/application-dev/media/mic-management.md @@ -44,7 +44,7 @@ } ``` -4. 根据查询结果的实际情况,调用setMicrophoneMute设置麦克风静音状态,入参输入true为静音,false为非静音。设置成功返回true,否则返回false。 +4. 根据查询结果的实际情况,调用setMicrophoneMute设置麦克风静音状态,入参输入true为静音,false为非静音。 ```ts async function setMicrophoneMuteTrue() { //设置麦克风静音,入参为true diff --git a/zh-cn/application-dev/media/using-audiocapturer-for-recording.md b/zh-cn/application-dev/media/using-audiocapturer-for-recording.md index 189093159072f5ad7b987ba493ed8d2e5cc1d990..76548cbe10a909340cddf0d1e570d4de08e10139 100644 --- a/zh-cn/application-dev/media/using-audiocapturer-for-recording.md +++ b/zh-cn/application-dev/media/using-audiocapturer-for-recording.md @@ -147,7 +147,7 @@ export default class AudioCapturerDemo { // 开始一次音频采集 async start() { let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED]; - if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 当且仅当状态为prepared、paused和stopped之一时才能启动采集 + if (stateGroup.indexOf(this.audioCapturer.state) === -1) { // 当且仅当状态为STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一时才能启动采集 console.error(`${TAG}: start failed`); return; } diff --git a/zh-cn/application-dev/media/using-audiorenderer-for-playback.md b/zh-cn/application-dev/media/using-audiorenderer-for-playback.md index a4356478fbe5facfc28822274dcce50e47e77f06..1bb55f5d5874923eb440ea911dbd3beedb0b4d5c 100644 --- a/zh-cn/application-dev/media/using-audiorenderer-for-playback.md +++ b/zh-cn/application-dev/media/using-audiorenderer-for-playback.md @@ -130,7 +130,7 @@ export default class AudioRendererDemo { private renderModel = undefined; private audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // 采样率 - channels: audio.AudioChannel.CHANNEL_2, // 通道数 + channels: audio.AudioChannel.CHANNEL_2, // 通道 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // 采样格式 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // 编码格式 } diff --git a/zh-cn/application-dev/media/using-avrecorder-for-recording.md b/zh-cn/application-dev/media/using-avrecorder-for-recording.md index f3c62923a7fa5ed418c1c18a8d316e893d9fa25d..98c9c4633eb25462ed4d8a6f09ab78a7b9883b4e 100644 --- a/zh-cn/application-dev/media/using-avrecorder-for-recording.md +++ b/zh-cn/application-dev/media/using-avrecorder-for-recording.md @@ -31,8 +31,8 @@ 2. 设置业务需要的监听事件,监听状态变化及错误上报。 | 事件类型 | 说明 | | -------- | -------- | - | stateChange | 必要事件,监听播放器的state属性改变 | - | error | 必要事件,监听播放器的错误信息 | + | stateChange | 必要事件,监听AVRecorder的state属性改变 | + | error | 必要事件,监听AVRecorder的错误信息 | ```ts diff --git a/zh-cn/application-dev/media/using-avsession-controller.md b/zh-cn/application-dev/media/using-avsession-controller.md index 26ae18f57f822a297e6f3b2ef43c2957b74f67c6..37aea26eb24fd8eeeb011a3ca2a9be5eda43218c 100644 --- a/zh-cn/application-dev/media/using-avsession-controller.md +++ b/zh-cn/application-dev/media/using-avsession-controller.md @@ -35,7 +35,7 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频 媒体会话控制方可以获取当前系统中所有的AVSessionDescriptor,并创建每个会话对应的AVSessionController,从而对系统中的音视频应用进行统一的播放控制。 ```ts - //导入AVSession模块 + //导入AVSessionManager模块 import AVSessionManager from '@ohos.multimedia.avsession'; // 全局变量定义 @@ -202,7 +202,7 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频 let validCommandTypeArray: Array = await controller.getValidCommands(); console.info(`get validCommandArray by controller : length : ${validCommandTypeArray.length}`); // 下发播放命令 - // 如果可用命令包含播放,则下发播放命令,当然正常session都应该提供并实现播放功能吧 + // 如果可用命令包含播放,则下发播放命令,正常session都应该提供并实现播放功能 if (validCommandTypeArray.indexOf('play') >= 0) { let avCommand: AVSessionManager.AVControlCommand = {command:'play'}; controller.sendControlCommand(avCommand); diff --git a/zh-cn/application-dev/media/using-avsession-developer.md b/zh-cn/application-dev/media/using-avsession-developer.md index a069465c0a3bdb02705776a449983fa461d917d0..40643ac3e089c5cf6cbd0e980cbab7b3b744d2fd 100644 --- a/zh-cn/application-dev/media/using-avsession-developer.md +++ b/zh-cn/application-dev/media/using-avsession-developer.md @@ -31,7 +31,7 @@ 1. 通过AVSessionManager的方法创建并激活媒体会话。 ```ts - import AVSessionManager from '@ohos.multimedia.avsession'; //导入AVSession模块 + import AVSessionManager from '@ohos.multimedia.avsession'; //导入AVSessionManager模块 // 创建session async createSession() { diff --git a/zh-cn/application-dev/media/using-distributed-avsession.md b/zh-cn/application-dev/media/using-distributed-avsession.md index 8f6793b1ee4c1d734fdea5b33e89e73f1868f565..a37f93e62b264f18e0c080174d59cfaa7918bced 100644 --- a/zh-cn/application-dev/media/using-distributed-avsession.md +++ b/zh-cn/application-dev/media/using-distributed-avsession.md @@ -14,13 +14,13 @@ | 接口名 | 说明 | | -------- | -------- | -| castAudio(session: SessionToken \| ‘all’, audioDevices: Array<audio.AudioDeviceDescriptor>, callback: AsyncCallback<void>): void | 投播会话到指定设备列表。 | +| castAudio(session: SessionToken \| 'all', audioDevices: Array<audio.AudioDeviceDescriptor>, callback: AsyncCallback<void>): void | 投播会话到指定设备列表。 | ## 开发步骤 系统应用作为媒体会话控制方接入媒体会话时,根据需要使用分布式媒体会话进行投播的步骤如下所示: -1. 导入模块接口。由于在进行投播之前,需要从audio模块获取音频设备描述符AudioDeviceDescriptor,所以除了导入avsession模块外,还需要导入audio模块。 +1. 导入模块接口。由于在进行投播之前,需要从audio模块获取音频设备描述符AudioDeviceDescriptor,所以除了导入AVSessionManager模块外,还需要导入audio模块。 ```ts import AVSessionManager from '@ohos.multimedia.avsession'; diff --git a/zh-cn/application-dev/media/using-opensl-es-for-recording.md b/zh-cn/application-dev/media/using-opensl-es-for-recording.md index 5dc7772809f8e552ecb7e139d3ef5e1eaada06fb..70e57a8fa95e23509736329dd7ccc88a8d3420c1 100644 --- a/zh-cn/application-dev/media/using-opensl-es-for-recording.md +++ b/zh-cn/application-dev/media/using-opensl-es-for-recording.md @@ -1,10 +1,10 @@ -# 使用OpenSLES开发音频录制功能 +# 使用OpenSL ES开发音频录制功能 OpenSL ES全称为Open Sound Library for Embedded Systems,是一个嵌入式、跨平台、免费的音频处理库。为嵌入式移动多媒体设备上的应用开发者提供标准化、高性能、低延迟的API。OpenHarmony的Native API基于[Khronos Group](https://www.khronos.org/)开发的[OpenSL ES](https://www.khronos.org/opensles/) 1.0.1 API 规范实现,开发者可以通过<OpenSLES.h>和<OpenSLES_OpenHarmony.h>在OpenHarmony上使用相关API。 ## OpenHarmony上的OpenSL ES -OpenSL ES中提供了以下的接口,OpenHarmony当前仅实现了部分[接口](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h),可以实现音频播放的基础功能。 +OpenSL ES中提供了以下的接口,OpenHarmony当前仅实现了部分[接口](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h),可以实现音频录制的基础功能。 调用未实现接口后会返回**SL_RESULT_FEATURE_UNSUPPORTED,**当前没有相关扩展可以使用。 diff --git a/zh-cn/application-dev/media/video-playback.md b/zh-cn/application-dev/media/video-playback.md index 7bbf8400ed151eaa94a9acfd5833c0b318fe4ac4..1cced19ac0bc0a73b999a49261c992272b58ace4 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -16,7 +16,7 @@ ![Playback status change](figures/video-playback-status-change.png) -状态的详细说明请参考[AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9)。当播放处于prepared / playing / paused / compeled状态时,播放引擎处于工作状态,这需要占用系统较多的运行内存。当客户端暂时不使用播放器时,调用reset()或release()回收内存资源,做好资源利用。 +状态的详细说明请参考[AVPlayerState](../reference/apis/js-apis-media.md#avplayerstate9)。当播放处于prepared / playing / paused / completed状态时,播放引擎处于工作状态,这需要占用系统较多的运行内存。当客户端暂时不使用播放器时,调用reset()或release()回收内存资源,做好资源利用。 ### 开发步骤及注意事项 @@ -32,8 +32,8 @@ | durationUpdate | 用于进度条,监听进度条长度,刷新资源时长。 | | timeUpdate | 用于进度条,监听进度条当前位置,刷新当前时间。 | | seekDone | 响应API调用,监听seek()请求完成情况。
当使用seek()跳转到指定播放位置后,如果seek操作成功,将上报该事件。 | - | speedDone | 响应API调用,监听setSpeed()请求完成情况。
当使用setSpeed()跳转到指定播放位置后,如果setSpeed操作成功,将上报该事件。 | - | volumeChange | 响应API调用,监听setVolume()请求完成情况。
当使用setVolume()跳转到指定播放位置后,如果setVolume操作成功,将上报该事件。 | + | speedDone | 响应API调用,监听setSpeed()请求完成情况。
当使用setSpeed()设置播放倍速后,如果setSpeed操作成功,将上报该事件。 | + | volumeChange | 响应API调用,监听setVolume()请求完成情况。
当使用setVolume()调节播放音量后,如果setVolume操作成功,将上报该事件。 | | bitrateDone | 响应API调用,用于HLS协议流,监听setBitrate()请求完成情况。
当使用setBitrate()指定播放比特率后,如果setBitrate操作成功,将上报该事件。 | | availableBitrates | 用于HLS协议流,监听HLS资源的可选bitrates,用于setBitrate()。 | | bufferingUpdate | 用于网络播放,监听网络播放缓冲信息。 | @@ -46,7 +46,7 @@ > > 下面代码示例中的url仅作示意使用,开发者需根据实际情况,确认资源有效性并设置: > - > - 确认相应的资源文件可用,并使用应用沙箱路径访问对应资源,参考[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。应用沙箱的介绍及如何向应用沙箱推送文件,请参考[文件管理](../file-management/app-sandbox-directory.md)。 + > - 如果使用本地资源播放,必须确认资源文件可用,并使用应用沙箱路径访问对应资源,参考[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)。应用沙箱的介绍及如何向应用沙箱推送文件,请参考[文件管理](../file-management/app-sandbox-directory.md)。 > > - 如果使用网络播放路径,需[申请相关权限](../security/accesstoken-guidelines.md):ohos.permission.INTERNET。 > @@ -61,9 +61,9 @@ 6. 视频播控:播放play(),暂停pause(),跳转seek(),停止stop() 等操作。 -7. 调用reset()重置资源,AVPlayer重新进入idle状态,允许更换资源url。 +7. (可选)更换资源:调用reset()重置资源,AVPlayer重新进入idle状态,允许更换资源url。 -8. 调用release()销毁实例,AVPlayer进入released状态,退出播放。 +8. 退出播放:调用release()销毁实例,AVPlayer进入released状态,退出播放。 ### 完整示例 diff --git a/zh-cn/application-dev/napi/figures/rawfile1.png b/zh-cn/application-dev/napi/figures/rawfile1.png new file mode 100644 index 0000000000000000000000000000000000000000..9f29f7875cd983f967b7a3b27b5898bfce76c9f3 Binary files /dev/null and b/zh-cn/application-dev/napi/figures/rawfile1.png differ diff --git a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md index f2ad48c2842755eadfa3ceab3327219f664a148a..7dba8071cd464c24ca2a2440f3b2dd31c2d207a6 100644 --- a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md +++ b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md @@ -241,4 +241,4 @@ int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { ## 相关实例 针对MindSpore Lite 的使用,有以下相关实例可供参考: -- [简易MSLite教程](https://gitee.com/openharmony/third_party_mindspore/tree/master/mindspore/lite/examples/quick_start_c) +- [简易MSLite教程](https://gitee.com/openharmony/third_party_mindspore/tree/OpenHarmony-3.2-Release/mindspore/lite/examples/quick_start_c) diff --git a/zh-cn/application-dev/napi/rawfile-guidelines.md b/zh-cn/application-dev/napi/rawfile-guidelines.md index bf57812aec92b68022636939f269d14734aa5bf9..f0b38d25a80e23c1a113c5f606cada27efb9c47c 100644 --- a/zh-cn/application-dev/napi/rawfile-guidelines.md +++ b/zh-cn/application-dev/napi/rawfile-guidelines.md @@ -1,10 +1,8 @@ -# Rawfile开发指导 - - +# 资源管理Rawfile开发指导 ## 场景介绍 -开发者可以通过本指导了解在OpenHarmony应用中,如何使用Native Rawfile接口操作Rawfile目录和文件。功能包括遍历、打开、搜索、读取和关闭Rawfile。 +开发者可以通过本指导了解在OpenHarmony应用中,如何使用Native Rawfile接口操作Rawfile目录和文件。功能包括文件列表遍历、文件打开、搜索、读取和关闭Rawfile。 ## 接口说明 @@ -27,60 +25,289 @@ ## 开发步骤 -1. 添加头文件。 + 以Js侧获取rawfile文件列表、rawfile文件内容、rawfile描述符{fd, offset, length}三种调用方式为例。 + +**1. 创建工程** + +![创建C++应用](figures/rawfile1.png) + +**2. 添加依赖** + +创建完成后,IDE会在工程生成cpp目录,目录有libentry/index.d.ts、hello.cpp、CMakeLists.txt等文件。 + +1. 打开src/main/cpp/CMakeLists.txt,在target_link_libraries依赖中添加资源的librawfile.z.so以及日志依赖libhilog_ndk.z.so ```c++ - #include "raw_file_manager.h" + target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so) ``` - - -2. 使用OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)接口获取NativeResourceManager实例。 +2. 打开src/main/cpp/types/libentry/index.d.ts文件,此文件声明了应用侧函数getFileList、getRawFileContent、getRawFileDescriptor。 - ```js - // js侧传递js resource manager。 - import resManager from '@ohos.resourceManager' - import rawfileTest from 'librawFileTest.so' - resManager.getResourceManager().then(resmgr => { - rawfileTest.testRawFile("test", resmgr, (error, value) => { - console.log("test rawFile"); - }) - }); - ``` - - ```c++ - // C++侧获取解析js侧传递的参数。 - NativeResourceManager* nativeResourceManager = nullptr; - std::string path; - if (i == 0 && valueType == napi_string) { - // 解析第一个参数,参数为相对rawfile目录的文件/目录路径。 - ...... - path = buf.data(); - } else if (i == 1 && valueType == napi_object) { - // 解析第二个参数,参数为js resource manager。 - nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]); + ```c++ + import resourceManager from '@ohos.resourceManager'; + export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array; + export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array; + export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor; + ``` + +**3. 修改源文件** + +1. 打开src/main/cpp/hello.cpp文件,文件Init会对当前方法进行初始化映射,这里定义对外接口为getFileList、getRawFileContent、getRawFileDescriptor,映射C++接口分别为GetFileList、GetRawFileContent、GetRawFileDescriptor。 + + ```c++ + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr } + }; + + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; } + EXTERN_C_END ``` +2. 把src/main/cpp/hello.cpp文件中,增加对应的三个方法,如下所示 + + ```c++ + static napi_value GetFileList(napi_env env, napi_callback_info info) + static napi_value GetRawFileContent(napi_env env, napi_callback_info info) + static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info) + ``` + +3. 在hello.cpp文件中获取Js的资源对象,并转为Native的资源对象,即可调用资源的Native接口,获取rawfile列表、rawfile文件内容以及rawfile描述符{fd, offset, length}三种调用方式示例代码如下: + + ```c++ + // 示例一:获取rawfile文件列表 GetFileList + static napi_value GetFileList(napi_env env, napi_callback_info info) + { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin"); + size_t requireArgc = 3; + size_t argc = 2; + napi_value argv[2] = { nullptr }; + // 获取参数信息 + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 + NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); + + // 获取函数argv[1],此为为rawfile相对路径 + size_t strSize; + char strBuf[256]; + napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); + std::string dirName(strBuf, strSize); + + // 获取对应的rawDir指针对象 + RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str()); + + // 获取rawDir下文件及文件夹数量 + int count = OH_ResourceManager_GetRawFileCount(rawDir); + + // 遍历获取文件名称,并保存 + std::vector tempArray; + for(int i = 0; i < count; i++) { + std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i); + tempArray.emplace_back(filename); + } + + napi_value fileList; + napi_create_array(env, &fileList); + for (size_t i = 0; i < tempArray.size(); i++) { + napi_value jsString; + napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString); + napi_set_element(env, fileList, i, jsString); + } + + // 关闭打开的指针对象 + OH_ResourceManager_CloseRawDir(rawDir); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + return fileList; + } + + // 示例二:获取rawfile文件内容 GetRawFileContent + napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) + { + napi_value buffer; + napi_status status = napi_create_external_arraybuffer(env, data.get(), length, + [](napi_env env, void *data, void *hint) { + delete[] static_cast(data); + }, nullptr, &buffer); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer"); + return nullptr; + } + napi_value result = nullptr; + status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array"); + return nullptr; + } + data.release(); + return result; + } + static napi_value GetRawFileContent(napi_env env, napi_callback_info info) + { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin"); + size_t requireArgc = 3; + size_t argc = 2; + napi_value argv[2] = { nullptr }; + // 获取参数信息 + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 + NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); + size_t strSize; + char strBuf[256]; + napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); + std::string filename(strBuf, strSize); + + // 获取rawfile指针对象 + RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); + if (rawFile != nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success"); + } + // 获取rawfile大小并申请内存 + long len = OH_ResourceManager_GetRawFileSize(rawFile); + std::unique_ptr data= std::make_unique(len); + // 读取rawfile + int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); + // 关闭打开的指针对象 + OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + // 转为js对象 + return CreateJsArrayValue(env, data, len); + } + + // 示例三:获取rawfile文件描述符 GetRawFileDescriptor + napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor) + { + napi_value result; + napi_status status = napi_create_object(env, &result); + if (status != napi_ok) { + return result; + } + + napi_value fd; + status = napi_create_int32(env, descriptor.fd, &fd); + if (status != napi_ok) { + return result; + } + status = napi_set_named_property(env, result, "fd", fd); + if (status != napi_ok) { + return result; + } + + napi_value offset; + status = napi_create_int64(env, descriptor.start, &offset); + if (status != napi_ok) { + return result; + } + status = napi_set_named_property(env, result, "offset", offset); + if (status != napi_ok) { + return result; + } + + napi_value length; + status = napi_create_int64(env, descriptor.length, &length); + if (status != napi_ok) { + return result; + } + status = napi_set_named_property(env, result, "length", length); + if (status != napi_ok) { + return result; + } + return result; + } + static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info) + { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin"); + size_t requireArgc = 3; + size_t argc = 2; + napi_value argv[2] = { nullptr }; + // 获取参数信息 + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + // 获取native的resourceManager对象 + NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); + size_t strSize; + char strBuf[256]; + napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); + std::string filename(strBuf, strSize); + // 获取rawfile指针对象 + RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); + if (rawFile != nullptr) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success"); + } + // 获取rawfile的描述符RawFileDescriptor {fd, offset, length} + RawFileDescriptor descriptor; + OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); + // 关闭打开的指针对象 + OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + // 转为js对象 + return createJsFileDescriptor(env,descriptor); + } + ``` + +**4. Js侧调用** + +1. 打开src\main\ets\pages\index.ets, 导入"libentry.so"; + +2. 获取当前js的resourceManager对象; +3. 调用Native接口getFileList即为src/main/cpp/types/libentry/index.d.ts中声明的接口,传入js的资源对象,以及rawfile文件夹的相对路径。示例如下: + + ```js + import hilog from '@ohos.hilog'; + import testNapi from 'libentry.so' // 导入so + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + private resmgr = getContext().resourceManager; // 获取js的资源对象 + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); + let rawfilelist = testNapi.getFileList(this.resmgr, ""); //传入资源对象,以及访问的rawfile文件夹名称 + console.log("rawfilelist" + rawfilelist); + let rawfileContet = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt"); + console.log("rawfileContet" + rawfileContet); + let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt"); + console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +## 函数介绍 -3. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawDir接口获取RawDir实例。 +1. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawDir接口获取RawDir实例。 ```c++ RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str()); ``` - - -4. 根据RawDir实例,使用OH_ResourceManager_GetRawFileCount接口获取对应目录下的rawfile文件总数 。 +2. 根据RawDir实例,使用OH_ResourceManager_GetRawFileCount接口获取对应目录下的rawfile文件总数 。 ```c++ int count = OH_ResourceManager_GetRawFileCount(rawDir); ``` - - -5. 根据RawDir实例,使用OH_ResourceManager_GetRawFileName接口获取目录下对应index的rawfile文件名。 +3. 根据RawDir实例,使用OH_ResourceManager_GetRawFileName接口获取目录下对应index的rawfile文件名。 ```c++ for (int index = 0; index < count; index++) { @@ -88,85 +315,65 @@ } ``` - - -6. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawFile接口获取指定文件名的RawFile实例 +4. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawFile接口获取指定文件名的RawFile实例 ```c++ RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); ``` - - -7. 根据RawFile实例,使用OH_ResourceManager_GetRawFileSize接口获取对应rawfile文件大小。 +5. 根据RawFile实例,使用OH_ResourceManager_GetRawFileSize接口获取对应rawfile文件大小。 ```c++ long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile); ``` - - -8. 根据RawFile实例,使用OH_ResourceManager_SeekRawFile接口指定rawfile偏移量。 +6. 根据RawFile实例,使用OH_ResourceManager_SeekRawFile接口指定rawfile偏移量。 ```c++ int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); int position = OH_ResourceManager_SeekRawFile(rawFile, 0 , 1); int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2); ``` - - -9. 根据RawFile实例,使用OH_ResourceManager_GetRawFileOffset接口获取rawfile偏移量。 +7. 根据RawFile实例,使用OH_ResourceManager_GetRawFileOffset接口获取rawfile偏移量。 ```c++ long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile) ``` - - -10. 根据RawFile实例,使用OH_ResourceManager_ReadRawFile接口读取rawfile文件内容。 +8. 根据RawFile实例,使用OH_ResourceManager_ReadRawFile接口读取rawfile文件内容。 ```c++ std::unique_ptr mediaData = std::make_unique(rawFileSize); long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize); ``` - - -11. 根据RawFile实例,使用OH_ResourceManager_CloseRawFile接口释放rawfile文件相关资源。 +9. 根据RawFile实例,使用OH_ResourceManager_CloseRawFile接口释放rawfile文件相关资源。 ```c++ OH_ResourceManager_CloseRawFile(rawFile); ``` - - -12. 根据RawDir实例,使用OH_ResourceManager_CloseRawDir接口释放rawfile目录相关资源。 +10. 根据RawDir实例,使用OH_ResourceManager_CloseRawDir接口释放rawfile目录相关资源。 ```c++ OH_ResourceManager_CloseRawDir(rawDir); ``` - - -13. 根据RawFile实例,使用OH_ResourceManager_GetRawFileDescriptor接口获取rawfile的RawFileDescriptor。 +11. 根据RawFile实例,使用OH_ResourceManager_GetRawFileDescriptor接口获取rawfile的RawFileDescriptor。 ```c++ RawFileDescriptor descriptor; bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); ``` - - -14. 根据RawFileDescriptor实例,使用OH_ResourceManager_ReleaseRawFileDescriptor接口关闭rawfile的fd。 +12. 根据RawFileDescriptor实例,使用OH_ResourceManager_ReleaseRawFileDescriptor接口关闭rawfile的fd。 ```c++ OH_ResourceManager_ReleaseRawFileDescriptor(descriptor); ``` - - -15. 根据NativeResourceManager实例,使用OH_ResourceManager_ReleaseNativeResourceManager接口释放native resource manager。 +13. 根据NativeResourceManager实例,使用OH_ResourceManager_ReleaseNativeResourceManager接口释放native resource manager。 ```c++ OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager); diff --git a/zh-cn/application-dev/notification/notification-overview.md b/zh-cn/application-dev/notification/notification-overview.md index 50525376aabb0a39bae6b303bd3fb29c7a84c3bf..18cfacc8a97bc17ab063a9046c5196a31faa2e19 100644 --- a/zh-cn/application-dev/notification/notification-overview.md +++ b/zh-cn/application-dev/notification/notification-overview.md @@ -30,6 +30,4 @@ OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对 基于通知的开发,有以下相关实例可供参考: -- [`CustomNotification`:自定义通知(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/CustomNotification) - -- [`Notification`:订阅、发送通知(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/Notification) \ No newline at end of file +- [`CustomNotification`:自定义通知(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Notification/CustomNotification) \ No newline at end of file diff --git a/zh-cn/application-dev/notification/progress-bar-notification.md b/zh-cn/application-dev/notification/progress-bar-notification.md index f8ea20e12108e82bf8d6a6f764ba264cea7add14..69da9774cda1cd37d28e08fd99e4870011a07147 100644 --- a/zh-cn/application-dev/notification/progress-bar-notification.md +++ b/zh-cn/application-dev/notification/progress-bar-notification.md @@ -3,7 +3,7 @@ 进度条通知也是常见的通知类型,主要应用于文件下载、事务处理进度显示。OpenHarmony提供了进度条模板,发布通知应用设置好进度条模板的属性值,如模板名、模板数据,通过通知子系统发送到通知栏显示。 -目前系统模板仅支持进度条模板,通知模板[NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate)中的data参数为用户自定义数据,用于显示与模块相关的数据,效果示意如下图所示。 +目前系统模板仅支持进度条模板,通知模板[NotificationTemplate](../reference/apis/js-apis-inner-notification-notificationTemplate.md)中的data参数为用户自定义数据,用于显示与模块相关的数据,效果示意如下图所示。 ![zh-cn_image_0000001416903138](figures/zh-cn_image_0000001416903138.png) diff --git a/zh-cn/application-dev/quick-start/application-configuration-file-overview-fa.md b/zh-cn/application-dev/quick-start/application-configuration-file-overview-fa.md index 9a176a9edcdd3400517f3032af75054897f04ce0..449b54e6ed40176171c1eba58da09524a2e86099 100644 --- a/zh-cn/application-dev/quick-start/application-configuration-file-overview-fa.md +++ b/zh-cn/application-dev/quick-start/application-configuration-file-overview-fa.md @@ -74,7 +74,7 @@ config.json示例: } ], "orientation": "unspecified", - "exported": true, + "visible": true, "srcPath": "MainAbility_entry", "name": ".MainAbility_entry", "srcLanguage": "ets", @@ -85,7 +85,7 @@ config.json示例: // $string:MainAbility_entry_label为资源索引 "label": "$string:MainAbility_entry_label", "type": "page", - "launchType": "multiton" + "launchType": "standard" } ], "distro": { diff --git a/zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md b/zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md index 7a7404987fb97f7e471576b801b266be96688815..553c849749a2a4d8e93fe025143a38984db8aa5c 100644 --- a/zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md +++ b/zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md @@ -23,7 +23,7 @@ - [自定义组件](arkts-create-custom-components.md):可复用的UI单元,可组合其他组件,如上述被\@Component装饰的struct Hello。 -- 系统组件:ArkUI框架中默认内置的基础和容器组件,可直接被开发者调用,比如示例中的Column 、 Text 、 Divider 、 Button。 +- 系统组件:ArkUI框架中默认内置的基础和容器组件,可直接被开发者调用,比如示例中的Column、Text、Divider、Button。 - 属性方法:组件可以通过链式调用配置多项属性,如fontSize()、width()、height()、color()等。 diff --git a/zh-cn/application-dev/quick-start/arkts-environment.md b/zh-cn/application-dev/quick-start/arkts-environment.md index 65f0b59d95f7da17638b65ec145409d691659ba9..4e69f5950e81eace3d8b06d0c034595160ab72f8 100644 --- a/zh-cn/application-dev/quick-start/arkts-environment.md +++ b/zh-cn/application-dev/quick-start/arkts-environment.md @@ -16,7 +16,7 @@ Environment是ArkUI框架在应用程序启动时创建的单例对象。它为A ```ts // 将设备的语言code存入AppStorage,默认值为en - // 后续设备的预览设置切换,都将同步到AppStorage中 + // 后续设备的语言设置切换,都将同步到AppStorage中 Environment.EnvProp('languageCode', 'en'); ``` diff --git a/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md b/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md index 01432b784c0432abcfa6c994dcdaaeeafd4fb673..c222dd5c435946369eba7572bdda0ae5d3eb241c 100644 --- a/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md +++ b/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @@ -84,7 +84,7 @@ 1. 在删除组件之前,将调用其aboutToDisappear生命周期函数,标记着该节点将要被销毁。ArkUI的节点删除机制是:后端节点直接从组件树上摘下,后端节点被销毁,对前端节点解引用,当前端节点已经没有引用时,将被JS虚拟机垃圾回收。 -2. 自定义组件和它的变量将被删除,如果其有同步的变量,比如[@Link](arkts-link.md)、[@Prop](zh-cn_topic_0000001524296665.xml)、[@StorageLink](arkts-appstorage.md#storagelink),将从[同步源](arkts-state-management-overview.md#基本概念)上取消注册。 +2. 自定义组件和它的变量将被删除,如果其有同步的变量,比如[@Link](arkts-link.md)、[@Prop](arkts-prop.md)、[@StorageLink](arkts-appstorage.md#storagelink),将从[同步源](arkts-state-management-overview.md#基本概念)上取消注册。 不建议在生命周期aboutToDisappear内使用async await,如果在生命周期的aboutToDisappear使用异步操作(Promise或者回调方法),自定义组件将被保留在Promise的闭包中,直到回调方法被执行完,这个行为阻止了自定义组件的垃圾回收。 diff --git a/zh-cn/application-dev/quick-start/figures/01.png b/zh-cn/application-dev/quick-start/figures/01.png deleted file mode 100644 index 8342856ec6643e20a941187852e6aef3ead11010..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/01.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/02.png b/zh-cn/application-dev/quick-start/figures/02.png deleted file mode 100644 index eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/02.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/04.png b/zh-cn/application-dev/quick-start/figures/04.png deleted file mode 100644 index 1190d1e5aa631b12171632d258e4c4fae32e9bba..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/04.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/07.png b/zh-cn/application-dev/quick-start/figures/07.png deleted file mode 100644 index 17f2b060d300667ff250935b6a37485843e854ce..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/quick-start/figures/07.png and /dev/null differ diff --git a/zh-cn/application-dev/quick-start/figures/chooseFAModel_ets.png b/zh-cn/application-dev/quick-start/figures/chooseFAModel_ets.png new file mode 100644 index 0000000000000000000000000000000000000000..784659f8b0efaf71620d06dd0df5c58d22ac47f4 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/chooseFAModel_ets.png differ diff --git a/zh-cn/application-dev/quick-start/figures/chooseFAModel_js.png b/zh-cn/application-dev/quick-start/figures/chooseFAModel_js.png new file mode 100644 index 0000000000000000000000000000000000000000..4d121aa3a9a1e3ba68cc5f70f6944fcfa3cef792 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/chooseFAModel_js.png differ diff --git a/zh-cn/application-dev/quick-start/figures/chooseStageModel.png b/zh-cn/application-dev/quick-start/figures/chooseStageModel.png new file mode 100644 index 0000000000000000000000000000000000000000..3125c8ba0591ce0c53344f35fb780eb956601624 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/chooseStageModel.png differ diff --git a/zh-cn/application-dev/quick-start/figures/createProject.png b/zh-cn/application-dev/quick-start/figures/createProject.png new file mode 100644 index 0000000000000000000000000000000000000000..7a56a44e0e7f80671b86c521792352db625ccad7 Binary files /dev/null and b/zh-cn/application-dev/quick-start/figures/createProject.png differ diff --git a/zh-cn/application-dev/quick-start/figures/09.png b/zh-cn/application-dev/quick-start/figures/secondPage.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/09.png rename to zh-cn/application-dev/quick-start/figures/secondPage.png diff --git a/zh-cn/application-dev/quick-start/figures/06.png b/zh-cn/application-dev/quick-start/figures/signConfig.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/06.png rename to zh-cn/application-dev/quick-start/figures/signConfig.png diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png index bcc45efdddb87a39201661c5f6d3ccbce9bfd3e6..8959cbb51a89df8142870313881bd45c2974d2ba 100644 Binary files a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png and b/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000001364054489.png differ diff --git a/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md b/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md index fde6de851ef350257cde9f26cdc12b0ca2b524a7..d1b97f4179a7d0e763b5370f31ff2ec9a81f28f4 100644 --- a/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md +++ b/zh-cn/application-dev/quick-start/full-sdk-compile-guide.md @@ -1,4 +1,4 @@ -# full-SDK编译指南 +# 如何编译full-SDK **full-SDK**是提供OpenHarmony全量接口的SDK,包含了系统应用所需要的高权限API,用于厂商开发应用。 diff --git a/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md b/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md index 73c9190d9fc124b353e6372ee1acc52f5d5781a8..b931eda14aa2545281bad1bb8ef8d7e4968c83c0 100644 --- a/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md +++ b/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md @@ -1,4 +1,4 @@ -# full-SDK替换指南 +# 如何替换full-SDK **public-SDK**是提供给应用开发的工具包,跟随DevEco Studio下载,不包含系统应用所需要的高权限API diff --git a/zh-cn/application-dev/quick-start/module-structure.md b/zh-cn/application-dev/quick-start/module-structure.md index 16534e58587ab1f6e55603e96f2ebbbcfc6ac814..d859c9c54f5fd7fe1557dba0053b361b3c90b076 100644 --- a/zh-cn/application-dev/quick-start/module-structure.md +++ b/zh-cn/application-dev/quick-start/module-structure.md @@ -48,7 +48,7 @@ module示例: } ], "orientation": "unspecified", - "exported": true, + "visible": true, "srcPath": "EntryAbility", "name": ".EntryAbility", "srcLanguage": "ets", @@ -57,7 +57,7 @@ module示例: "formsEnabled": false, "label": "$string:MainAbility_label", "type": "page", - "launchType": "multiton" + "launchType": "standard" } ], "distro": { @@ -263,8 +263,8 @@ OpenHarmony系统对无图标应用严格管控。如果HAP中没有配置入口 | icon | 标识Ability图标资源文件的索引。取值示例:$media:ability_icon。如果在该Ability的skills属性中,actions的取值包含 "action.system.home",entities取值中包含"entity.system.home",则该Ability的icon将同时作为应用的icon。如果存在多个符合条件的Ability,则取位置靠前的Ability的icon作为应用的icon。
说明:应用的"icon"和"label"是用户可感知配置项,需要区别于当前所有已有的应用"icon"或"label"(至少有一个不同)。 | 字符串 | 可缺省,缺省值为空。 | | label | 标识Ability对用户显示的名称。取值可以是Ability名称,也可以是对该名称的资源索引,以支持多语言。如果在该Ability的skills属性中,actions的取值包含 "action.system.home",entities取值中包含"entity.system.home",则该Ability的label将同时作为应用的label。如果存在多个符合条件的Ability,则取位置靠前的Ability的label作为应用的label。
说明: 应用的"icon"和"label"是用户可感知配置项,需要区别于当前所有已有的应用"icon"或"label"(至少有一个不同)。该标签为资源文件中定义的字符串的引用,或以"{}"包括的字符串。该标签最大长度为255个字节。 | 字符串 | 可缺省,缺省值为空。 | | uri | 标识Ability的统一资源标识符。该标签最大长度为255个字节。 | 字符串 | 可缺省,对于data类型的Ability不可缺省。 | -| launchType | 标识Ability的启动模式,支持"multiton"和"singleton"两种模式:
multiton:表示该Ability可以有多实例。该模式适用于大多数应用场景。
singleton:表示该Ability在所有任务栈中仅可以有一个实例。例如,具有全局唯一性的呼叫来电界面即采用"singleton"模式。该标签仅适用于默认设备、平板、智慧屏、车机、智能穿戴。 | 字符串 | 可缺省,缺省值为"singleton"。 | -| exported | 标识Ability是否可以被其他应用调用。
true:可以被其他应用调用。
false:不能被其他应用调用。 | 布尔类型 | 可缺省,缺省值为"false"。 | +| launchType | 标识Ability的启动模式,支持"standard"和"singleton"两种模式:
standard:表示该Ability可以有多实例。该模式适用于大多数应用场景。
singleton:表示该Ability在所有任务栈中仅可以有一个实例。例如,具有全局唯一性的呼叫来电界面即采用"singleton"模式。该标签仅适用于默认设备、平板、智慧屏、车机、智能穿戴。 | 字符串 | 可缺省,缺省值为"singleton"。 | +| visible | 标识Ability是否可以被其他应用调用。
true:可以被其他应用调用。
false:不能被其他应用调用。 | 布尔类型 | 可缺省,缺省值为"false"。 | | permissions | 标识其他应用的Ability调用此Ability时需要申请的权限集合,一个数组元素为一个权限名称。通常采用反向域名格式(最大255字节),取值为系统预定义的权限。 | 字符串数组 | 可缺省,缺省值为空。 | |skills | 标识Ability能够接收的want的特征。 | 对象数组 | 可缺省,缺省值为空。 | | deviceCapability | 标识Ability运行时要求设备具有的能力,采用字符串数组的格式表示。该标签为数组,支持最多配置512个元素,单个元素最大字节长度为64。 | 字符串数组 | 可缺省,缺省值为空。 | @@ -277,7 +277,7 @@ OpenHarmony系统对无图标应用严格管控。如果HAP中没有配置入口 | writePermission | 标识向Ability写数据所需的权限。该标签仅适用于data类型的Ability。取值为长度不超过255字节的字符串。 | 字符串 | 可缺省,缺省为空。 | | configChanges | 标识Ability关注的系统配置集合。当已关注的配置发生变更后,Ability会收到onConfigurationUpdated回调。取值范围:
mcc:表示IMSI移动设备国家/地区代码(MCC)发生变更。典型场景:检测到SIM并更新MCC。
mnc:IMSI移动设备网络代码(MNC)发生变更。典型场景:检测到SIM并更新MNC。
locale:表示语言区域发生变更。典型场景:用户已为设备文本的文本显示选择新的语言类型。
layout:表示屏幕布局发生变更。典型场景:当前有不同的显示形态都处于活跃状态。
fontSize:表示字号发生变更。典型场景:用户已设置新的全局字号。
orientation:表示屏幕方向发生变更。典型场景:用户旋转设备。
density:表示显示密度发生变更。典型场景:用户可能指定不同的显示比例,或当前有不同的显示形态同时处于活跃状态。
size:显示窗口大小发生变更。
smallestSize:显示窗口较短边的边长发生变更。
colorMode:颜色模式发生变更。 | 字符串数组 | 可缺省,缺省为空。 | | mission | 标识Ability指定的任务栈。该标签仅适用于page类型的Ability。默认情况下应用中所有Ability同属一个任务栈。 | 字符串 | 可缺省,缺省为应用的包名。 | -| targetAbility | 标识当前Ability重用的目标Ability。该标签仅适用于page类型的Ability。如果配置了targetAbility属性,则当前Ability(即别名Ability)的属性中仅name、icon、label、exported、permissions、skills生效,其他属性均沿用targetAbility中的属性值。目标Ability必须与别名Ability在同一应用中,且在配置文件中目标Ability必须在别名之前进行声明。 | 字符串 | 可缺省,缺省值为空。表示当前Ability不是一个别名Ability。 | +| targetAbility | 标识当前Ability重用的目标Ability。该标签仅适用于page类型的Ability。如果配置了targetAbility属性,则当前Ability(即别名Ability)的属性中仅name、icon、label、visible、permissions、skills生效,其他属性均沿用targetAbility中的属性值。目标Ability必须与别名Ability在同一应用中,且在配置文件中目标Ability必须在别名之前进行声明。 | 字符串 | 可缺省,缺省值为空。表示当前Ability不是一个别名Ability。 | | formsEnabled | 标识Ability是否支持卡片(forms)功能。该标签仅适用于page类型的Ability。
true:支持卡片能力。
false:不支持卡片能力。 | 布尔值 | 可缺省,缺省值为false。 | | forms | 标识服务卡片的属性。该标签仅当formsEnabled为"true"时,才能生效。 | 对象数组 | 可缺省,缺省值为空。 | | srcLanguage | Ability开发语言的类型,开发者创建工程时由开发者手动选择开发语言。 | 字符串 | 可缺省,缺省值为“js”。 | @@ -308,10 +308,10 @@ abilities示例: "icon": "$media:ic_launcher", // $string:example 为字符串类资源 "label": "$string:example", - "launchType": "multiton", + "launchType": "standard", "orientation": "unspecified", "permissions": [], - "exported": true, + "visible": true, "skills": [ { "actions": [ @@ -338,9 +338,9 @@ abilities示例: "description": "example play ability", "icon": "$media:ic_launcher", "label": "$string:example", - "launchType": "multiton", + "launchType": "standard", "orientation": "unspecified", - "exported": false, + "visible": false, "skills": [ { "actions": [ @@ -361,7 +361,7 @@ abilities示例: "name": ".UserADataAbility", "type": "data", "uri": "dataability://com.example.world.test.UserADataAbility", - "exported": true + "visible": true } ] ``` diff --git a/zh-cn/application-dev/quick-start/start-overview.md b/zh-cn/application-dev/quick-start/start-overview.md index 17cfcb5a1cff589cbddf6bffb394eb122e882b3b..d3a3528883a02dbeb91d210de97606e0109455bc 100644 --- a/zh-cn/application-dev/quick-start/start-overview.md +++ b/zh-cn/application-dev/quick-start/start-overview.md @@ -41,6 +41,6 @@ FA模型和Stage模型的整体架构和设计思想等更多区别,请见[应 1. 安装最新版[DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio)。 -2. 请参考[配置OpenHarmony SDK](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-setting-up-environment-0000001263160443-V3),完成**DevEco Studio**的安装和开发环境配置。 +2. 请参考[配置开发环境](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/environment_config-0000001052902427-V3),完成**DevEco Studio**的安装和开发环境配置。 完成上述操作及基本概念的理解后,可参照[使用ArkTS语言进行开发(Stage模型)](start-with-ets-stage.md)、[使用ArkTS语言开发(FA模型)](start-with-ets-fa.md)、[使用JS语言开发(FA模型)](../quick-start/start-with-js-fa.md)中的任一章节进行下一步体验和学习。 \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/start-with-ets-fa.md b/zh-cn/application-dev/quick-start/start-with-ets-fa.md index 00fdfdbd088ba060a8d86bcaf31ac03df3326c03..e04557d126081c36aced089576003df3e26b6002 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-fa.md @@ -5,28 +5,29 @@ > > 请使用**DevEco Studio V3.0.0.601 Beta1**及更高版本。 > -> 为确保运行效果,本文以使用**DevEco Studio 3.1 Beta1**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio)获取下载链接。 +> 为确保运行效果,本文以使用**DevEco Studio 3.1 Beta2**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio)获取下载链接。 ## 创建ArkTS工程 -1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**OpenHarmony**模板库,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 +1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**Application**应用开发(本文以应用开发为例,**Atomic Service**对应为原子化服务开发),选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 - ![01](figures/01.png) + ![createProject](figures/createProject.png) 2. 进入配置工程界面,**Compile SDK** 选择“**8**”(**Compile SDK**选择“**9**”时注意同步选择**Model** 为“**FA**”,此处以选择“**8**”为例),**Language**选择“**ArkTS**”,其他参数保持默认设置即可。 - ![02](figures/02.png) + ![chooseFAModel_ets](figures/chooseFAModel_ets.png) > **说明:** > - > DevEco Studio V3.0 Beta3及更高版本支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-ide-low-code-overview-0000001445605884-V3)方式。 + > DevEco Studio V3.0 Beta3及更高版本支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ide-low-code-overview-0000001480179573-V3)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > > 如需使用低代码开发方式,请打开上图中的Enable Super Visual开关。 3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 +4. 工程创建完成后,在**entry > build-profile.json5**文件中,将targets中的runtimeOS改为“OpenHarmony”,然后点击右上角提示框的**Sync Now**以进行OpenHarmony应用开发。 ## ArkTS工程目录结构(FA模型) @@ -34,18 +35,16 @@ ![zh-cn_image_0000001384652328](figures/zh-cn_image_0000001384652328.png) - **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 - - **src > main > ets**:用于存放ets源码。 + - **src > main > ets**:用于存放ArkTS源码。 - **src > main > ets > MainAbility**:应用/服务的入口。 - **src > main > ets > MainAbility > pages**:MainAbility包含的页面。 - **src > main > ets > MainAbility > pages > index.ets**:pages列表中的第一个页面,即应用的首页入口。 - **src > main > ets > MainAbility > app.ets**:承载Ability生命周期。 - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > config.json**:模块配置文件。主要包含HAP的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用配置文件(FA模型)](application-configuration-file-overview-fa.md)。 - - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 + - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。其中targets中可配置当前运行环境,默认为HarmonyOS。若需开发OpenHarmony应用,则需开发者自行修改为OpenHarmony。 - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 - - **hvigorfile.ts**:应用级编译构建任务脚本。 @@ -291,7 +290,7 @@ 2. 点击**File** > **Project Structure...** > **Project** > **SigningConfigs** 界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: - ![06](figures/06.png) + ![signConfig](figures/signConfig.png) 3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001364054485](figures/zh-cn_image_0000001364054485.png)按钮运行。效果如下图所示: diff --git a/zh-cn/application-dev/quick-start/start-with-ets-stage.md b/zh-cn/application-dev/quick-start/start-with-ets-stage.md index f913187c82312cb47d3316d36cdf8e1a1998152d..309d69cc9868c8e29311564cf74c2a16c80eeb43 100644 --- a/zh-cn/application-dev/quick-start/start-with-ets-stage.md +++ b/zh-cn/application-dev/quick-start/start-with-ets-stage.md @@ -5,22 +5,22 @@ > > 请使用**DevEco Studio V3.0.0.900 Beta3**及更高版本。 > -> 为确保运行效果,本文以使用**DevEco Studio 3.1 Beta1**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio)获取下载链接。 +> 为确保运行效果,本文以使用**DevEco Studio 3.1 Beta2**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio)获取下载链接。 ## 创建ArkTS工程 -1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**OpenHarmony**模板库,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 +1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**Application**应用开发(本文以应用开发为例,**Atomic Service**对应为原子化服务开发),选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 - ![01](figures/01.png) + ![createProject](figures/createProject.png) 2. 进入配置工程界面,**Compile SDK**选择“**9**”,**Model** 选择“**Stage**”,其他参数保持默认设置即可。 - ![07](figures/07.png) + ![chooseStageModel](figures/chooseStageModel.png) > **说明:** > - > 支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-ide-low-code-overview-0000001445605884-V3)方式。 + > 支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ide-low-code-overview-0000001480179573-V3)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > @@ -28,22 +28,24 @@ 3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 +4. 工程创建完成后,在**entry > build-profile.json5**文件中,将targets中的runtimeOS改为“OpenHarmony”,然后点击右上角提示框的**Sync Now**以进行OpenHarmony应用开发。 + ## ArkTS工程目录结构(Stage模型) ![zh-cn_image_0000001364054489](figures/zh-cn_image_0000001364054489.png) +- **AppStore > app.json5**:应用的全局配置信息。 - **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。 - - **src > main > ets**:用于存放ets源码。 + - **oh_modules**:用于存放三方库依赖信息。关于原npm工程适配ohpm操作,请参考[历史工程手动迁移](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212)。 + - **src > main > ets**:用于存放ArkTS源码。 - **src > main > ets > entryability**:应用/服务的入口。 - **src > main > ets > pages**:应用/服务包含的页面。 - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源文件的分类](resource-categories-and-access.md#资源分类)。 - **src > main > module.json5**:模块配置文件。主要包含HAP的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[module.json5配置文件](module-configuration-file.md)。 - - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 - - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - + - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。其中targets中可配置当前运行环境,默认为HarmonyOS。若需开发OpenHarmony应用,则需开发者自行修改为OpenHarmony。 +- **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 - - **hvigorfile.ts**:应用级编译构建任务脚本。 @@ -123,7 +125,7 @@ - 新建第二个页面文件。在“**Project**”窗口,打开“**entry > src > main > ets**”,右键点击“**pages**”文件夹,选择“**New > ArkTS File**”,命名为“**Second**”,点击“**Finish**”。可以看到文件目录结构如下: - ![09](figures/09.png) + ![secondPage](figures/secondPage.png) > **说明:** > @@ -281,7 +283,7 @@ 2. 点击**File** > **Project Structure...** > **Project** > **SigningConfigs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: - ![06](figures/06.png) + ![signConfig](figures/signConfig.png) 3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001364054485](figures/zh-cn_image_0000001364054485.png)按钮运行。效果如下图所示: diff --git a/zh-cn/application-dev/quick-start/start-with-js-fa.md b/zh-cn/application-dev/quick-start/start-with-js-fa.md index e1bc75285c9d17d4731418e272001dc865edb16c..027047b98c7f9f57dde812613cff25a3601a5927 100644 --- a/zh-cn/application-dev/quick-start/start-with-js-fa.md +++ b/zh-cn/application-dev/quick-start/start-with-js-fa.md @@ -3,22 +3,22 @@ > **说明:** > -> 为确保运行效果,本文以使用**DevEco Studio 3.1 Beta1**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download)获取下载链接。 +> 为确保运行效果,本文以使用**DevEco Studio 3.1 Beta2**版本为例,点击[此处](https://developer.harmonyos.com/cn/develop/deveco-studio#download)获取下载链接。 ## 创建JS工程 -1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**OpenHarmony**模板库,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 +1. 若首次打开**DevEco Studio**,请点击**Create Project**创建工程。如果已经打开了一个工程,请在菜单栏选择**File** > **New** > **Create Project**来创建一个新工程。选择**Application**应用开发(本文以应用开发为例,**Atomic Service**对应为原子化服务开发),选择模板“**Empty Ability**”,点击**Next**进行下一步配置。 - ![01](figures/01.png) + ![createProject](figures/createProject.png) 2. 进入配置工程界面,**Compile SDK**选择“**8**”(**Compile SDK**选择“**9**”时注意同步选择 **Model** 为“**FA**”,此处以选择“**8**”为例),**Language**选择“**JS**”,其他参数保持默认设置即可。 - ![04](figures/04.png) + ![chooseFAModel_js](figures/chooseFAModel_js.png) > **说明:** > - > DevEco Studio V2.2 Beta1及更高版本支持使用JS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-ide-low-code-overview-0000001445605884-V3)方式。 + > DevEco Studio V2.2 Beta1及更高版本支持使用JS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ide-low-code-overview-0000001480179573-V3)方式。 > > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > @@ -26,6 +26,8 @@ 3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。 +4. 工程创建完成后,在**entry > build-profile.json5**文件中,将targets中的runtimeOS改为“OpenHarmony”,然后点击右上角提示框的**Sync Now**以进行OpenHarmony应用开发。 + ## JS工程目录结构 @@ -40,7 +42,7 @@ - **src > main > resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。关于资源文件,详见[资源限定与访问](../ui/js-framework-resource-restriction.md)。 - **src > main > config.json**:模块配置文件。主要包含HAP的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。具体的配置文件说明,详见[应用配置文件(FA模型)](application-configuration-file-overview-fa.md)。 - - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。 + - **build-profile.json5**:当前的模块信息 、编译信息配置项,包括buildOption、targets配置等。其中targets中可配置当前运行环境,默认为HarmonyOS。若需开发OpenHarmony应用,则需开发者自行修改为OpenHarmony。 - **hvigorfile.ts**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。 - **build-profile.json5**:应用级配置信息,包括签名、产品配置等。 @@ -226,11 +228,10 @@ 2. 点击**File** > **Project Structure...** > **Project** > **Signing Configs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示: - ![06](figures/06.png) + ![signConfig](figures/signConfig.png) 3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001364054485](figures/zh-cn_image_0000001364054485.png)按钮运行。效果如下图所示: ![zh-cn_image_0000001311175132](figures/zh-cn_image_0000001311175132.png) 恭喜您已经使用JS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 - diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 92d01f33bc2bc141374a1317bfd0734bc407cfd4..6d83377eb5def012611401569ad36a5242407630 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -152,6 +152,7 @@ - bundleManager - [abilityInfo](js-apis-bundleManager-abilityInfo.md) - [applicationInfo](js-apis-bundleManager-applicationInfo.md) + - [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md) - [bundleInfo](js-apis-bundleManager-bundleInfo.md) - [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md) - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) @@ -233,6 +234,7 @@ - [@ohos.data.ValuesBucket (数据集)](js-apis-data-valuesBucket.md) - 文件管理 + - [@ohos.file.backup (备份恢复)](js-apis-file-backup.md) - [@ohos.file.cloudSyncManager (端云同步管理)](js-apis-file-cloudsyncmanager.md) - [@ohos.file.environment (目录环境能力)](js-apis-file-environment.md) - [@ohos.file.fileAccess (公共文件访问与管理)](js-apis-fileAccess.md) diff --git a/zh-cn/application-dev/reference/apis/common_event/commonEvent-ans.md b/zh-cn/application-dev/reference/apis/common_event/commonEvent-ans.md new file mode 100644 index 0000000000000000000000000000000000000000..0a95dea844b855463eed428f362d0f3a409920f2 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/common_event/commonEvent-ans.md @@ -0,0 +1,13 @@ +# 通知服务公共事件定义 +通知服务面向应用发布如下系统公共事件,应用如需订阅系统公共事件,请参考公共事件[接口文档](../js-apis-commonEventManager.md)。 + +## COMMON_EVENT_SLOT_CHANGE +表示通知渠道或通知开关发生变化。 + +- 常量值:"usual.event.SLOT_CHANGE" +- 订阅方需要的权限:ohos.permission.NOTIFICATION_CONTROLLER + +通知设置里修改应用的渠道参数、渠道开关,或者开启、关闭通知使能开关时,都会触发通知服务发布这个系统公共事件。 + +与这个公共事件相关的接口:setSlotByBundle、setNotificationEnableSlot、setNotificationEnable,这些为系统API,一般都是通知设置应用调用,具体参看[通知接口文档](../js-apis-notificationManager.md)。 + diff --git a/zh-cn/application-dev/reference/apis/common_event/commonEvent-subsystem.md b/zh-cn/application-dev/reference/apis/common_event/commonEvent-subsystem.md new file mode 100644 index 0000000000000000000000000000000000000000..24c662b23d8d222260ae74f5111e5edb1c9ecf50 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/common_event/commonEvent-subsystem.md @@ -0,0 +1,13 @@ +# xxx(子系统名称)公共事件定义 +xxxx子系统/服务面向应用发布如下系统公共事件,应用如需订阅系统公共事件,请参考公共事件[接口文档](../js-apis-commonEventManager.md)。 + +## commonEvent1(事件名称) +// 第一段描述:事件的解释,能够简要表达事件包含的含义。 + +- 常量值:"usual.event.xx" +- 订阅方需要的权限:xxx/无需权限 + +// 第二段描述:这里需要详细描述事件上报的机制,用于帮助开发者理解具体是因为什么动作触发了这条系统公共事件。 + +// 第三段描述(可选):如果该事件的触发依赖一些变量,需要额外解释这些变量的成因,比如本子系统某个接口的返回值或回调决定了该事件的触发条件,那么需要在这里进行解释说明,有必要的话需要提供到该接口的链接。 + diff --git a/zh-cn/application-dev/reference/apis/development-intro.md b/zh-cn/application-dev/reference/apis/development-intro.md index d609303628f400b35fa22e9e1e794feb78ebf946..3ae0b33f7b4767ff3342ab5b95cd6417c199183a 100644 --- a/zh-cn/application-dev/reference/apis/development-intro.md +++ b/zh-cn/application-dev/reference/apis/development-intro.md @@ -30,7 +30,7 @@ OpenHarmony中提供的接口,部分是仅供OEM厂商使用的system api, 随DevEco下载的SDK为public-SDK,不包括系统接口。如需使用系统接口,需要: - 参考[full-SDK替换指南](../../quick-start/full-sdk-switch-guide.md)将SDK替换为full-SDK。 -- 参考[HarmonyAppProvision配置文件的说明](../../security/app-provision-structure.md#harmonyappprovision配置文件的说明)修改HarmonyAppProvision配置文件中的app-feature字段为hos_system_app(系统应用)。 +- 参考[HarmonyAppProvision配置文件的说明](../../security/app-provision-structure.md)修改HarmonyAppProvision配置文件中的app-feature字段为hos_system_app(系统应用)。 ## 权限说明 diff --git a/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index c7f5608e6f679afad5f6162c343533011d38ed6a..79eb98c313cecc829b95f67828b8d79a82743a56 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -110,7 +110,7 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil onAppStart(bundleName: string): void -应用卸载事件回调。 +应用启动事件回调。 **系统能力**:SystemCapability.Customization.EnterpriseDeviceManager @@ -136,7 +136,7 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil onAppStop(bundleName: string): void -应用卸载事件回调。 +应用停止事件回调。 **系统能力**:SystemCapability.Customization.EnterpriseDeviceManager diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md index 2ec899589fce0fd7deb34e659ed1261c23bd6a6c..18c89d87f89719c70a87007b7abe72f5f10a913d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md @@ -15,15 +15,15 @@ import ability from '@ohos.ability.ability'; **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase -| 名称 | 类型 | 必填 | 描述 | -| ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | 否 | DataAbilityHelper二级模块。 | -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | 否 | PacMap二级模块。 | -| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | 否 | DataAbilityOperation二级模块。 | -| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | 否 | DataAbilityResult二级模块。 | -| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | 否 | AbilityResult二级模块。 | -| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 否 | ConnectOptions二级模块。 | -| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | 否 | StartAbilityParameter二级模块。 | +| 名称 | 类型 | 描述 | +| ----------- | -------------------- | ------------------------------------------------------------ | +| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | DataAbilityHelper二级模块。 | +| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | PacMap二级模块。 | +| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | DataAbilityOperation二级模块。 | +| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。 | +| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | +| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | +| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | StartAbilityParameter二级模块。 | **示例:** ```ts 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 daed6bc605c3ae6430f947f0d973591e62d506d5..4220b7883f52d7072d0447c1c3a7f0aef11f8287 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 @@ -25,7 +25,7 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\) 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -77,7 +77,7 @@ startAbility(parameter: StartAbilityParameter): Promise\ 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -128,7 +128,7 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper 使用规则: - 跨应用访问dataAbility,对端应用需配置关联启动 - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标dataAbility的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标dataAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -165,7 +165,7 @@ startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\ 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -218,7 +218,7 @@ startAbilityForResult(parameter: StartAbilityParameter): Promise\ 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -564,7 +564,7 @@ connectAbility(request: Want, options:ConnectOptions): number 使用规则: - 跨应用连接serviceAbility,对端应用需配置关联启动 - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标serviceAbility的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标serviceAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel 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 18e1da6b38a7925c334934fe2e43bf1b87b2e00a..ef0d0134d8a7f645ddd16d166a5086c0598a33e4 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 @@ -25,7 +25,7 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -75,7 +75,7 @@ startAbility(parameter: StartAbilityParameter): Promise\; 使用规则: - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标Ability的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -182,7 +182,7 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper 使用规则: - 跨应用访问dataAbility,对端应用需配置关联启动 - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标dataAbility的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标dataAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel @@ -405,7 +405,7 @@ connectAbility(request: Want, options:ConnectOptions): number 使用规则: - 跨应用连接serviceAbility,对端应用需配置关联启动 - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - - 跨应用场景下,目标serviceAbility的exported属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 + - 跨应用场景下,目标serviceAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md) **系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index 9e315b85cdc38bc6882d8d08ad5c1667bf15e5fb..48cec6bed3381996252d478db696b20a8b3407a7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -414,9 +414,9 @@ import abilityManager from '@ohos.app.ability.abilityManager'; abilityManager.acquireShareData(1, (err, wantParam) => { if (err) { - console.error('acquireShareData fail, err: ${JSON.stringify(err)}'); + console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`); } else { - console.log('acquireShareData success, data: ${JSON.stringify(data)}'); + console.log(`acquireShareData success, data: ${JSON.stringify(data)}`); } }); @@ -448,10 +448,13 @@ acquireShareData(missionId: number): Promise<{[key: string]: Object}>; ```ts import abilityManager from '@ohos.app.ability.abilityManager'; - -abilityManager.acquireShareData(1).then((wantParam) => { - console.log('acquireShareData success, data: ${JSON.stringify(data)}'); -}).catch((err) => { - console.error('acquireShareData fail, err: ${JSON.stringify(err)}'); -}); +try { + abilityManager.acquireShareData(1).then((wantParam) => { + console.log(`acquireShareData success, data: ${JSON.stringify(data)}`); + }).catch((err) => { + console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`); + }); +} 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-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index bd6bccb49048fc3cdc49075e4b22f59a9e2c784c..6b864a63ac5748aa57d97536d44f53b0ce0107ef 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 @@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | FormExtensionContext二级模块。 | | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | ServiceExtensionContext二级模块。 | | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | EventHub二级模块。 | -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | PacMap二级模块。 | +| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | PacMap二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | 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 3ffc94c818de97cc9b2c1e515f89ecd0265f239f..640b08d8cd0ffe1a259e663a9df514bdc175a61b 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 @@ -32,6 +32,14 @@ on(type: 'error', observer: ErrorObserver): number; | -------- | -------- | | number | 观察器的index值,和观察器一一对应。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000003 | Id does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -71,6 +79,14 @@ off(type: 'error', observerId: number, callback: AsyncCallback\): void; | observerId | number | 是 | 由on方法返回的观察器的index值。 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000003 | Id does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -109,6 +125,14 @@ off(type: 'error', observerId: number): Promise\; | -------- | -------- | | Promise\ | 返回执行结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000003 | Id does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts 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 566ae59852950a9c918485661e57fee21474faae..4f41fa7a307f7584da825acbf4c8232799d837ce 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 @@ -122,6 +122,14 @@ off(type: 'mission', listenerId: number, callback: AsyncCallback<void>): v | listenerId | number | 是 | 系统任务状态监器法的index值,和监听器一一对应,由on方法返回。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300002 | Input error. The specified mission listener does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -209,6 +217,14 @@ off(type: 'mission', listenerId: number): Promise<void>; | -------- | -------- | | Promise<void> | promise方式返回执行结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300002 | Input error. The specified mission listener does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -624,6 +640,14 @@ lockMission(missionId: number, callback: AsyncCallback<void>): void; | missionId | number | 是 | 任务ID。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300001 | Mission not found. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -667,6 +691,14 @@ lockMission(missionId: number): Promise<void>; | -------- | -------- | | Promise<void> | promise方式返回执行结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300001 | Mission not found. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts import missionManager from '@ohos.app.ability.missionManager'; @@ -702,6 +734,14 @@ unlockMission(missionId: number, callback: AsyncCallback<void>): void; | missionId | number | 是 | 任务ID。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300001 | Mission not found. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts import missionManager from '@ohos.app.ability.missionManager'; @@ -744,6 +784,14 @@ unlockMission(missionId: number): Promise<void>; | -------- | -------- | | Promise<void> | promise方式返回执行结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300001 | Mission not found. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -924,6 +972,14 @@ moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void | missionId | number | 是 | 任务ID。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -963,6 +1019,14 @@ moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCall | options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动参数选项,用于指定任务切到前台时的窗口模式,设备ID等。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1007,6 +1071,14 @@ moveMissionToFront(missionId: number, options?: StartOptions): Promise<void&g | -------- | -------- | | Promise<void> | promise方式返回执行结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index b9ae553c8814f479412f04c6e016492306396727..0b908a0bd49caa2dcd9020a731818e17fa7af889 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -62,6 +62,25 @@ applyQuickFix(hapModuleQuickFixFiles: Array\, callback: AsyncCallback\ | 是 | 快速修复补丁文件(补丁文件需包含有效的文件路径)。 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 18500002 | Copy file failed, maybe not exist or inaccessible. | +| 18500008 | Internal error. | + +在打补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9)的参数返回给应用开发者。这部分错误码及错误信息如下: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 18500003 | Deploy hqf failed. | +| 18500004 | Switch hqf failed. | +| 18500005 | Delete hqf failed. | +| 18500006 | Load patch failed. | +| 18500007 | Unload patch failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + > 说明:调用applyQuickFix接口时,补丁文件所在路径为应用沙箱路径。沙箱路径的获取参考[获取应用的沙箱路径](js-apis-bundle-BundleInstaller.md#获取应用的沙箱路径),映射到设备上的路径为/proc/<应用进程Id>/root/沙箱路径。 **示例:** @@ -105,6 +124,25 @@ applyQuickFix(hapModuleQuickFixFiles: Array\): Promise\; | -------- | -------- | | Promise\ | 返回相应结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 18500002 | Copy file failed, maybe not exist or inaccessible. | +| 18500008 | Internal error. | + +在打补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9)的参数返回给应用开发者。这部分错误码及错误信息如下: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 18500003 | Deploy hqf failed. | +| 18500004 | Switch hqf failed. | +| 18500005 | Delete hqf failed. | +| 18500006 | Load patch failed. | +| 18500007 | Unload patch failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -139,6 +177,15 @@ getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\ | 是 | 应用的快速修复信息。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 18500001 | The bundle is not exist. | +| 18500008 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -180,6 +227,15 @@ getApplicationQuickFixInfo(bundleName: string): Promise\ | 返回应用的快速修复信息。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 18500001 | The bundle is not exist. | +| 18500008 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-startOptions.md index b372ed87892023e3a45bbbd46f67e853b1685138..b761614625d15acde69c7e0ad990544fd02ae0af 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-startOptions.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -33,7 +33,7 @@ import StartOptions from '@ohos.app.ability.StartOptions'; try { missionManager.getMissionInfos('', 10, (error, missions) => { if (error) { - console.error('getMissionInfos failed, error.code: ${error.code}, error.message: ${error.message}'); + console.error(`getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`); return; } console.log(`size = ${missions.length}`); 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 2301738bc5f83b30c6139ed963e20eac4c260930..da52ea4a49fc2b6c10123538a887f08ee4310357 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 @@ -358,7 +358,9 @@ call(method: string, data: rpc.Parcelable): Promise<void>; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 @@ -437,7 +439,9 @@ callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequ | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 @@ -505,10 +509,10 @@ release(): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 401 | Invalid input parameter. | | 16200001 | Caller released. The caller has been released. | | 16200002 | Callee invalid. The callee does not exist. | -| 16000050 | Internal Error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -542,6 +546,14 @@ release(): void; **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16200001 | Caller released. The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -588,6 +600,14 @@ release(): void; | -------- | -------- | -------- | -------- | | callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback) | 是 | 返回onRemoteStateChange回调结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16200001 | Caller released. The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -636,7 +656,7 @@ release(): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | +| 16200001 | Caller released. The caller has been released. | 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 @@ -681,13 +701,6 @@ off(type: 'release', callback: OnReleaseCallback): void; | type | string | 是 | 监听releaseCall事件,固定为'release'。 | | callback | [OnReleaseCallback](#onreleasecallback) | 是 | 返回off回调结果。 | -**错误码:** - -| 错误码ID | 错误信息 | -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | -其他ID见[元能力子系统错误码](../errorcodes/errorcode-ability.md) - **示例:** ```ts @@ -730,13 +743,6 @@ off(type: 'release'): void; | -------- | -------- | -------- | -------- | | type | string | 是 | 监听releaseCall事件,固定为'release'。 | -**错误码:** - -| 错误码ID | 错误信息 | -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | -其他ID见[元能力子系统错误码](../errorcodes/errorcode-ability.md) - **示例:** ```ts @@ -788,7 +794,8 @@ on(method: string, callback: CalleeCallback): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | +| 16200004 | Method registered. The method has registered. | +| 16000050 | Internal error. | 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 @@ -853,7 +860,8 @@ off(method: string): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | +| 16200005 | Method not registered. The method has not registered. | +| 16000050 | Internal error. | 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md index 540592747ed6c478f156cfb3fe9aea85e2bebb6b..be50fee49f3337029f03f67e39383cfc4a49366b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -28,31 +28,13 @@ getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 创建WantAgent的回调方法。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -125,31 +107,13 @@ getWantAgent(info: WantAgentInfo): Promise\ | Promise\ | 以Promise形式返回WantAgent。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -211,31 +175,13 @@ getBundleName(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 获取WantAgent实例的包名的回调方法。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -321,31 +267,13 @@ getBundleName(agent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取WantAgent实例的包名。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -422,31 +350,13 @@ getUid(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 获取WantAgent实例的用户ID的回调方法。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -533,31 +443,13 @@ getUid(agent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取WantAgent实例的用户ID。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -635,31 +527,14 @@ getWant(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | 是 | 获取WantAgent对象want的回调方法。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| +| 16000015 | Service timeout.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -747,31 +622,14 @@ getWant(agent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取WantAgent对象的want。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| +| 16000015 | Service timeout.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -848,31 +706,13 @@ cancel(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 取消WantAgent实例的回调方法。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -958,31 +798,13 @@ cancel(agent: WantAgent): Promise\ | Promise\ | 以Promise形式获取异步返回结果。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -1057,33 +879,6 @@ trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\ | 否 | 主动激发WantAgent实例的回调方法。 | -**错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) -| 错误码ID | 错误信息 | -|-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| -| 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| - **示例:** ```ts @@ -1167,33 +962,6 @@ equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\ | 是 | 判断两个WantAgent实例是否相等的回调方法。 | -**错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) -| 错误码ID | 错误信息 | -|-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| -| 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| - **示例:** ```ts @@ -1280,33 +1048,6 @@ equal(agent: WantAgent, otherAgent: WantAgent): Promise\ | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回获取判断两个WantAgent实例是否相等的结果。 | -**错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) -| 错误码ID | 错误信息 | -|-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| -| 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| - **示例:** ```ts @@ -1382,31 +1123,14 @@ getOperationType(agent: WantAgent, callback: AsyncCallback\): void; | callback | AsyncCallback\ | 是 | 获取一个WantAgent的OperationType信息的回调方法。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| +| 16000015 | Service timeout.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -1490,31 +1214,14 @@ getOperationType(agent: WantAgent): Promise\; | Promise\ | 以Promise形式返回获取operationType的结果。 | **错误码:** -错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + | 错误码ID | 错误信息 | |-----------|--------------------| -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong.| -| 16000003 | Input error. The specified id does not exist.| -| 16000004 | Visibility verification failed.| -| 16000006 | Can not cross user operations.| | 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| -| 16000008 | Crowdtest App Expiration.| -| 16000009 | Can not start ability in wukong mode.| -| 16000010 | Can not operation with continue flag.| -| 16000011 | Context does not exist.| -| 16000050 | Internal Error.| -| 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The applicaiotn dose not support free install.| -| 16000053 | Not top ability. The application is not top ability.| -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| -| 16000055 | Free install timeout.| -| 16000056 | Can not free install other ability.| -| 16000057 | Not support cross device free install.| -| 16000101 | execute shell command failed.| +| 16000015 | Service timeout.| | 16000151 | Invalid wantagent object.| -| 16000152 | wantAgent object not found.| -| 16000153 | wangAgent object canceled.| + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** 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 67da9ed4ddafd4f68b1adc2f2c0a8d1d3d2d162b..6ae0d2a5caa5faacd943fe578668e5ad2e3f6d90 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 @@ -23,6 +23,7 @@ want的Params操作的常量。 | 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**:该接口为系统接口,三方应用不支持调用。 | +| ABILITY_RECOVERY_RESTART | ohos.ability.params.abilityRecoveryRestart | 指示当前Ability是否发生了故障恢复重启。 | | CONTENT_TITLE_KEY | ohos.extra.param.key.contentTitle | 指示原子化服务支持分享标题的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | | SHARE_ABSTRACT_KEY | ohos.extra.param.key.shareAbstract | 指示原子化服务支持分享内容的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | | SHARE_URL_KEY | ohos.extra.param.key.shareUrl | 指示原子化服务支持分享链接的参数的操作。
**系统API**:该接口为系统接口,三方应用不支持调用。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md index d12a34d5b0e790448ffff671b0ab2203b5e8939c..cc094eba4f7a6360fe4c6edaa5aa895f75623aff 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -34,7 +34,14 @@ deleteForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 202 | The application is not a system application. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -83,7 +90,14 @@ deleteForm(formId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **参数:** @@ -124,7 +138,14 @@ releaseForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -166,7 +187,14 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback< | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -201,7 +229,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------ | ---- | ----------- | | formId | string | 是 | 卡片标识。 | -| isReleaseCache | boolean | 否 | 是否释放缓存。 | +| isReleaseCache | boolean | 否 | 是否释放缓存,默认为false。 | **返回值:** @@ -213,7 +241,14 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -254,7 +289,14 @@ requestForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -300,7 +342,14 @@ requestForm(formId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -342,7 +391,14 @@ castToNormalForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501002 | The number of forms exceeds upper bound. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -388,7 +444,14 @@ castToNormalForm(formId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501002 | The number of forms exceeds upper bound. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -429,7 +492,12 @@ notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -475,7 +543,12 @@ notifyVisibleForms(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -516,7 +589,12 @@ notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<vo | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -562,7 +640,12 @@ notifyInvisibleForms(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -603,7 +686,13 @@ enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void& | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -649,7 +738,13 @@ enableFormsUpdate(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -690,7 +785,14 @@ disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -736,7 +838,14 @@ disableFormsUpdate(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -770,6 +879,14 @@ isSystemReady(callback: AsyncCallback<void>): void | ------ | ------ | ---- | ------- | | callback | AsyncCallback<void> | 是 | 回调函数。当检查系统是否准备好成功,error为undefined,否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -800,6 +917,13 @@ isSystemReady(): Promise<void> | -------- | -------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -826,6 +950,18 @@ getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): **系统能力**:SystemCapability.Ability.Form +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -860,6 +996,17 @@ getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> **系统能力**:SystemCapability.Ability.Form +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **返回值:** | 类型 | 说明 | @@ -903,7 +1050,13 @@ getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.Fo | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -946,7 +1099,13 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback< | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -982,7 +1141,7 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formI | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | bundleName | string | 是 | 要查询的应用Bundle名称。 | -| moduleName | string | 否 | 要查询的模块名称。 | +| moduleName | string | 否 | 要查询的模块名称,缺省默认为空。 | **返回值:** @@ -994,7 +1153,13 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formI | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1030,6 +1195,18 @@ deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<numb | formIds | Array<string> | 是 | 有效卡片标识列表。 | | callback | AsyncCallback<number> | 是 | 回调函数。当根据列表删除应用程序的无效卡片成功,error为undefined,data为删除的卡片个数;否则为错误对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -1071,6 +1248,18 @@ deleteInvalidForms(formIds: Array<string>): Promise<number> | :------------ | :---------------------------------- | | Promise<number> | Promise对象,返回删除的卡片个数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -1109,7 +1298,13 @@ acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo&g | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1166,7 +1361,13 @@ acquireFormState(want: Want): Promise<formInfo.FormStateInfo> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1210,6 +1411,14 @@ on(type: 'formUninstall', callback: Callback<string>): void | type | string | 是 | 填写'formUninstall',表示卡片卸载事件。 | | callback | Callback<string> | 是 | 回调函数。返回卡片标识。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -1236,6 +1445,14 @@ off(type: 'formUninstall', callback?: Callback<string>): void | type | string | 是 | 填写'formUninstall',表示卡片卸载事件。 | | callback | Callback<string> | 否 | 回调函数。返回卡片标识。缺省时,表示注销所有已注册事件回调。
需与对应on('formUninstall')的callback一致。| +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -1269,7 +1486,13 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: A | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1316,7 +1539,13 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise< | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1358,7 +1587,13 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, c | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1405,7 +1640,13 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1446,7 +1687,13 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>) | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1494,7 +1741,13 @@ shareForm(formId: string, deviceId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1535,9 +1788,14 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb **错误码:** -| 错误码ID | 错误信息 | -| ------------------------------------------------------------ | ------------------ | -| 401 | 调用接口入参错误。 | +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | | 以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 | | **示例:** @@ -1582,9 +1840,14 @@ function notifyFormsPrivacyProtected(formIds: Array\, isProtected: bool **错误码:** -| 错误码ID | 错误信息 | -| ------------------------------------------------------------ | ------------------ | -| 401 | 调用接口入参错误。 | +| 错误码ID | 错误信息 | +| -------- | -------- | +| 201 | Permissions denied. | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16501000 | An internal functional error occurred. | | 以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 | | ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md index 5e1b17549769c8d6155a9432129cc6c1becadc55..bf7e9556fc7cdc34e63b12be191eb246c33c1341 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -31,7 +31,14 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501002 | The number of forms exceeds upper bound. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -41,12 +48,12 @@ import formProvider from '@ohos.app.form.formProvider'; let formId = '12400633174999288'; try { - formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { + formProvider.setFormNextRefreshTime(formId, 5, (error) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log(`formProvider setFormNextRefreshTime success`); + return; } + console.log(`formProvider setFormNextRefreshTime success`); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -78,7 +85,14 @@ setFormNextRefreshTime(formId: string, minute: number): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501002 | The number of forms exceeds upper bound. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -118,7 +132,13 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -130,12 +150,12 @@ import formProvider from '@ohos.app.form.formProvider'; let formId = '12400633174999288'; try { let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); - formProvider.updateForm(formId, obj, (error, data) => { + formProvider.updateForm(formId, obj, (error) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log(`formProvider updateForm success`); + return; } + console.log(`formProvider updateForm success`); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -167,7 +187,13 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500060 | A service connection error happened, please try again later. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form can not be operated by the current application. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -204,10 +230,12 @@ getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): voi | callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到的卡片信息。 | **错误码:** - | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| @@ -220,9 +248,9 @@ try { formProvider.getFormsInfo((error, data) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); + return; } + console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -247,7 +275,10 @@ getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array&l | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -264,9 +295,9 @@ try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); + return; } + console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -285,7 +316,7 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.For | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | 否 | 卡片信息过滤器。 | +| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | 否 | 卡片信息过滤器, 默认为空,不进行过滤。 | **返回值:** @@ -297,7 +328,10 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.For | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -343,7 +377,11 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -365,9 +403,9 @@ try { formProvider.requestPublishForm(want, obj, (error, data) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); + return; } + console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -395,7 +433,11 @@ requestPublishForm(want: Want, callback: AsyncCallback<string>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -415,9 +457,9 @@ try { formProvider.requestPublishForm(want, (error, data) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); + return; } + console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -439,7 +481,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData | 参数名 | 类型 | 必填 | 说明 | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | 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-app-form-formBindingData.md#formbindingdata) | 否 | 创建卡片的数据。 | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | 否 | 创建卡片的数据,默认为空,不提供创建卡片数据。 | **返回值:** @@ -451,7 +493,11 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | 调用接口入参错误。 | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -494,6 +540,16 @@ isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void | ------ | ------ | ---- | ------- | | callback | AsyncCallback<boolean> | 是 | 回调函数。返回是否支持发布一张卡片到使用方。| +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts @@ -517,9 +573,9 @@ try { formProvider.requestPublishForm(want, (error, data) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); + return; } + console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); }); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message})`); @@ -548,6 +604,15 @@ isRequestPublishFormSupported(): Promise<boolean> | :------------ | :---------------------------------- | | Promise<boolean> | Promise对象。返回是否支持发布一张卡片到使用方。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 16500050 | An IPC connection error happened. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-want.md b/zh-cn/application-dev/reference/apis/js-apis-application-want.md index f028724c676fb7437c902c9ef45a7a795525bde2..184d2ee6fe82c73a60046da37d1b83473491ae73 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-want.md @@ -23,10 +23,10 @@ import Want from '@ohos.application.Want'; | abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | | uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | | type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:'text/xml' 、 'image/*'等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | -| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantConstant.Flags)。 | -| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md)。 | -| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | -| entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity)。 | +| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantconstantflags)。 | +| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-ability-wantConstant.md#wantconstantaction)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](../../application-models/explicit-implicit-want-mappings.md)。 | +| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | +| entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-ability-wantConstant.md#wantconstantentity)。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index d11cf7f204326c6826f63265a719df589d5c1741..1b26e4c82c793b7db094bf83d02894c23dd7fe1b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -485,8 +485,8 @@ async function createTonePlayerBefore(){ | 名称 | 值 | 说明 | | --------- | -------- | -------- | -| CHANNEL_1 | 0x1 << 0 | 单声道。 | -| CHANNEL_2 | 0x1 << 1 | 双声道。 | +| CHANNEL_1 | 0x1 << 0 | 第一声道。 | +| CHANNEL_2 | 0x1 << 1 | 第二声道。 | ## AudioSamplingRate8+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index c1e20856bc517f82791a6e365645d88015b9d1d3..5410dd74cd29becf202eb439a888ea9df22a4885 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -26,11 +26,11 @@ | iconId | string | 是 | 否 | 应用程序图标的资源id值。 | | process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称。 | | supportedModes | number | 是 | 否 | 标识应用支持的运行模式,当前只定义了驾驶模式(drive)。该标签只适用于车机。 | -| moduleSourceDirs | Array\ | 是 | 否 | 应用程序的资源存放的相对路径。 | +| moduleSourceDirs | Array\ | 是 | 否 | 应用程序的资源存放的相对路径。不能拼接路径访问资源文件,请使用[资源管理接口](js-apis-resource-manager.md)访问资源。 | | permissions | Array\ | 是 | 否 | 访问应用程序所需的权限。
通过调用[bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated)接口时,传入GET_APPLICATION_INFO_WITH_PERMISSION获取。 | | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | 是 | 否 | 应用程序的模块信息。 | -| entryDir | string | 是 | 否 | 应用程序的文件保存路径。 | -| codePath8+ | string | 是 | 否 | 应用程序的安装目录。 | +| entryDir | string | 是 | 否 | 应用程序的文件保存路径。不能拼接路径访问资源文件,请使用[资源管理接口](js-apis-resource-manager.md)访问资源。 | +| codePath8+ | string | 是 | 否 | 应用程序的安装目录。不能拼接路径访问资源文件,请使用[资源管理接口](js-apis-resource-manager.md)访问资源。 | | metaData8+ | Map\> | 是 | 否 | 应用程序的自定义元信息。
通过调用[bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated)接口时,传入GET_APPLICATION_INFO_WITH_METADATA获取。 | | removable8+ | boolean | 是 | 否 | 应用程序是否可以被移除。 | | accessTokenId8+ | number | 是 | 否 | 应用程序的accessTokenId。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index a3221812add7f5461b29281968e1fd24ae7c3c76..8cfbeddf13b70ba4de142d77d7c0d6289ea22aa4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -12,4 +12,4 @@ | 名称 | 类型 | 可读 | 可写 | 说明 | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | 是 | 否 | 模块名称。 | -| moduleSourceDir | string | 是 | 否 | 安装目录。 | \ No newline at end of file +| moduleSourceDir | string | 是 | 否 | 安装目录。不能拼接路径访问资源文件,请使用[资源管理接口](js-apis-resource-manager.md)访问资源。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-AppProvisionInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-AppProvisionInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..4327147b28e0c090f2c98825295be8ae79a277c6 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-AppProvisionInfo.md @@ -0,0 +1,36 @@ +# AppProvisionInfo + +应用[HarmonyAppProvision配置文件](../../security/app-provision-structure.md)中的信息,可以通过[getAppProvisionInfo](js-apis-bundleManager.md#bundlemanagergetappprovisioninfo10)获取。 + +> **说明:** +> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## AppProvisionInfo + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**系统接口:** 此接口为系统接口。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| versionCode | number | 是 | 否 | 配置文件的版本号。 | +| versionName | string | 是 | 否 | 配置文件的版本名称。 | +| uuid | string | 是 | 否 | 配置文件中的uuid。 | +| type | string | 是 | 否 | 配置文件的类型,为debug或者release。 | +| appDistributionType | string | 是 | 否 | 配置文件中的分发类型,为app_gallery、enterprise、os_integration和crowdtesting其中之一。 | +| validity | [Validity](#validity) | 是 | 否 | 配置文件中的有效期。 | +| developerId | string | 是 | 否 | 配置文件中的开发者ID。 | +| certificate | string | 是 | 否 | 配置文件中的证书公钥。 | +| apl | string | 是 | 否 | 配置文件中的apl字段,为normal、system_basic和system_core其中之一。 | +| issuer | string | 是 | 否 | 配置文件中的发行者名称。 | + +## Validity + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**系统接口:** 此接口为系统接口。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| notBefore | number | 是 | 否 | 配置文件的最早有效日期。 | +| notAfter | number | 是 | 否 | 配置文件的最晚有效日期。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md index 8cb105a93ae6b645e7a6918606bdb1c2e42ad73a..95d925883ee3a6bc3c7a7ac40c6002b05887cb92 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md @@ -3,7 +3,7 @@ > **说明:** > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -包含远程的ability信息,通过接口[distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundle.md)获取。 +包含远程的ability信息,通过接口[distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundleManager.md#distributedbundlegetremoteabilityinfo)获取。 ## RemoteAbilityInfo diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 67b3a567cde25339020af03a067b7a4d51f68791..2991bf1bf6718a06c8083f4680434f1813fd41ed 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -5,7 +5,7 @@ > **说明:** > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> FA模型配置在[config.json文件中进行配置](../../quick-start/module-structure.md#%E8%A1%A817-shortcuts%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%86%85%E9%83%A8%E7%BB%93%E6%9E%84%E8%AF%B4%E6%98%8E),Stage模型配置参考[shortcuts对象内部结构](../../quick-start/module-configuration-file.md#shortcuts标签)。 +> FA模型配置在[config.json文件中进行配置](../../quick-start/module-structure.md),Stage模型配置参考[shortcuts对象内部结构](../../quick-start/module-configuration-file.md#shortcuts标签)。 ## ShortcutWant diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md index ec34b0df17214771952f8307caca333203a74be9..5dcd85dcb0307a5aecab326370c50d9ef976a5de 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @@ -2947,7 +2947,7 @@ try { ### bundleManager.getSharedBundleInfo10+ -function getSharedBundleInfo(bundleName: string, moduleName: string): Promise\\>; +getSharedBundleInfo(bundleName: string, moduleName: string): Promise\\>; 以异步的方法获取指定的共享包信息,使用Promise形式返回结果。 @@ -3037,7 +3037,7 @@ try { ### bundleManager.getAllSharedBundleInfo10+ -function getAllSharedBundleInfo(): Promise\\>; +getAllSharedBundleInfo(): Promise\\>; 以异步的方法获取所有的共享包信息,使用Promise形式返回结果。 @@ -3070,3 +3070,164 @@ try { } ``` +### bundleManager.getAppProvisionInfo10+ + +getAppProvisionInfo(bundleName: string, callback: AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\>): void; + +以异步的方法获取指定bundleName的provision配置文件信息,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 指定应用的bundleName。 | +| callback | AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\> | 是 | 回调函数,当获取成功时,err为null,data为指定bundleName的provision配置文件信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; + +try { + bundleManager.getAppProvisionInfo(bundleName, (err, data) => { + if (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); + } else { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully: %{public}s', JSON.stringify(data)); + } + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); +} +``` + +### bundleManager.getAppProvisionInfo10+ + +getAppProvisionInfo(bundleName: string, userId: number, callback: AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\>): void; + +以异步的方法获取指定bundleName和userId的provision配置文件信息,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 指定应用的bundleName。 | +| userId | number | 是 | 指定用户ID, 可以通过接口[getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9)获取当前设备上的用户ID。 | +| callback | AsyncCallback\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\> | 是 | 回调函数,当获取成功时,err为null,data为指定bundleName的provision配置文件信息。 | + + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700004 | The specified user ID is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; +let userId = 100; + +try { + bundleManager.getAppProvisionInfo(bundleName, userId, (err, data) => { + if (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); + } else { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully: %{public}s', JSON.stringify(data)); + } + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed: %{public}s', err.message); +} +``` + +### bundleManager.getAppProvisionInfo10+ + +getAppProvisionInfo(bundleName: string, userId?: number): Promise\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\>; + +以异步的方法根据bundleName和userId获取应用的provision配置文件信息,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 指定的bundleName。 | +| userId | number | 否 | 指定的用户ID,可以通过接口[getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9)获取当前设备上的用户ID。 | + + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ----------------------------------- | +| Promise\<[AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)\> | Promise对象,返回应用的provision配置文件信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found. | +| 17700004 | The specified user ID is not found. | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleName = "com.ohos.myapplication"; +let userId = 100; + +try { + bundleManager.getAppProvisionInfo(bundleName).then((data) => { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); +} + +try { + bundleManager.getAppProvisionInfo(bundleName, userId).then((data) => { + hilog.info(0x0000, 'testTag', 'getAppProvisionInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md index 71359cac05b2716a4ed36012a18c4734cdc4e60b..8ed865ef1cf2b5265c43037b8ef1a125d92ce2ea 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @@ -37,6 +37,14 @@ publish(event: string, callback: AsyncCallback): void 错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 401 | The parameter check failed. | +| 1500004 | not System services. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | +| 1500009 | error obtaining system parameters. | + **示例:** ```ts @@ -77,6 +85,14 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback< 错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 401 | The parameter check failed. | +| 1500004 | not System services. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | +| 1500009 | error obtaining system parameters. | + **示例:** ```ts @@ -126,6 +142,15 @@ publishAsUser(event: string, userId: number, callback: AsyncCallback): voi 错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 202 | not system app. | +| 401 | The parameter check failed. | +| 1500004 | not System services. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | +| 1500009 | error obtaining system parameters. | + **示例:** ```ts @@ -172,6 +197,15 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca 错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 202 | not system app. | +| 401 | The parameter check failed. | +| 1500004 | not System services. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | +| 1500009 | error obtaining system parameters. | + **示例:** @@ -217,6 +251,14 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac | subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | 是 | 表示订阅信息。 | | callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | 是 | 表示创建订阅者的回调方法。 | +**错误码:** + +错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 401 | The parameter check failed. | + **示例:** @@ -265,6 +307,14 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise | 返回订阅者对象。 | +**错误码:** + +错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 401 | The parameter check failed. | + **示例:** ```ts @@ -300,6 +350,17 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback | 是 | 表示接收公共事件数据的回调函数。 | +**错误码:** + +错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 401 | The parameter check failed. | +| 801 | capability not supported. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | + **示例:** ```ts @@ -359,6 +420,17 @@ unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback): | subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | 是 | 表示订阅者对象。 | | callback | AsyncCallback\ | 否 | 表示取消订阅的回调方法。 | +**错误码:** + +错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 401 | The parameter check failed. | +| 801 | capability not supported. | +| 1500007 | error sending message to Common Event Service. | +| 1500008 | Common Event Service does not complete initialization. | + **示例:** ```ts @@ -430,6 +502,19 @@ removeStickyCommonEvent(event: string, callback: AsyncCallback): void | event | string | 是 | 表示被移除的粘性公共事件。 | | callback | AsyncCallback\ | 是 | 表示移除粘性公共事件的回调方法。 | +**错误码:** + +错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 201 | The application dose not have permission to call the interface. | +| 202 | not system app. | +| 401 | The parameter check failed. | +| 1500004 | not system service. | +| 1500007 | The message send error. | +| 1500008 | The CEMS error. | + **示例:** @@ -466,6 +551,19 @@ removeStickyCommonEvent(event: string): Promise | -------------- | ---------------------------- | | Promise\ | 表示移除粘性公共事件的对象。 | +**错误码:** + +错误码介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 201 | The application dose not have permission to call the interface. | +| 202 | not system app. | +| 401 | The parameter check failed. | +| 1500004 | not system service. | +| 1500007 | The message send error. | +| 1500008 | The CEMS error. | + **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md index d2a9c901ca3fe2b2471c0696f14bdf255d48d454..a7a8b4022dc7b7b3d0214dfa63eb56d07b8af958 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @@ -16,6 +16,8 @@ >- 从API Version 9开始,该接口不再维护,推荐使用新接口[`@ohos.data.distributedKVStore`](js-apis-distributedKVStore.md)。 > >- 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +>- 本模块中所有需要获取deviceId的接口,都仅系统应用可用。 ## 导入模块 @@ -88,25 +90,22 @@ createKVManager(config: KVManagerConfig): Promise<KVManager> **示例:** ```js -let kvManager; try { - const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + const kvManagerConfig = { + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Succeeded in creating KVManager"); - kvManager = manager; - }); + } + distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("Succeeded in creating KVManager"); + kvManager = manager; + }).catch((err) => { + console.error("Failed to create KVManager: " + JSON.stringify(err)); + }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error:" + e); } ``` @@ -2012,6 +2011,10 @@ try { deviceId(deviceId:string):Query 添加设备ID作为key的前缀。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -3664,6 +3667,10 @@ try { removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 删除指定设备的数据,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -3706,6 +3713,10 @@ try { removeDeviceData(deviceId: string): Promise<void> 删除指定设备的数据,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -4084,6 +4095,10 @@ try { get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void 获取与指定设备ID和key匹配的string值,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4119,6 +4134,10 @@ try{ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> 获取与指定设备ID和key匹配的string值,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4163,6 +4182,10 @@ try { getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void 获取与指定设备ID和key前缀匹配的所有键值对,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4211,6 +4234,10 @@ try { getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> 获取与指定设备ID和key前缀匹配的所有键值对,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4380,6 +4407,10 @@ try { getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void 获取与指定设备ID和Query对象匹配的键值对列表,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4433,6 +4464,10 @@ try { getEntries(deviceId: string, query: Query): Promise<Entry[]> 获取与指定设备ID和Query对象匹配的键值对列表,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4493,6 +4528,10 @@ try { getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void 获取与指定设备ID和key前缀匹配的KvStoreResultSet对象,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4528,6 +4567,10 @@ try { getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> 获取与指定设备ID和key前缀匹配的KvStoreResultSet对象,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4688,6 +4731,10 @@ try { getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void 获取与指定设备ID和Query对象匹配的KvStoreResultSet对象,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4740,6 +4787,10 @@ try { getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> 获取与指定设备ID和Query对象匹配的KvStoreResultSet对象,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4982,6 +5033,10 @@ try { getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; 获取与指定设备ID和Query对象匹配的结果数,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5029,6 +5084,10 @@ try { getResultSize(deviceId: string, query: Query): Promise<number> 获取与指定设备ID和Query对象匹配的结果数,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5085,6 +5144,10 @@ try { removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 从当前数据库中删除指定设备的数据,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5127,6 +5190,10 @@ try { removeDeviceData(deviceId: string): Promise<void> 从当前数据库中删除指定设备的数据,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md index ccf2915c953c2a8fca6f5978cd60d8b4235d332e..6f22a81e047fac925f76a4a07719950e07410d64 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -13,6 +13,7 @@ > **说明:** > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +>
本模块中所有需要获取deviceId的接口,都仅系统应用可用。 ## 导入模块 @@ -28,7 +29,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; | 名称 | 类型 | 必填 | 说明 | | ---------- | --------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。
从API version 10开始,context的参数类型为[BaseContext](js-apis-inner-application-baseContext.md)。 | | bundleName | string | 是 | 调用方的包名。 | ## Constants @@ -41,7 +42,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; | --------------------- | ------- | --------------------------------------- | | MAX_KEY_LENGTH | 1024 | 数据库中Key允许的最大长度,单位字节。 | | MAX_VALUE_LENGTH | 4194303 | 数据库中Value允许的最大长度,单位字节。 | -| MAX_KEY_LENGTH_DEVICE | 896 | 最大设备密钥长度,单位字节。 | +| MAX_KEY_LENGTH_DEVICE | 896 | 设备协同数据库中key允许的最大长度,单位字节。 | | MAX_STORE_ID_LENGTH | 128 | 数据库标识符允许的最大长度,单位字节。 | | MAX_QUERY_LENGTH | 512000 | 最大查询长度,单位字节。 | | MAX_BATCH_SIZE | 128 | 最大批处理操作数量。 | @@ -137,10 +138,10 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; | 名称 | 说明 | | -------: | ------------------------------------------------------------ | -| S1 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | -| S2 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | -| S3 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | -| S4 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | +| S1 | 表示数据库的安全级别为低级别,数据的泄露、篡改、破坏、销毁可能会给个人或组织导致有限的不利影响。
例如,性别、国籍,用户申请记录等。 | +| S2 | 表示数据库的安全级别为中级别,数据的泄露、篡改、破坏、销毁可能会给个人或组织导致严重的不利影响。
例如,个人详细通信地址,姓名昵称等。 | +| S3 | 表示数据库的安全级别为高级别,数据的泄露、篡改、破坏、销毁可能会给个人或组织导致严峻的不利影响。
例如,个人实时精确定位信息、运动轨迹等。 | +| S4 | 表示数据库的安全级别为关键级别,业界法律法规中定义的特殊数据类型,涉及个人的最私密领域的信息或者一旦泄露、篡改、破坏、销毁可能会给个人或组织造成重大的不利影响数据。
例如,政治观点、宗教、和哲学信仰、工会成员资格、基因数据、生物信息、健康和性生活状况、性取向等或设备认证鉴权、个人的信用卡等财务信息。 | ## Options @@ -226,23 +227,22 @@ appendChild(child: FieldNode): boolean **示例:** ```js -import ddm from '@ohos.data.distributedKVStore'; try { - let node = new ddm.FieldNode("root"); - let child1 = new ddm.FieldNode("child1"); - let child2 = new ddm.FieldNode("child2"); - let child3 = new ddm.FieldNode("child3"); + let node = new distributedKVStore.FieldNode("root"); + let child1 = new distributedKVStore.FieldNode("child1"); + let child2 = new distributedKVStore.FieldNode("child2"); + let child3 = new distributedKVStore.FieldNode("child3"); node.appendChild(child1); node.appendChild(child2); node.appendChild(child3); - console.log("appendNode " + JSON.stringify(node)); + console.info("appendNode " + JSON.stringify(node)); child1 = null; child2 = null; child3 = null; node = null; } catch (e) { - console.log("AppendChild " + e); + console.error("AppendChild " + e); } ``` @@ -276,7 +276,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; let kvManager; export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbilityStage onCreate") + console.info("MyAbilityStage onCreate") let context = this.context const kvManagerConfig = { context: context, @@ -284,7 +284,7 @@ export default class EntryAbility extends UIAbility { } try { kvManager = distributedKVStore.createKVManager(kvManagerConfig); - console.log("Succeeded in creating KVManager"); + console.info("Succeeded in creating KVManager"); } catch (e) { console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); } @@ -304,7 +304,7 @@ const kvManagerConfig = { } try { kvManager = distributedKVStore.createKVManager(kvManagerConfig); - console.log("Succeeded in creating KVManager"); + console.info("Succeeded in creating KVManager"); } catch (e) { console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); } @@ -316,7 +316,7 @@ try { ### getKVStore -getKVStore<T >(storeId: string, options: Options, callback: AsyncCallback<T>): void +getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void 通过指定Options和storeId,创建并获取分布式键值数据库,使用callback异步回调。 @@ -343,7 +343,6 @@ getKVStore<T >(storeId: string, options: Options, callback: AsyncCallback& ```js let kvStore; -let kvManager; try { const options = { createIfMissing: true, @@ -355,20 +354,20 @@ try { }; kvManager.getKVStore('storeId', options, function (err, store) { if (err) { - console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log("Succeeded in getting KVStore"); + console.info("Succeeded in getting KVStore"); kvStore = store; }); } catch (e) { - console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` ### getKVStore -getKVStore<T >(storeId: string, options: Options): Promise<T> +getKVStore<T>(storeId: string, options: Options): Promise<T> 通过指定Options和storeId,创建并获取分布式键值数据库,使用Promise异步回调。 @@ -400,7 +399,6 @@ getKVStore<T >(storeId: string, options: Options): Promise<T> ```js let kvStore; -let kvManager; try { const options = { createIfMissing: true, @@ -411,13 +409,13 @@ try { securityLevel: distributedKVStore.SecurityLevel.S2, }; kvManager.getKVStore('storeId', options).then((store) => { - console.log("Succeeded in getting KVStore"); + console.info("Succeeded in getting KVStore"); kvStore = store; }).catch((err) => { - console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` @@ -440,8 +438,6 @@ closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void> **示例:** ```js -let kvStore; -let kvManager; const options = { createIfMissing: true, encrypt: false, @@ -453,14 +449,20 @@ const options = { } try { kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('Succeeded in getting KVStore'); + if (err != undefined) { + console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in getting KVStore'); kvStore = store; + kvStore = null; + store = null; kvManager.closeKVStore('appId', 'storeId', function (err, data) { if (err != undefined) { - console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing KVStore'); + console.info('Succeeded in closing KVStore'); }); }); } catch (e) { @@ -492,8 +494,6 @@ closeKVStore(appId: string, storeId: string): Promise<void> **示例:** ```js -let kvManager; -let kvStore; const options = { createIfMissing: true, encrypt: false, @@ -505,18 +505,20 @@ const options = { } try { kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('Succeeded in getting KVStore'); + console.info('Succeeded in getting KVStore'); kvStore = store; + kvStore = null; + store = null; kvManager.closeKVStore('appId', 'storeId').then(() => { - console.log('Succeeded in closing KVStore'); + console.info('Succeeded in closing KVStore'); }).catch((err) => { - console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to close KVStore.code is ${e.code},message is ${e.message}`); + console.error(`Failed to close KVStore.code is ${e.code},message is ${e.message}`); } ``` @@ -547,8 +549,6 @@ deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void> **示例:** ```js -let kvManager; -let kvStore; const options = { createIfMissing: true, encrypt: false, @@ -561,21 +561,23 @@ const options = { try { kvManager.getKVStore('store', options, async function (err, store) { if (err != undefined) { - console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting KVStore'); + console.info('Succeeded in getting KVStore'); kvStore = store; + kvStore = null; + store = null; kvManager.deleteKVStore('appId', 'storeId', function (err, data) { if (err != undefined) { - console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); return; } - console.log(`Succeeded in deleting KVStore`); + console.info(`Succeeded in deleting KVStore`); }); }); } catch (e) { - console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); + console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`); } ``` @@ -611,8 +613,6 @@ deleteKVStore(appId: string, storeId: string): Promise<void> **示例:** ```js -let kvManager; -let kvStore; const options = { createIfMissing: true, encrypt: false, @@ -624,18 +624,20 @@ const options = { } try { kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('Succeeded in getting KVStore'); + console.info('Succeeded in getting KVStore'); kvStore = store; + kvStore = null; + store = null; kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('Succeeded in deleting KVStore'); + console.info('Succeeded in deleting KVStore'); }).catch((err) => { - console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); + console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`); } ``` @@ -657,18 +659,17 @@ getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void **示例:** ```js -let kvManager; try { kvManager.getAllKVStoreId('appId', function (err, data) { if (err != undefined) { - console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting AllKVStoreId'); - console.log(`GetAllKVStoreId size = ${data.length}`); + console.info('Succeeded in getting AllKVStoreId'); + console.info(`GetAllKVStoreId size = ${data.length}`); }); } catch (e) { - console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`); } ``` @@ -695,17 +696,16 @@ getAllKVStoreId(appId: string): Promise<string[]> **示例:** ```js -let kvManager; try { - console.log('GetAllKVStoreId'); + console.info('GetAllKVStoreId'); kvManager.getAllKVStoreId('appId').then((data) => { - console.log('Succeeded in getting AllKVStoreId'); - console.log(`GetAllKVStoreId size = ${data.length}`); + console.info('Succeeded in getting AllKVStoreId'); + console.info(`GetAllKVStoreId size = ${data.length}`); }).catch((err) => { - console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`); } ``` @@ -713,7 +713,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -订阅服务状态变更通知。 +订阅服务状态变更通知。如果服务终止,需要重新注册数据变更通知和同步完成事件回调通知,并且同步操作会返回失败。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -727,15 +727,14 @@ on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): voi **示例:** ```js -let kvManager; try { - console.log('KVManagerOn'); + console.info('KVManagerOn'); const deathCallback = function () { - console.log('death callback call'); + console.info('death callback call'); } kvManager.on('distributedDataServiceDie', deathCallback); } catch (e) { - console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` @@ -743,7 +742,7 @@ try { off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -取消订阅服务状态变更通知。 +取消订阅服务状态变更通知。参数中的deathCallback必须是已经订阅过的deathCallback,否则会取消订阅失败。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -752,26 +751,25 @@ off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): v | 参数名 | 类型 | 必填 | 说明 | | ------------- | -------------------- | ---- | ------------------------------------------------------------ | | event | string | 是 | 取消订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。 | -| deathCallback | Callback<void> | 否 | 回调函数。 | +| deathCallback | Callback<void> | 否 | 回调函数。如果该参数不填,那么会将之前订阅过的所有的deathCallback取消订阅。 | **示例:** ```js -let kvManager; try { - console.log('KVManagerOff'); + console.info('KVManagerOff'); const deathCallback = function () { - console.log('death callback call'); + console.info('death callback call'); } kvManager.off('distributedDataServiceDie', deathCallback); } catch (e) { - console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` ## KVStoreResultSet -提供获取数据库结果集的相关方法,包括查询和移动数据读取位置等。 +提供获取数据库结果集的相关方法,包括查询和移动数据读取位置等。同时允许打开的结果集的最大数量为8个。 在调用KVStoreResultSet的方法前,需要先通过[getKVStore](#getkvstore)构建一个SingleKVStore或者DeviceKVStore实例。 @@ -792,19 +790,19 @@ getCount(): number **示例:** ```js -let kvStore; try { let resultSet; + let count; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + count = resultSet.getCount(); + console.info("getCount succeed:" + count); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const count = resultSet.getCount(); - console.log("getCount succeed:" + count); } catch (e) { - console.log("getCount failed: " + e); + console.error("getCount failed: " + e); } ``` @@ -812,7 +810,7 @@ try { getPosition(): number -获取结果集中当前的读取位置。 +获取结果集中当前的读取位置。读取位置会因[moveToFirst](#movetofirst)、[moveToLast](#movetolast)等操作而发生变化。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -820,24 +818,24 @@ getPosition(): number | 类型 | 说明 | | ------ | ------------------ | -| number | 返回当前读取位置。 | +| number | 返回当前读取位置。取值范围>= -1,值为 -1 时表示还未开始读取,值为 0 时表示第一行。 | **示例:** ```js -let kvStore; try { let resultSet; + let position; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeeded.'); + console.info('getResultSet succeeded.'); resultSet = result; + position = resultSet.getPosition(); + console.info("getPosition succeed:" + position); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const position = resultSet.getPosition(); - console.log("getPosition succeed:" + position); } catch (e) { - console.log("getPosition failed: " + e); + console.error("getPosition failed: " + e); } ``` @@ -858,19 +856,19 @@ moveToFirst(): boolean **示例:** ```js -let kvStore; try { let resultSet; + let moved; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + moved = resultSet.moveToFirst(); + console.info("moveToFirst succeed: " + moved); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const moved1 = resultSet.moveToFirst(); - console.log("moveToFirst succeed: " + moved1); } catch (e) { - console.log("moveToFirst failed " + e); + console.error("moveToFirst failed " + e); } ``` @@ -891,19 +889,19 @@ moveToLast(): boolean **示例:** ```js -let kvStore; try { let resultSet; + let moved; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + moved = resultSet.moveToLast(); + console.info("moveToLast succeed:" + moved); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const moved2 = resultSet.moveToLast(); - console.log("moveToLast succeed:" + moved2); } catch (e) { - console.log("moveToLast failed: " + e); + console.error("moveToLast failed: " + e); } ``` @@ -911,7 +909,7 @@ try { moveToNext(): boolean -将读取位置移动到下一行。如果结果集为空,则返回false。 +将读取位置移动到下一行。如果结果集为空,则返回false。适用于全量获取数据库结果集的场景。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -924,19 +922,22 @@ moveToNext(): boolean **示例:** ```js -let kvStore; try { let resultSet; + let moved; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + do { + moved = resultSet.moveToNext(); + const entry = resultSet.getEntry(); + console.info("moveToNext succeed: " + moved); + } while (moved) }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const moved3 = resultSet.moveToNext(); - console.log("moveToNext succeed: " + moved3); } catch (e) { - console.log("moveToNext failed: " + e); + console.error("moveToNext failed: " + e); } ``` @@ -944,7 +945,7 @@ try { moveToPrevious(): boolean -将读取位置移动到上一行。如果结果集为空,则返回false。 +将读取位置移动到上一行。如果结果集为空,则返回false。适用于全量获取数据库结果集的场景。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -957,19 +958,20 @@ moveToPrevious(): boolean **示例:** ```js -let kvStore; try { let resultSet; + let moved; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + moved = resultSet.moveToLast(); + moved = resultSet.moveToPrevious(); + console.info("moveToPrevious succeed:" + moved); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const moved4 = resultSet.moveToPrevious(); - console.log("moveToPrevious succeed:" + moved4); } catch (e) { - console.log("moveToPrevious failed: " + e); + console.error("moveToPrevious failed: " + e); } ``` @@ -977,7 +979,7 @@ try { move(offset: number): boolean -将读取位置移动到当前位置的相对偏移量。 +将读取位置移动到当前位置的相对偏移量。即当前游标位置向下偏移 offset 行。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -996,19 +998,19 @@ move(offset: number): boolean **示例:** ```js -let kvStore; try { let resultSet; + let moved; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Succeeded in getting resultSet'); + console.info('Succeeded in getting resultSet'); resultSet = result; + moved = resultSet.move(2); //若当前位置为0,将读取位置从绝对位置为0的位置移动2行,即移动到绝对位置为2,行数为3的位置 + console.info(`Succeeded in moving.moved = ${moved}`); }).catch((err) => { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); }); - const moved5 = resultSet.move(1); - console.log(`Succeeded in moving.moved5 = ${moved5}`); } catch (e) { - console.log(`Fail to move.code is ${e.code},message is ${e.message}`); + console.error(`Failed to move.code is ${e.code},message is ${e.message}`); } ``` @@ -1035,19 +1037,19 @@ moveToPosition(position: number): boolean **示例** ```js -let kvStore; try { let resultSet; + let moved; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Succeeded in getting resultSet'); + console.info('Succeeded in getting resultSet'); resultSet = result; + moved = resultSet.moveToPosition(1); + console.info(`Succeeded in moving to position.moved=${moved}`); }).catch((err) => { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); }); - const moved6 = resultSet.moveToPosition(1); - console.log(`Succeeded in moving to position.moved6=${moved6}`); } catch (e) { - console.error(`Fail to move to position.code is ${e.code},message is ${e.message}`); + console.error(`Failed to move to position.code is ${e.code},message is ${e.message}`); } ``` @@ -1068,19 +1070,19 @@ isFirst(): boolean **示例:** ```js -let kvStore; try { let resultSet; + let isfirst; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + isfirst = resultSet.isFirst(); + console.info("Check isFirst succeed:" + isfirst); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const isfirst = resultSet.isFirst(); - console.log("Check isFirst succeed:" + isfirst); } catch (e) { - console.log("Check isFirst failed: " + e); + console.error("Check isFirst failed: " + e); } ``` @@ -1101,19 +1103,19 @@ isLast(): boolean **示例:** ```js -let kvStore; try { let resultSet; + let islast; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + islast = resultSet.isLast(); + console.info("Check isLast succeed: " + islast); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const islast = resultSet.isLast(); - console.log("Check isLast succeed: " + islast); } catch (e) { - console.log("Check isLast failed: " + e); + console.error("Check isLast failed: " + e); } ``` @@ -1134,19 +1136,18 @@ isBeforeFirst(): boolean **示例:** ```js -let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + const isbeforefirst = resultSet.isBeforeFirst(); + console.info("Check isBeforeFirst succeed: " + isbeforefirst); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const isbeforefirst = resultSet.isBeforeFirst(); - console.log("Check isBeforeFirst succeed: " + isbeforefirst); } catch (e) { - console.log("Check isBeforeFirst failed: " + e); + console.error("Check isBeforeFirst failed: " + e); } ``` @@ -1167,19 +1168,18 @@ isAfterLast(): boolean **示例:** ```js -let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + const isafterlast = resultSet.isAfterLast(); + console.info("Check isAfterLast succeed:" + isafterlast); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const isafterlast = resultSet.isAfterLast(); - console.log("Check isAfterLast succeed:" + isafterlast); } catch (e) { - console.log("Check isAfterLast failed: " + e); + console.error("Check isAfterLast failed: " + e); } ``` @@ -1200,25 +1200,24 @@ getEntry(): Entry **示例:** ```js -let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); + console.info('getResultSet succeed.'); resultSet = result; + const entry = resultSet.getEntry(); + console.info("getEntry succeed:" + JSON.stringify(entry)); }).catch((err) => { - console.log('getResultSet failed: ' + err); + console.error('getResultSet failed: ' + err); }); - const entry = resultSet.getEntry(); - console.log("getEntry succeed:" + JSON.stringify(entry)); } catch (e) { - console.log("getEntry failed: " + e); + console.error("getEntry failed: " + e); } ``` ## Query -使用谓词表示数据库查询,提供创建Query实例、查询数据库中的数据和添加谓词的方法。 +使用谓词表示数据库查询,提供创建Query实例、查询数据库中的数据和添加谓词的方法。一个Query对象中谓词数量上限为256个。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -1250,12 +1249,12 @@ reset(): Query try { let query = new distributedKVStore.Query(); query.equalTo("key", "value"); - console.log("query is " + query.getSqlLike()); + console.info("query is " + query.getSqlLike()); query.reset(); - console.log("query is " + query.getSqlLike()); + console.info("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("simply calls should be ok :" + e); + console.error("simply calls should be ok :" + e); } ``` @@ -1286,7 +1285,7 @@ equalTo(field: string, value: number|string|boolean): Query try { let query = new distributedKVStore.Query(); query.equalTo("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`); @@ -1320,7 +1319,7 @@ notEqualTo(field: string, value: number|string|boolean): Query try { let query = new distributedKVStore.Query(); query.notEqualTo("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1353,7 +1352,7 @@ greaterThan(field: string, value: number|string|boolean): Query try { let query = new distributedKVStore.Query(); query.greaterThan("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1388,7 +1387,7 @@ lessThan(field: string, value: number|string): Query try { let query = new distributedKVStore.Query(); query.lessThan("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1423,7 +1422,7 @@ greaterThanOrEqualTo(field: string, value: number|string): Query try { let query = new distributedKVStore.Query(); query.greaterThanOrEqualTo("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1458,7 +1457,7 @@ lessThanOrEqualTo(field: string, value: number|string): Query try { let query = new distributedKVStore.Query(); query.lessThanOrEqualTo("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1491,7 +1490,7 @@ isNull(field: string): Query try { let query = new distributedKVStore.Query(); query.isNull("field"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1525,7 +1524,7 @@ inNumber(field: string, valueList: number[]): Query try { let query = new distributedKVStore.Query(); query.inNumber("field", [0, 1]); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1559,7 +1558,7 @@ inString(field: string, valueList: string[]): Query try { let query = new distributedKVStore.Query(); query.inString("field", ['test1', 'test2']); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1593,7 +1592,7 @@ notInNumber(field: string, valueList: number[]): Query try { let query = new distributedKVStore.Query(); query.notInNumber("field", [0, 1]); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1627,7 +1626,7 @@ notInString(field: string, valueList: string[]): Query try { let query = new distributedKVStore.Query(); query.notInString("field", ['test1', 'test2']); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1661,7 +1660,7 @@ like(field: string, value: string): Query try { let query = new distributedKVStore.Query(); query.like("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1695,7 +1694,7 @@ unlike(field: string, value: string): Query try { let query = new distributedKVStore.Query(); query.unlike("field", "value"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1724,10 +1723,10 @@ try { query.notEqualTo("field", "value1"); query.and(); query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); + console.info("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("duplicated calls should be ok :" + e); + console.error("duplicated calls should be ok :" + e); } ``` @@ -1753,10 +1752,10 @@ try { query.notEqualTo("field", "value1"); query.or(); query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); + console.info("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("duplicated calls should be ok :" + e); + console.error("duplicated calls should be ok :" + e); } ``` @@ -1787,7 +1786,7 @@ try { let query = new distributedKVStore.Query(); query.notEqualTo("field", "value"); query.orderByAsc("field"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1821,7 +1820,7 @@ try { let query = new distributedKVStore.Query(); query.notEqualTo("field", "value"); query.orderByDesc("field"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1832,7 +1831,7 @@ try { limit(total: number, offset: number): Query -构造一个Query对象来指定结果的数量和开始位置。 +构造一个Query对象来指定结果的数量和开始位置。该接口必须要在Query对象查询和升降序等操作之后调用,调用limit接口后,不可再对Query对象进行查询和升降序等操作。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -1858,7 +1857,7 @@ try { let query = new distributedKVStore.Query(); query.notEqualTo("field", "value"); query.limit(total, offset); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1891,7 +1890,7 @@ isNotNull(field: string): Query try { let query = new distributedKVStore.Query(); query.isNotNull("field"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -1920,10 +1919,10 @@ try { query.beginGroup(); query.isNotNull("field"); query.endGroup(); - console.log("query is " + query.getSqlLike()); + console.info("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("duplicated calls should be ok :" + e); + console.error("duplicated calls should be ok :" + e); } ``` @@ -1949,10 +1948,10 @@ try { query.beginGroup(); query.isNotNull("field"); query.endGroup(); - console.log("query is " + query.getSqlLike()); + console.info("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("duplicated calls should be ok :" + e); + console.error("duplicated calls should be ok :" + e); } ``` @@ -1983,7 +1982,7 @@ try { let query = new distributedKVStore.Query(); query.prefixKey("$.name"); query.prefixKey("0"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -2017,7 +2016,7 @@ try { let query = new distributedKVStore.Query(); query.setSuggestIndex("$.name"); query.setSuggestIndex("0"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); query = null; } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); @@ -2029,6 +2028,10 @@ try { deviceId(deviceId:string):Query 添加设备ID作为key的前缀。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync) **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core @@ -2050,7 +2053,7 @@ deviceId(deviceId:string):Query try { let query = new distributedKVStore.Query(); query.deviceId("deviceId"); - console.log(`query is ${query.getSqlLike()}`); + console.info(`query is ${query.getSqlLike()}`); } catch (e) { console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); } @@ -2076,9 +2079,9 @@ getSqlLike():string try { let query = new distributedKVStore.Query(); let sql1 = query.getSqlLike(); - console.log(`GetSqlLike sql= ${sql1}`); + console.info(`GetSqlLike sql= ${sql1}`); } catch (e) { - console.log("duplicated calls should be ok : " + e); + console.error("duplicated calls should be ok : " + e); } ``` @@ -2122,16 +2125,15 @@ put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncC **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } - console.log("Succeeded in putting"); + console.info("Succeeded in putting"); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2177,14 +2179,13 @@ put(key: string, value: Uint8Array | string | number | boolean): Promise<void **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Succeeded in putting.data=${data}`); + console.info(`Succeeded in putting.data=${data}`); }).catch((err) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2203,7 +2204,7 @@ putBatch(entries: Entry[], callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------ | -| entries | [Entry](#entry)[] | 是 | 表示要批量插入的键值对。 | +| entries | [Entry](#entry)[] | 是 | 表示要批量插入的键值对。一个entries对象中允许的最大条目个数为128个。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -2224,7 +2225,6 @@ putBatch(entries: Entry[], callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -2238,20 +2238,20 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key', function (err, entries) { if (err != undefined) { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); } - console.log('Succeeded in getting Entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting Entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }); }); } catch (e) { @@ -2271,7 +2271,7 @@ putBatch(entries: Entry[]): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------- | ---- | ------------------------ | -| entries | [Entry](#entry)[] | 是 | 表示要批量插入的键值对。 | +| entries | [Entry](#entry)[] | 是 | 表示要批量插入的键值对。一个entries对象中允许的最大条目个数为128个。 | **返回值:** @@ -2297,7 +2297,6 @@ putBatch(entries: Entry[]): Promise<void> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -2311,17 +2310,17 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries).then(async (entries) => { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('Succeeded in getting Entries'); - console.log(`PutBatch ${entries}`); + console.info('Succeeded in getting Entries'); + console.info(`PutBatch ${entries}`); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); @@ -2363,7 +2362,6 @@ putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): **示例:** ```js -let kvStore; try { let v8Arr = []; let arr = new Uint8Array([4, 5, 6, 7]); @@ -2376,13 +2374,13 @@ try { v8Arr.push(vb3); kvStore.putBatch(v8Arr, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }) } catch (e) { - console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); + console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`); } ``` @@ -2426,7 +2424,6 @@ putBatch(value: Array<ValuesBucket>): Promise<void> **示例:** ```js -let kvStore; try { let v8Arr = []; let arr = new Uint8Array([4, 5, 6, 7]); @@ -2438,7 +2435,7 @@ try { v8Arr.push(vb2); v8Arr.push(vb3); kvStore.putBatch(v8Arr).then(async (data) => { - console.log(`Succeeded in putting patch`); + console.info(`Succeeded in putting patch`); }).catch((err) => { console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); }); @@ -2480,22 +2477,21 @@ delete(key: string, callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting'); + console.info('Succeeded in putting'); kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in deleting'); + console.info('Succeeded in deleting'); }); }); } catch (e) { @@ -2541,19 +2537,18 @@ delete(key: string): Promise<void> **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Succeeded in putting: ${data}`); + console.info(`Succeeded in putting: ${data}`); kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('Succeeded in deleting'); + console.info('Succeeded in deleting'); }).catch((err) => { - console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2574,7 +2569,7 @@ delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallb | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -2596,15 +2591,23 @@ delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallb ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); - kvStore.delete(predicates, function (err, data) { - if (err == undefined) { - console.log('Succeeded in deleting'); - } else { - console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + let arr = ["name"]; + predicates.inKeys(arr); + kvStore.put("name", "bob", function (err, data) { + if (err != undefined) { + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); + return; } + console.info("Succeeded in putting"); + kvStore.delete(predicates, function (err, data) { + if (err == undefined) { + console.info('Succeeded in deleting'); + } else { + console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); + } + }); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2653,20 +2656,19 @@ delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); let arr = ["name"]; predicates.inKeys(arr); kvStore.put("name", "bob").then((data) => { - console.log(`Succeeded in putting: ${data}`); + console.info(`Succeeded in putting: ${data}`); kvStore.delete(predicates).then((data) => { - console.log('Succeeded in deleting'); + console.info('Succeeded in deleting'); }).catch((err) => { - console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2706,7 +2708,6 @@ deleteBatch(keys: string[], callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; try { let entries = []; let keys = []; @@ -2722,19 +2723,19 @@ try { entries.push(entry); keys.push(key + i); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.deleteBatch(keys, async function (err, data) { if (err != undefined) { - console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in deleting Batch'); + console.info('Succeeded in deleting Batch'); }); }); } catch (e) { @@ -2780,7 +2781,6 @@ deleteBatch(keys: string[]): Promise<void> **示例:** ```js -let kvStore; try { let entries = []; let keys = []; @@ -2796,16 +2796,16 @@ try { entries.push(entry); keys.push(key + i); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries).then(async (data) => { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.deleteBatch(keys).then((err) => { - console.log('Succeeded in deleting Batch'); + console.info('Succeeded in deleting Batch'); }).catch((err) => { - console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -2817,6 +2817,10 @@ try { removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 删除指定设备的数据,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync) **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -2838,20 +2842,19 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { - console.log('Succeeded in putting data'); + console.info('Succeeded in putting data'); const deviceid = 'no_exist_device_id'; kvStore.removeDeviceData(deviceid, async function (err, data) { if (err == undefined) { - console.log('succeeded in removing device data'); + console.info('succeeded in removing device data'); } else { - console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { - console.log('Succeeded in getting data'); + console.info('Succeeded in getting data'); }); } }); @@ -2866,6 +2869,10 @@ try { removeDeviceData(deviceId: string): Promise<void> 删除指定设备的数据,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync) **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -2892,25 +2899,24 @@ removeDeviceData(deviceId: string): Promise<void> **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('Succeeded in putting data'); + console.info('Succeeded in putting data'); }).catch((err) => { - console.error(`Fail to put data.code is ${err.code},message is ${err.message} `); + console.error(`Failed to put data.code is ${err.code},message is ${err.message} `); }); const deviceid = 'no_exist_device_id'; kvStore.removeDeviceData(deviceid).then((err) => { - console.log('succeeded in removing device data'); + console.info('succeeded in removing device data'); }).catch((err) => { - console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); }); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('Succeeded in getting data'); + console.info('Succeeded in getting data'); }).catch((err) => { - console.error(`Fail to get data.code is ${err.code},message is ${err.message} `); + console.error(`Failed to get data.code is ${err.code},message is ${err.message} `); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`) @@ -2945,26 +2951,25 @@ get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Arr **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } - console.log("Succeeded in putting"); + console.info("Succeeded in putting"); kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get.code is ${err.code},message is ${err.message}`); return; } - console.log(`Succeeded in getting data.data=${data}`); + console.info(`Succeeded in getting data.data=${data}`); }); }); } catch (e) { - console.error(`Fail to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -3001,22 +3006,21 @@ get(key: string): Promise<boolean | string | number | Uint8Array> **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Succeeded in putting data.data=${data}`); + console.info(`Succeeded in putting data.data=${data}`); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log(`Succeeded in getting data.data=${data}`); + console.info(`Succeeded in getting data.data=${data}`); }).catch((err) => { - console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -3047,7 +3051,6 @@ getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -3061,21 +3064,21 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key', function (err, entries) { if (err != undefined) { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting Entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting Entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }); }); } catch (e) { @@ -3115,7 +3118,6 @@ getEntries(keyPrefix: string): Promise<Entry[]> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -3129,17 +3131,17 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries).then(async (entries) => { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('Succeeded in getting Entries'); - console.log(`PutBatch ${entries}`); + console.info('Succeeded in getting Entries'); + console.info(`PutBatch ${entries}`); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); @@ -3173,7 +3175,6 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void **示例:** ```js -let kvStore; try { var arr = new Uint8Array([21, 31]); let entries = []; @@ -3188,23 +3189,23 @@ try { } entries.push(entry); } - console.log(`entries: {entries}`); + console.info(`entries: {entries}`); kvStore.putBatch(entries, async function (err, data) { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query, function (err, entries) { if (err != undefined) { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting Entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting Entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }); }); } catch (e) { - console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); } ``` @@ -3240,7 +3241,6 @@ getEntries(query: Query): Promise<Entry[]> **示例:** ```js -let kvStore; try { var arr = new Uint8Array([21, 31]); let entries = []; @@ -3255,22 +3255,22 @@ try { } entries.push(entry); } - console.log(`entries: {entries}`); + console.info(`entries: {entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query).then((entries) => { - console.log('Succeeded in getting Entries'); + console.info('Succeeded in getting Entries'); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) }); - console.log('Succeeded in getting Entries'); + console.info('Succeeded in getting Entries'); } catch (e) { - console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); } ``` @@ -3303,7 +3303,6 @@ getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>) **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -3320,23 +3319,23 @@ try { } kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); kvStore.getResultSet('batch_test_string_key', async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }) }); }); @@ -3378,7 +3377,6 @@ getResultSet(keyPrefix: string): Promise<KVStoreResultSet> **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -3394,20 +3392,20 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }).catch((err) => { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -3442,7 +3440,6 @@ getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): voi **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -3459,18 +3456,18 @@ try { } kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query, async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); }); }); } catch (e) { @@ -3511,7 +3508,6 @@ getResultSet(query: Query): Promise<KVStoreResultSet> **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -3527,17 +3523,17 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query).then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -3576,24 +3572,23 @@ getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: Asyn ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let resultSet; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet(predicates, async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }) }); } catch (e) { @@ -3638,21 +3633,20 @@ getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KV ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let resultSet; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet(predicates).then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }).catch((err) => { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -3677,14 +3671,13 @@ closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>) **示例:** ```js -let kvStore; try { let resultSet = null; kvStore.closeResultSet(resultSet, function (err, data) { if (err == undefined) { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); } else { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); } }); } catch (e) { @@ -3715,13 +3708,12 @@ closeResultSet(resultSet: KVStoreResultSet): Promise<void> **示例:** ```js -let kvStore; try { let resultSet = null; kvStore.closeResultSet(resultSet).then(() => { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }).catch((err) => { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -3755,7 +3747,6 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -3770,15 +3761,15 @@ try { entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query, async function (err, resultSize) { if (err != undefined) { - console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set size'); + console.info('Succeeded in getting result set size'); }); }); } catch (e) { @@ -3818,7 +3809,6 @@ getResultSize(query: Query): Promise<number> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -3833,16 +3823,16 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query).then((resultSize) => { - console.log('Succeeded in getting result set size'); + console.info('Succeeded in getting result set size'); }).catch((err) => { - console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -3875,12 +3865,11 @@ backup(file:string, callback: AsyncCallback<void>):void **示例:** ```js -let kvStore; let file = "BK001"; try { kvStore.backup(file, (err, data) => { if (err) { - console.error(`Fail to backup.code is ${err.code},message is ${err.message} `); + console.error(`Failed to backup.code is ${err.code},message is ${err.message} `); } else { console.info(`Succeeded in backupping data.data=${data}`); } @@ -3921,13 +3910,12 @@ backup(file:string): Promise<void> **示例:** ```js -let kvStore; let file = "BK001"; try { kvStore.backup(file).then((data) => { console.info(`Succeeded in backupping data.data=${data}`); }).catch((err) => { - console.error(`Fail to backup.code is ${err.code},message is ${err.message}`); + console.error(`Failed to backup.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -3960,12 +3948,11 @@ restore(file:string, callback: AsyncCallback<void>):void **示例:** ```js -let kvStore; let file = "BK001"; try { kvStore.restore(file, (err, data) => { if (err) { - console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); } else { console.info(`Succeeded in restoring data.data=${data}`); } @@ -4006,13 +3993,12 @@ restore(file:string): Promise<void> **示例:** ```js -let kvStore; let file = "BK001"; try { kvStore.restore(file).then((data) => { console.info(`Succeeded in restoring data.data=${data}`); }).catch((err) => { - console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4037,12 +4023,11 @@ deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[str **示例:** ```js -let kvStore; let files = ["BK001", "BK002"]; try { kvStore.deleteBackup(files, (err, data) => { if (err) { - console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`); } else { console.info(`Succeed in deleting Backup.data=${data}`); } @@ -4075,16 +4060,15 @@ deleteBackup(files:Array<string>): Promise<Array<[string, number]> **示例:** ```js -let kvStore; let files = ["BK001", "BK002"]; try { kvStore.deleteBackup(files).then((data) => { console.info(`Succeed in deleting Backup.data=${data}`); }).catch((err) => { - console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`); }) } catch (e) { - console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` @@ -4119,7 +4103,6 @@ startTransaction(callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; function putBatchString(len, prefix) { let entries = []; for (var i = 0; i < len; i++) { @@ -4138,27 +4121,27 @@ function putBatchString(len, prefix) { try { var count = 0; kvStore.on('dataChange', 0, function (data) { - console.log(`startTransaction 0 ${data}`); + console.info(`startTransaction 0 ${data}`); count++; }); kvStore.startTransaction(async function (err, data) { if (err != undefined) { - console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in starting Transaction'); + console.info('Succeeded in starting Transaction'); let entries = putBatchString(10, 'batch_test_string_key'); - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); }); }); } catch (e) { - console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); + console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`); } ``` @@ -4193,20 +4176,19 @@ startTransaction(): Promise<void> **示例:** ```js -let kvStore; try { var count = 0; kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log(`startTransaction 0 ${data}`); + console.info(`startTransaction 0 ${data}`); count++; }); kvStore.startTransaction().then(async (err) => { - console.log('Succeeded in starting Transaction'); + console.info('Succeeded in starting Transaction'); }).catch((err) => { - console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); + console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`); } ``` @@ -4235,13 +4217,12 @@ commit(callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; try { kvStore.commit(function (err, data) { if (err == undefined) { - console.log('Succeeded in committing'); + console.info('Succeeded in committing'); } else { - console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); } }); } catch (e) { @@ -4274,12 +4255,11 @@ commit(): Promise<void> **示例:** ```js -let kvStore; try { kvStore.commit().then(async (err) => { - console.log('Succeeded in committing'); + console.info('Succeeded in committing'); }).catch((err) => { - console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.ode is ${e.code},message is ${e.message}`); @@ -4311,13 +4291,12 @@ rollback(callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; try { kvStore.rollback(function (err,data) { if (err == undefined) { - console.log('Succeeded in rolling back'); + console.info('Succeeded in rolling back'); } else { - console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); } }); }catch(e) { @@ -4350,12 +4329,11 @@ rollback(): Promise<void> **示例:** ```js -let kvStore; try { kvStore.rollback().then(async (err) => { - console.log('Succeeded in rolling back'); + console.info('Succeeded in rolling back'); }).catch((err) => { - console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4380,13 +4358,12 @@ enableSync(enabled: boolean, callback: AsyncCallback<void>): void **示例:** ```js -let kvStore; try { kvStore.enableSync(true, function (err, data) { if (err == undefined) { - console.log('Succeeded in enabling sync'); + console.info('Succeeded in enabling sync'); } else { - console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); } }); } catch (e) { @@ -4417,12 +4394,11 @@ enableSync(enabled: boolean): Promise<void> **示例:** ```js -let kvStore; try { kvStore.enableSync(true).then((err) => { - console.log('Succeeded in enabling sync'); + console.info('Succeeded in enabling sync'); }).catch((err) => { - console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4448,16 +4424,15 @@ setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: Asy **示例:** ```js -let kvStore; try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) { if (err != undefined) { - console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in setting syncRange'); + console.info('Succeeded in setting syncRange'); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4488,14 +4463,13 @@ setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<v **示例:** ```js -let kvStore; try { const localLabels = ['A', 'B']; const remoteSupportLabels = ['C', 'D']; kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { - console.log('Succeeded in setting syncRange'); + console.info('Succeeded in setting syncRange'); }).catch((err) => { - console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4520,15 +4494,14 @@ setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>) **示例:** ```js -let kvStore; try { const defaultAllowedDelayMs = 500; kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) { if (err != undefined) { - console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in setting syncParam'); + console.info('Succeeded in setting syncParam'); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4558,13 +4531,12 @@ setSyncParam(defaultAllowedDelayMs: number): Promise<void> **示例:** ```js -let kvStore; try { const defaultAllowedDelayMs = 500; kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { - console.log('Succeeded in setting syncParam'); + console.info('Succeeded in setting syncParam'); }).catch((err) => { - console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4607,7 +4579,6 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void import deviceManager from '@ohos.distributedHardware.deviceManager'; let devManager; -let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; // create deviceManager @@ -4623,19 +4594,19 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { } try { kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); + console.info('Sync dataChange'); }); kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting data'); + console.info('Succeeded in putting data'); const mode = distributedKVStore.SyncMode.PULL_ONLY; kvStore.sync(deviceIds, mode, 1000); }); } catch (e) { - console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); + console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); } } }); @@ -4678,7 +4649,6 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void import deviceManager from '@ohos.distributedHardware.deviceManager'; let devManager; -let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; // create deviceManager @@ -4694,14 +4664,14 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { } try { kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); + console.info('Sync dataChange'); }); kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting data'); + console.info('Succeeded in putting data'); const mode = distributedKVStore.SyncMode.PULL_ONLY; const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); @@ -4709,7 +4679,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { kvStore.sync(deviceIds, query, mode, 1000); }); } catch (e) { - console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); + console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); } } }); @@ -4743,10 +4713,9 @@ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotific **示例:** ```js -let kvStore; try { kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log(`dataChange callback call data: ${data}`); + console.info(`dataChange callback call data: ${data}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4771,20 +4740,19 @@ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]> **示例:** ```js -let kvStore; const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; const VALUE_TEST_FLOAT_ELEMENT = 321.12; try { kvStore.on('syncComplete', function (data) { - console.log(`syncComplete ${data}`); + console.info(`syncComplete ${data}`); }); kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('succeeded in putting'); + console.info('succeeded in putting'); }).catch((err) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to subscribe syncComplete.code is ${e.code},message is ${e.message}`); + console.error(`Failed to subscribe syncComplete.code is ${e.code},message is ${e.message}`); } ``` @@ -4814,10 +4782,9 @@ off(event:'dataChange', listener?: Callback<ChangeNotification>): void **示例:** ```js -let kvStore; class KvstoreModel { call(data) { - console.log(`dataChange : ${data}`); + console.info(`dataChange : ${data}`); } subscribeDataChange() { @@ -4826,7 +4793,7 @@ class KvstoreModel { kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); } } catch (err) { - console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`); } } @@ -4836,7 +4803,7 @@ class KvstoreModel { kvStore.off('dataChange', this.call); } } catch (err) { - console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); } } } @@ -4860,10 +4827,9 @@ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]& **示例:** ```js -let kvStore; class KvstoreModel { call(data) { - console.log(`syncComplete : ${data}`); + console.info(`syncComplete : ${data}`); } subscribeDataChange() { @@ -4872,7 +4838,7 @@ class KvstoreModel { kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); } } catch (err) { - console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`); } } @@ -4882,7 +4848,7 @@ class KvstoreModel { kvStore.off('dsyncComplete', this.call); } } catch (err) { - console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); } } } @@ -4913,14 +4879,13 @@ getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void **示例:** ```js -let kvStore; try { kvStore.getSecurityLevel(function (err, data) { if (err != undefined) { - console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting securityLevel'); + console.info('Succeeded in getting securityLevel'); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -4952,12 +4917,11 @@ getSecurityLevel(): Promise<SecurityLevel> **示例:** ```js -let kvStore; try { kvStore.getSecurityLevel().then((data) => { - console.log('Succeeded in getting securityLevel'); + console.info('Succeeded in getting securityLevel'); }).catch((err) => { - console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); @@ -5002,26 +4966,25 @@ get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Arr **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } - console.log("Succeeded in putting"); + console.info("Succeeded in putting"); kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get.code is ${err.code},message is ${err.message}`); return; } - console.log(`Succeeded in getting data.data=${data}`); + console.info(`Succeeded in getting data.data=${data}`); }); }); } catch (e) { - console.error(`Fail to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -5058,22 +5021,21 @@ get(key: string): Promise<boolean | string | number | Uint8Array> **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log(`Succeeded in putting data.data=${data}`); + console.info(`Succeeded in putting data.data=${data}`); kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log(`Succeeded in getting data.data=${data}`); + console.info(`Succeeded in getting data.data=${data}`); }).catch((err) => { - console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -5082,6 +5044,10 @@ try { get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 获取与指定设备ID和key匹配的string值,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5106,26 +5072,25 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { if (err != undefined) { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting'); + console.info('Succeeded in putting'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { - console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting'); + console.info('Succeeded in getting'); }); }) } catch (e) { - console.error(`Fail to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -5134,6 +5099,10 @@ try { get(deviceId: string, key: string): Promise<boolean | string | number | Uint8Array> 获取与指定设备ID和key匹配的string值,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5163,22 +5132,21 @@ get(deviceId: string, key: string): Promise<boolean | string | number | Uint8 **示例:** ```js -let kvStore; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { - console.log('Succeeded in putting'); + console.info('Succeeded in putting'); kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('Succeeded in getting'); + console.info('Succeeded in getting'); }).catch((err) => { - console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get.code is ${err.code},message is ${err.message}`); }); }).catch((error) => { - console.error(`Fail to put.code is ${error.code},message is ${error.message}`); + console.error(`Failed to put.code is ${error.code},message is ${error.message}`); }); } catch (e) { - console.error(`Fail to get.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -5209,7 +5177,6 @@ getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -5223,21 +5190,21 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key', function (err, entries) { if (err != undefined) { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting Entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting Entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }); }); } catch (e) { @@ -5277,7 +5244,6 @@ getEntries(keyPrefix: string): Promise<Entry[]> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -5291,17 +5257,17 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries).then(async (entries) => { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('Succeeded in getting Entries'); - console.log(`PutBatch ${entries}`); + console.info('Succeeded in getting Entries'); + console.info(`PutBatch ${entries}`); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); @@ -5313,6 +5279,10 @@ try { getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void 获取与指定设备ID和key前缀匹配的所有键值对,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5336,7 +5306,6 @@ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -5350,25 +5319,25 @@ try { } entries.push(entry); } - console.log(`entries : ${entries}`); + console.info(`entries : ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { if (err != undefined) { - console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }); }); } catch (e) { - console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); + console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`); } ``` @@ -5377,6 +5346,10 @@ try { getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> 获取与指定设备ID和key前缀匹配的所有键值对,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5405,7 +5378,6 @@ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -5419,23 +5391,23 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { - console.log('Succeeded in getting entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); - console.log(`entries[0].value: ${entries[0].value}`); - console.log(`entries[0].value.value: ${entries[0].value.value}`); + console.info('Succeeded in getting entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); + console.info(`entries[0].value: ${entries[0].value}`); + console.info(`entries[0].value.value: ${entries[0].value.value}`); }).catch((err) => { - console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); + console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`); } ``` @@ -5466,7 +5438,6 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void **示例:** ```js -let kvStore; try { var arr = new Uint8Array([21, 31]); let entries = []; @@ -5481,23 +5452,23 @@ try { } entries.push(entry); } - console.log(`entries: {entries}`); + console.info(`entries: {entries}`); kvStore.putBatch(entries, async function (err, data) { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query, function (err, entries) { if (err != undefined) { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting Entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting Entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }); }); } catch (e) { - console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); } ``` @@ -5533,7 +5504,6 @@ getEntries(query: Query): Promise<Entry[]> **示例:** ```js -let kvStore; try { var arr = new Uint8Array([21, 31]); let entries = []; @@ -5548,22 +5518,22 @@ try { } entries.push(entry); } - console.log(`entries: {entries}`); + console.info(`entries: {entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting Batch'); + console.info('Succeeded in putting Batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getEntries(query).then((entries) => { - console.log('Succeeded in getting Entries'); + console.info('Succeeded in getting Entries'); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) }); - console.log('Succeeded in getting Entries'); + console.info('Succeeded in getting Entries'); } catch (e) { - console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); } ``` @@ -5572,6 +5542,10 @@ try { getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void 获取与指定设备ID和Query对象匹配的键值对列表,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5595,7 +5569,6 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]> **示例:** ```js -let kvStore; try { var arr = new Uint8Array([21, 31]); let entries = []; @@ -5610,29 +5583,29 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); var query = new distributedKVStore.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); kvStore.getEntries('localDeviceId', query, function (err, entries) { if (err != undefined) { - console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting entries'); - console.log(`entries.length: ${entries.length}`); - console.log(`entries[0]: ${entries[0]}`); + console.info('Succeeded in getting entries'); + console.info(`entries.length: ${entries.length}`); + console.info(`entries[0]: ${entries[0]}`); }) }); - console.log('Succeeded in getting entries'); + console.info('Succeeded in getting entries'); } catch (e) { - console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`); } ``` @@ -5641,6 +5614,10 @@ try { getEntries(deviceId: string, query: Query): Promise<Entry[]> 获取与指定设备ID和Query对象匹配的键值对列表,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5669,7 +5646,6 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]> **示例:** ```js -let kvStore; try { var arr = new Uint8Array([21, 31]); let entries = []; @@ -5684,23 +5660,23 @@ try { } entries.push(entry); } - console.log(`entries: ${entries}`); + console.info(`entries: ${entries}`); kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); var query = new distributedKVStore.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); kvStore.getEntries('localDeviceId', query).then((entries) => { - console.log('Succeeded in getting entries'); + console.info('Succeeded in getting entries'); }).catch((err) => { - console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); }); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); - console.log('Succeeded in getting entries'); + console.info('Succeeded in getting entries'); } catch (e) { - console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`); } ``` @@ -5732,7 +5708,6 @@ getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>) **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -5749,23 +5724,23 @@ try { } kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); kvStore.getResultSet('batch_test_string_key', async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }) }); }); @@ -5807,7 +5782,6 @@ getResultSet(keyPrefix: string): Promise<KVStoreResultSet> **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -5823,20 +5797,20 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }).catch((err) => { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -5848,6 +5822,10 @@ try { getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 获取与指定设备ID和key前缀匹配的KVStoreResultSet对象,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5872,26 +5850,25 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVS **示例:** ```js -let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting resultSet'); + console.info('Succeeded in getting resultSet'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing resultSet'); + console.info('Succeeded in closing resultSet'); }) }); } catch (e) { - console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); } ``` @@ -5900,6 +5877,10 @@ try { getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> 获取与指定设备ID和key前缀匹配的KVStoreResultSet对象,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5929,22 +5910,21 @@ getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet&g **示例:** ```js -let kvStore; try { let resultSet; kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('Succeeded in getting resultSet'); + console.info('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing resultSet'); + console.info('Succeeded in closing resultSet'); }).catch((err) => { - console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); } ``` @@ -5953,6 +5933,10 @@ try { getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void 获取与指定设备ID和Query对象匹配的KVStoreResultSet对象,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5977,7 +5961,6 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreR **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -5994,30 +5977,30 @@ try { } kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query, async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting resultSet'); + console.info('Succeeded in getting resultSet'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing resultSet'); + console.info('Succeeded in closing resultSet'); }) }); }); } catch (e) { - console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); } ``` @@ -6026,6 +6009,10 @@ try { getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> 获取与指定设备ID和Query对象匹配的KVStoreResultSet对象,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6055,7 +6042,6 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -6071,28 +6057,28 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('Succeeded in getting resultSet'); + console.info('Succeeded in getting resultSet'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); }); query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); + console.info("GetResultSet " + query.getSqlLike()); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing resultSet'); + console.info('Succeeded in closing resultSet'); }).catch((err) => { - console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); } ``` @@ -6129,7 +6115,6 @@ getResultSet(query: Query): Promise<KVStoreResultSet> **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -6145,17 +6130,17 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSet(query).then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -6164,24 +6149,23 @@ try { ### getResultSet -getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> +getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void -获取与指定设备ID和Query对象匹配的KVStoreResultSet对象,使用Promise异步回调。 +获取与本设备指定Query对象匹配的KVStoreResultSet对象,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 -**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore +**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------- | -| deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | | query | [Query](#query) | 是 | 表示查询对象。 | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | 是 | 回调函数,获取与指定Predicates对象匹配的KVStoreResultSet对象。 | -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------------------- | ------------------------------------------------------------ | -| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise对象。返回与指定设备ID和Query对象匹配的KVStoreResultSet对象。 | **错误码:** @@ -6196,7 +6180,6 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> **示例:** ```js -let kvStore; try { let resultSet; let entries = []; @@ -6211,29 +6194,32 @@ try { } entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); - }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); - }); - const query = new distributedKVStore.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('Succeeded in getting resultSet'); - resultSet = result; - }).catch((err) => { - console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); - }); - query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing resultSet'); - }).catch((err) => { - console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in putting batch'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query, async function (err, result) { + if (err != undefined) { + console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in getting resultSet'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.info('Succeeded in closing resultSet'); + }) + }); }); - } catch (e) { - console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); } ``` @@ -6269,24 +6255,23 @@ getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: Asyn ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let resultSet; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet(predicates, async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }) }); } catch (e) { @@ -6331,21 +6316,20 @@ getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KV ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let resultSet; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet(predicates).then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }).catch((err) => { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -6357,6 +6341,10 @@ try { getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 获取与指定Predicate对象匹配的KVStoreResultSet对象,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统接口:** 此接口为系统接口。 @@ -6385,24 +6373,23 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; try { let resultSet; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet('localDeviceId', predicates, async function (err, result) { if (err != undefined) { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { if (err != undefined) { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }) }); } catch (e) { @@ -6415,6 +6402,10 @@ try { getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 获取与指定Predicate对象匹配的KVStoreResultSet对象,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统接口:** 此接口为系统接口。 @@ -6447,21 +6438,21 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat ```js import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; + try { let resultSet; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.prefixKey("batch_test_string_key"); kvStore.getResultSet('localDeviceId', predicates).then((result) => { - console.log('Succeeded in getting result set'); + console.info('Succeeded in getting result set'); resultSet = result; }).catch((err) => { - console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); }); kvStore.closeResultSet(resultSet).then((err) => { - console.log('Succeeded in closing result set'); + console.info('Succeeded in closing result set'); }).catch((err) => { - console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -6495,7 +6486,6 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -6510,15 +6500,15 @@ try { entries.push(entry); } kvStore.putBatch(entries, async function (err, data) { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query, async function (err, resultSize) { if (err != undefined) { - console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting result set size'); + console.info('Succeeded in getting result set size'); }); }); } catch (e) { @@ -6558,7 +6548,6 @@ getResultSize(query: Query): Promise<number> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -6573,16 +6562,16 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize(query).then((resultSize) => { - console.log('Succeeded in getting result set size'); + console.info('Succeeded in getting result set size'); }).catch((err) => { - console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); }); } catch (e) { console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); @@ -6594,6 +6583,10 @@ try { getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; 获取与指定设备ID和Query对象匹配的结果数,使用callback异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6617,7 +6610,6 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number& **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -6633,23 +6625,23 @@ try { } kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); const query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { if (err != undefined) { - console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); return; } - console.log('Succeeded in getting resultSize'); + console.info('Succeeded in getting resultSize'); ; }); }); } catch (e) { - console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`); } ``` @@ -6658,6 +6650,10 @@ try { getResultSize(deviceId: string, query: Query): Promise<number> 获取与指定设备ID和Query对象匹配的结果数,使用Promise异步回调。 +> **说明:** +> +> 其中deviceId通过调用[deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync)方法得到。deviceManager模块的接口均为系统接口,仅系统应用可用。 +> deviceId具体获取方式请参考[sync接口示例](#sync)。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -6686,7 +6682,6 @@ getResultSize(deviceId: string, query: Query): Promise<number> **示例:** ```js -let kvStore; try { let entries = []; for (var i = 0; i < 10; i++) { @@ -6701,19 +6696,19 @@ try { entries.push(entry); } kvStore.putBatch(entries).then(async (err) => { - console.log('Succeeded in putting batch'); + console.info('Succeeded in putting batch'); }).catch((err) => { - console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); }); var query = new distributedKVStore.Query(); query.prefixKey("batch_test"); kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('Succeeded in getting resultSize'); + console.info('Succeeded in getting resultSize'); ; }).catch((err) => { - console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); }); } catch (e) { - console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); + console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md index bee6cc69d5bcacfdbbea479f2f56958c283e4193..ae6c7f9e45e34b18e8c502982bd51e78d72ea9d8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @@ -16,7 +16,7 @@ import accountManager from '@ohos.enterprise.accountManager'; disallowAddLocalAccount(admin: Want, disallow: boolean, callback: AsyncCallback<void>): void -是否禁止创建本地用户接口,使用callback异步回调。 +指定设备管理员应用禁止创建本地用户接口,使用callback形式返回设置结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY @@ -28,9 +28,9 @@ disallowAddLocalAccount(admin: Want, disallow: boolean, callback: AsyncCallback& | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| disallow | boolean | 是 | 是否禁止创建本地用户,true表示禁止,false表示解除禁止。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| disallow | boolean | 是 | 是否禁止创建本地用户,true表示禁止创建本地用户,false表示允许创建本地用户。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -59,7 +59,7 @@ accountManager.disallowAddLocalAccount(admin, true, (error) => { disallowAddLocalAccount(admin: Want, disallow: boolean): Promise<void> -是否禁止创建本地用户,使用promise异步回调。 +指定设备管理员应用禁止创建本地用户,使用Promise形式返回设置结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY @@ -71,14 +71,14 @@ disallowAddLocalAccount(admin: Want, disallow: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| disallow | boolean | 是 | 是否禁止创建本地用户,true表示禁止,false表示解除禁止。 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| disallow | boolean | 是 | 是否禁止创建本地用户,true表示禁止创建本地用户,false表示允许创建本地用户。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。当禁止创建本地用户失败时抛出错误对象。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md index b590eaabcd37d55076372d91e1827ca98e9e79ea..a2a47106d0b1a5f329b7e9ed58d24b152a2b89d5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @@ -16,7 +16,7 @@ import adminManager from '@ohos.enterprise.adminManager'; enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void -以异步方法根据给定的包名和类名激活设备管理员应用,使用Callback形式返回是否激活成功。 +激活当前用户下的指定设备管理员应用,使用callback形式返回是否激活成功。其中超级管理员应用只能在管理员用户下被激活。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -28,10 +28,10 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callba | 参数名 | 类型 | 必填 | 说明 | | -------------- | ----------------------------------- | ---- | ------------------ | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息 | -| type | [AdminType](#admintype) | 是 | 激活的设备管理员类型 | -| callback | AsyncCallback\ | 是 | callback方式返回是否激活成功 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息。 | +| type | [AdminType](#admintype) | 是 | 激活的设备管理员类型。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -67,7 +67,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\): void -以异步方法根据给定的包名和类名激活设备管理员应用,使用Callback形式返回是否激活成功。 +激活指定用户下的指定设备管理员应用,使用callback形式返回是否激活成功。其中超级管理员应用只能在管理员用户下被激活。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -79,11 +79,11 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId | 参数名 | 类型 | 必填 | 说明 | | -------------- | ----------------------------------- | ---- | ---------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息 | -| type | [AdminType](#admintype) | 是 | 激活的设备管理员类型 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息。 | +| type | [AdminType](#admintype) | 是 | 激活的设备管理员类型。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -| callback | AsyncCallback\ | 是 | callback方式返回是否激活成功 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -119,7 +119,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number): Promise\ -以异步方法根据给定的包名和类名激活设备管理员应用,使用Promise形式返回是否激活成功。 +如果调用接口时传入了可选参数userId,则激活指定用户下的指定设备管理员应用,否则激活当前用户下的指定设备管理员应用,使用Promise形式返回是否激活成功。其中超级管理员应用只能在管理员用户下被激活。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -131,16 +131,16 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId | 参数名 | 类型 | 必填 | 说明 | | -------------- | ----------------------------------- | ---- | ---------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息 | -| type | [AdminType](#admintype) | 是 | 激活的设备管理员类型 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息。 | +| type | [AdminType](#admintype) | 是 | 激活的设备管理员类型。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | **返回值:** | 类型 | 说明 | | ----------------- | ----------------- | -| Promise\ | Promise形式返回是否激活成功 | +| Promise\ | 无返回结果的Promise对象。当激活设备管理员应用失败时会抛出错误对象。 | **错误码**: @@ -173,7 +173,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_ disableAdmin(admin: Want, callback: AsyncCallback\): void -以异步方法根据给定的包名和类名将设备普通管理员应用去激活,使用Callback形式返回是否去激活成功。 +将当前用户下的指定普通管理员应用去激活,使用callback形式返回是否去激活成功。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -185,8 +185,8 @@ disableAdmin(admin: Want, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 普通设备管理员应用 | -| callback | AsyncCallback\ | 是 | callback方式返回是否去激活成功 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 普通设备管理员应用。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -216,7 +216,7 @@ adminManager.disableAdmin(wantTemp, error => { disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void -以异步方法根据给定的包名和类名将设备普通管理员应用去激活,使用Callback形式返回是否去激活成功。 +将指定用户下的指定普通管理员应用去激活,使用callback形式返回是否去激活成功。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -228,9 +228,9 @@ disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 普通设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 普通设备管理员应用。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -| callback | AsyncCallback\ | 是 | callback方式返回是否去激活成功 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -260,7 +260,7 @@ adminManager.disableAdmin(wantTemp, 100, error => { disableAdmin(admin: Want, userId?: number): Promise\ -以异步方法根据给定的包名和类名将设备普通管理员应用去激活,使用Promise形式返回是否去激活成功。 +如果调用接口时传入了可选参数userId,则将指定用户下的指定普通管理员应用去激活,否则将当前用户下的指定普通管理员应用去激活,使用Promise形式返回是否去激活成功。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -272,14 +272,14 @@ disableAdmin(admin: Want, userId?: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------------- | ---- | ---------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 普通设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 普通设备管理员应用。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | **返回值:** | 类型 | 说明 | | ----------------- | ----------------- | -| Promise\ | Promise形式返回是否激活成功 | +| Promise\ | 无返回结果的Promise对象。当去激活普通管理员应用失败时会抛出错误对象。 | **错误码**: @@ -305,7 +305,7 @@ adminManager.disableAdmin(wantTemp, 100).catch(error => { disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void -以异步方法根据给定的包名将设备超级管理员应用去激活,使用Callback形式返回是否去激活成功。 +根据bundleName将管理员用户下的超级管理员应用去激活,使用callback形式返回是否去激活成功。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -317,8 +317,8 @@ disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | ---------- | ----------------------- | ---- | ------------------- | -| bundleName | String | 是 | 超级设备管理员应用的包名 | -| callback | AsyncCallback\ | 是 | callback方式返回是否去激活成功 | +| bundleName | String | 是 | 超级设备管理员应用的包名。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -345,7 +345,7 @@ adminManager.disableSuperAdmin(bundleName, error => { disableSuperAdmin(bundleName: String): Promise\ -以异步方法根据给定的包名将设备超级管理员应用去激活,使用Promise形式返回是否去激活成功。 +根据bundleName将管理员用户下的超级管理员应用去激活,使用Promise形式返回是否去激活成功。 **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN @@ -357,13 +357,13 @@ disableSuperAdmin(bundleName: String): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | ------------ | -| bundleName | String | 是 | 超级设备管理员应用的包名 | +| bundleName | String | 是 | 超级设备管理员应用的包名。 | **返回值:** | 类型 | 说明 | | ----------------- | ----------------- | -| Promise\ | Promise形式返回是否激活成功 | +| Promise\ | 无返回结果的Promise对象。当去激活超级管理员应用失败时会抛出错误对象。 | **错误码**: @@ -386,7 +386,7 @@ adminManager.disableSuperAdmin(bundleName).catch(error => { isAdminEnabled(admin: Want, callback: AsyncCallback\): void -以异步方法根据给定的包名和类名判断设备管理员应用是否被激活,使用Callback形式返回是否处于激活状态。 +查询当前用户下的指定设备管理员应用是否被激活,使用callback形式返回是否处于激活状态。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -396,8 +396,8 @@ isAdminEnabled(admin: Want, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | -------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback\ | 是 | callback方式返回是否处于激活状态 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,data为boolean值,true表示当前用户下的指定设备管理员应用被激活,false表示当前用户下的指定设备管理员应用未激活,否则err为错误对象。 | **示例**: @@ -419,7 +419,7 @@ adminManager.isAdminEnabled(wantTemp, (error, result) => { isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): void -以异步方法根据给定的包名和类名判断设备管理员应用是否被激活,使用Callback形式返回是否处于激活状态。 +查询指定用户下的指定设备管理员应用是否被激活,使用callback形式返回是否处于激活状态。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -429,9 +429,9 @@ isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -| callback | AsyncCallback\ | 是 | callback方式返回是否处于激活状态 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,data为boolean值,true表示当前用户下的指定设备管理员应用被激活,false表示当前用户下的指定设备管理员应用未激活,否则err为错误对象。 | **示例**: @@ -453,7 +453,7 @@ adminManager.isAdminEnabled(wantTemp, 100, (error, result) => { isAdminEnabled(admin: Want, userId?: number): Promise\ -以异步方法根据给定的包名和类名判断设备管理员应用是否被激活,使用Promise形式返回是否处于激活状态。 +如果调用接口时传入参数userId,则查询指定用户下的设备管理员应用是否被激活,否则判断当前用户下的设备管理员应用是否被激活,使用Promise形式返回是否处于激活状态。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -463,14 +463,14 @@ isAdminEnabled(admin: Want, userId?: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------------- | ---- | ---------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | **返回值:** | 类型 | 说明 | | ----------------- | ------------------- | -| Promise\ | Promise形式返回是否处于激活状态 | +| Promise\ | Promise对象, 返回true表示指定的管理员应用被激活,返回false表示指定的管理员应用未激活。| **示例**: @@ -490,7 +490,7 @@ adminManager.isAdminEnabled(wantTemp, 100).then((result) => { isSuperAdmin(bundleName: String, callback: AsyncCallback\): void -以异步方法根据给定的包名判断设备超级管理员应用是否被激活,使用Callback形式返回是否处于激活状态。 +根据bundleName查询管理员用户下的超级管理员应用是否被激活,使用callback形式返回是否处于激活状态。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -500,8 +500,8 @@ isSuperAdmin(bundleName: String, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | ---------- | ----------------------- | ---- | -------------------- | -| bundleName | String | 是 | 设备管理员应用 | -| callback | AsyncCallback\ | 是 | callback方式返回是否处于激活状态 | +| bundleName | String | 是 | 设备管理员应用。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,data为boolean类型值,true表示当前用户下的指定设备管理员应用被激活,false表示当前用户下的指定设备管理员应用未激活,否则err为错误对象。 | **示例**: @@ -520,7 +520,7 @@ adminManager.isSuperAdmin(bundleName, (error, result) => { isSuperAdmin(bundleName: String): Promise\ -以异步方法根据给定的包名判断设备超级管理员应用是否被激活,使用Promise形式返回是否处于激活状态。 +根据bundleName查询管理员用户下的超级管理员应用是否被激活,使用Promise形式返回是否处于激活状态。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -530,13 +530,13 @@ isSuperAdmin(bundleName: String): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | --------- | -| bundleName | String | 是 | 超级设备管理员应用 | +| bundleName | String | 是 | 超级设备管理员应用。 | **返回值:** | 错误码ID | 错误信息 | | ----------------- | ------------------- | -| Promise\ | Promise形式返回是否处于激活状态 | +| Promise\ | Promise对象, 返回true表示指定的超级管理员应用被激活,返回false表示指定的超级管理员应用未激活。 | **示例**: @@ -553,7 +553,7 @@ adminManager.isSuperAdmin(bundleName).then((result) => { setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCallback\;): void -设置设备管理员应用的企业信息,使用callback形式返回是否设置成功。 +设置指定设备管理员应用的企业信息,使用callback形式返回是否设置成功。 **需要权限:** ohos.permission.SET_ENTERPRISE_INFO @@ -565,9 +565,9 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCa | 参数名 | 类型 | 必填 | 说明 | | -------------- | ----------------------------------- | ---- | ---------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息 | -| callback | AsyncCallback\; | 是 | callback方式返回是否设置企业信息成功 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | 是 | 设备管理员应用的企业信息。 | +| callback | AsyncCallback\; | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -601,7 +601,7 @@ adminManager.setEnterpriseInfo(wantTemp, enterpriseInfo, error => { setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise\; -设置设备管理员应用的企业信息,使用Promise形式返回是否设置成功。 +设置指定设备管理员应用的企业信息,使用Promise形式返回是否设置成功。 **需要权限:** ohos.permission.SET_ENTERPRISE_INFO @@ -620,7 +620,7 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise\; | 类型 | 说明 | | ----------------- | --------------------- | -| Promise\ | Promise方式返回是否设置企业信息成功 | +| Promise\ | 无返回结果的Promise对象。当设置设备管理员应用企业信息失败时会抛出错误对象。 | **错误码**: @@ -650,7 +650,7 @@ adminManager.setEnterpriseInfo(wantTemp, enterpriseInfo).catch(error => { getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): void -获取设备管理员应用的企业信息,使用callback形式返回设备管理员应用的企业信息。 +获取指定设备管理员应用的企业信息,使用callback形式返回设备管理员应用的企业信息。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -661,7 +661,7 @@ getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------ | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback<[EnterpriseInfo](#enterpriseinfo)> | 是 | callback方式返回设备管理员应用的企业信息 | +| callback | AsyncCallback<[EnterpriseInfo](#enterpriseinfo)> | 是 | 回调函数,当接口调用成功,err为null,data为设备管理员应用的企业信息,否则err为错误对象。 | **错误码**: @@ -692,7 +692,7 @@ adminManager.getEnterpriseInfo(wantTemp, (error, result) => { getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> -获取设备管理员应用的企业信息,使用Promise形式返回设备管理员应用的企业信息。 +获取指定设备管理员应用的企业信息,使用Promise形式返回设备管理员应用的企业信息。 **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager @@ -708,7 +708,7 @@ getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> | 类型 | 说明 | | ---------------------------------------- | ------------------------- | -| Promise<[EnterpriseInfo](#enterpriseinfo)> | Promise方式返回设备管理员应用的企业信息对象 | +| Promise<[EnterpriseInfo](#enterpriseinfo)> | Promise对象,返回指定设备管理员应用的企业信息。 | **错误码**: @@ -737,7 +737,7 @@ adminManager.getEnterpriseInfo(wantTemp).then((result) => { subscribeManagedEvent(admin: Want, managedEvents: Array\, callback: AsyncCallback\): void -订阅系统管理事件。使用callback异步回调。 +指定设备管理员应用订阅系统管理事件。使用callback形式返回结果。 **需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT @@ -751,7 +751,7 @@ subscribeManagedEvent(admin: Want, managedEvents: Array\, callback | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | managedEvents | Array\<[ManagedEvent](#managedevent)> | 是 | 订阅事件数组。 | -| callback | AsyncCallback\ | 是 | 回调函数。当系统管理事件订阅成功err为null,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -781,7 +781,7 @@ adminManager.subscribeManagedEvent(wantTemp, events, (error) => { subscribeManagedEvent(admin: Want, managedEvents: Array\): Promise\ -订阅系统管理事件。使用Promise异步回调。 +指定设备管理员应用订阅系统管理事件。使用Promise形式返回结果。 **需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT @@ -800,7 +800,7 @@ subscribeManagedEvent(admin: Want, managedEvents: Array\): Promise | 类型 | 说明 | | ----- | ----------------------------------- | -| Promise\ | Promise对象。无返回结果的Promise对象。 | +| Promise\ | 无返回结果的Promise对象。当指定设备管理员应用订阅系统事件失败时会抛出错误对象。 | **错误码**: @@ -829,7 +829,7 @@ adminManager.subscribeManagedEvent(wantTemp, events).then(() => { unsubscribeManagedEvent(admin: Want, managedEvents: Array\, callback: AsyncCallback\): void -取消订阅系统管理事件。使用callback异步回调。 +指定设备管理员应用取消订阅系统管理事件。使用callback形式返回结果。 **需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT @@ -843,7 +843,7 @@ unsubscribeManagedEvent(admin: Want, managedEvents: Array\, callba | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | managedEvents | Array\<[ManagedEvent](#managedevent)> | 是 | 取消订阅事件数组。 | -| callback | AsyncCallback\ | 是 | 回调函数。当系统管理事件取消订阅成功err为null,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -873,7 +873,7 @@ adminManager.unsubscribeManagedEvent(wantTemp, events, (error) => { unsubscribeManagedEvent(admin: Want, managedEvents: Array\): Promise\ -取消订阅系统管理事件。使用callback异步回调。 +指定设备管理员应用取消订阅系统管理事件。使用Promise形式返回结果。 **需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT @@ -892,7 +892,7 @@ unsubscribeManagedEvent(admin: Want, managedEvents: Array\): Promi | 类型 | 说明 | | ----- | ----------------------------------- | -| Promise\ | Promise对象。无返回结果的Promise对象。 | +| Promise\ | 无返回结果的Promise对象。当指定设备管理员应用取消订阅系统管理时间失败时会抛出错误对象。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-bundleManager.md index 66249739bb2d229bb2a855b5cb71e76cc70d9b4e..1f07f73ff0ef1c72242ced25dd950f3d97e0d5eb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-bundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-bundleManager.md @@ -16,7 +16,7 @@ import bundleManager from '@ohos.enterprise.bundleManager'; addAllowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCallback<void>): void; -添加包安装白名单接口,使用callback异步回调。 +指定设备管理员应用添加包安装白名单接口,添加至白名单的应用允许在管理员用户下安装,否则不允许安装,使用callback形式返回是否添加成功。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -28,9 +28,9 @@ addAllowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCal | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| appIds | Array<string> | 是 | 允许安装包的白名单 | -| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| appIds | Array<string> | 是 | 允许安装包的白名单。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -61,7 +61,7 @@ bundleManager.AddAllowedInstallBundles(wantTemp, appIds, (error) => { addAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, callback: AsyncCallback<void>): void; -添加包安装白名单接口,使用callback异步回调。 +指定设备管理员应用添加包安装白名单接口,添加至白名单的应用允许在指定用户下安装,否则不允许安装,使用callback形式返回是否添加成功。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -73,10 +73,10 @@ addAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, ca | 参数 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| appIds | Array<string> | 是 | 允许安装包的白名单 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| appIds | Array<string> | 是 | 允许安装包的白名单。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -107,7 +107,7 @@ bundleManager.AddAllowedInstallBundles(wantTemp, appIds, 100, (error) => { addAllowedInstallBundles(admin: Want, appIds: Array\, userId?: number): Promise<void>; -添加包安装白名单接口,使用promise异步回调。 +指定设备管理员应用添加包安装白名单接口,如果调用接口时传入了可选参数userId,则添加至白名单的应用允许在指定用户下安装,如果调用接口时没有传入参数userId,则添加至白名单的应用允许在当前用户下安装,使用promise形式返回是否添加成功。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -119,15 +119,15 @@ addAllowedInstallBundles(admin: Want, appIds: Array\, userId?: number): | 参数 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| appIds | Array<string> | 是 | 允许安装包的白名单 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| appIds | Array<string> | 是 | 允许安装包的白名单。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。当指定设备管理员应用添加包安装白名单失败时会抛出错误对象。 | **错误码**: @@ -158,7 +158,7 @@ bundleManager.addAllowedInstallBundles(wantTemp, appIds, 100).then(() => { removeAllowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCallback<void>): void; -移除包安装白名单接口,使用callback异步回调。 +指定设备管理员应用移除包安装白名单接口,在白名单存在的情况下,不在包安装白名单中的应用不允许在当前用户下安装,使用callback形式返回移除结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -170,9 +170,9 @@ removeAllowedInstallBundles(admin: Want, appIds: Array\, callback: Async | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| appIds | Array<string> | 是 | 移除允许安装包的白名单 | -| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| appIds | Array<string> | 是 | 移除允许安装包的白名单。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -203,7 +203,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, (error) => { removeAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, callback: AsyncCallback<void>): void; -移除包安装白名单接口,使用callback异步回调。 +指定设备管理员应用移除包安装白名单接口,在白名单存在的情况下,不在包安装白名单中的应用不允许在指定用户下安装,使用callback形式返回移除结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -215,10 +215,10 @@ removeAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, | 参数 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| appIds | Array<string> | 是 | 允许安装包的白名单 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| appIds | Array<string> | 是 | 允许安装包的白名单。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -249,7 +249,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, 100, (error) => { removeAllowedInstallBundles(admin: Want, appIds: Array\, userId?: number): Promise<void>; -移除包安装白名单接口,使用promise异步回调。 +指定设备管理员应用移除包安装白名单接口,在白名单存在的情况下,如果调用接口时传入参数userId,则不在包安装白名单中的应用不允许在指定用户下安装,如果调用接口时没有传入参数userId,则不在包安装白名单中的应用不允许在当前用户下安装,使用promise形式返回移除结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -261,15 +261,15 @@ removeAllowedInstallBundles(admin: Want, appIds: Array\, userId?: number | 参数 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| appIds | Array\<string> | 是 | 允许安装包的白名单 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| appIds | Array\<string> | 是 | 允许安装包的白名单。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。当指定设备管理员应用移除包安装白名单失败时会抛出错误对象。 | **错误码**: @@ -298,9 +298,52 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, 100).then(() => { ## bundleManager.getAllowedInstallBundles +getAllowedInstallBundles(admin: Want, callback: AsyncCallback<Array<string>>): void; + +指定管理员应用获取管理员用户下的包安装白名单接口,使用callback形式返回获取包安装白名单。 + +**需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager + +**系统API**: 此接口为系统接口。 + +**参数:** + +| 参数 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | + +**错误码**: + +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) + +| 错误码ID | 错误信息 | +| ------- | ---------------------------------------------------------------------------- | +| 9200003 | the administrator ability component is invalid. | +| 9200007 | the system ability work abnormally. | + +**示例:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; + +bundleManager.getAllowedInstallBundles(wantTemp, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.getAllowedInstallBundles + getAllowedInstallBundles(admin: Want, userId: number, callback: AsyncCallback<Array<string>>): void; -获取包安装白名单接口,使用callback异步回调。 +指定管理员应用获取指定用户下的包安装白名单接口,使用callback形式返回获取包安装白名单。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -312,9 +355,9 @@ getAllowedInstallBundles(admin: Want, userId: number, callback: AsyncCallback< | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -344,7 +387,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, 100, (error) => { getAllowedInstallBundles(admin: Want, userId?: number): Promise<Array<string>>; -获取包安装白名单接口,使用promise异步回调。 +指定管理员应用获取管理员用户下包安装白名单接口,使用promise形式返回获取包安装白名单。 **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -356,14 +399,14 @@ getAllowedInstallBundles(admin: Want, userId?: number): Promise<Array<stri | 参数 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<void> | 返回结果为String类型数组的Promise对象。 | +| Promise<Array<string>> | Promise对象,返回管理员用户下的包安装白名单。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md index 23cdc4b26795752e36031617b57a4bebc8d352f0..b3a7bb6eef5d14b0104e1bb053c68e37af2caf5f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @@ -16,7 +16,7 @@ import dateTimeManager from '@ohos.enterprise.dateTimeManager' setDateTime(admin: Want, time: number, callback: AsyncCallback\): void -设置系统时间。使用callback异步回调。 +指定设备管理员应用设置系统时间。使用callback形式返回设置结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_DATETIME @@ -30,7 +30,7 @@ setDateTime(admin: Want, time: number, callback: AsyncCallback\): void | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | time | number | 是 | 时间戳(ms)。 | -| callback | AsyncCallback\ | 是 | 回调函数。当系统时间设置成功err为null,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -59,7 +59,7 @@ dateTimeManager.setDateTime(wantTemp, 1526003846000, (error) => { setDateTime(admin: Want, time: number): Promise\ -设置系统时间。使用Promise异步回调。 +指定设备管理员应用设置系统时间。使用Promise形式返回设置结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_DATETIME @@ -106,7 +106,7 @@ dateTimeManager.setDateTime(wantTemp, 1526003846000).then(() => { disallowModifyDateTime(admin: Want, disallow: boolean, callback: AsyncCallback\): void -禁止修改系统时间。使用callback异步回调。 +指定设备管理员应用禁止修改系统时间。使用callback形式返回结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_DATETIME @@ -120,7 +120,7 @@ disallowModifyDateTime(admin: Want, disallow: boolean, callback: AsyncCallback\< | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | | disallow | boolean | 是 | true 表示禁止修改系统时间,false表示允许修改系统时间。 | -| callback | AsyncCallback\ | 是 | 回调函数。当禁止修改系统时间设置成功err为null,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -149,7 +149,7 @@ dateTimeManager.disallowModifyDateTime(wantTemp, true, (error) => { disallowModifyDateTime(admin: Want, disallow: boolean): Promise\ -禁止修改系统时间。使用Promise异步回调。 +指定设备管理员应用禁止修改系统时间。使用Promise形式返回结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_DATETIME @@ -168,7 +168,7 @@ disallowModifyDateTime(admin: Want, disallow: boolean): Promise\ | 类型 | 说明 | | ----- | ----------------------------------- | -| Promise\ | Promise对象。无返回结果的Promise对象。 | +| Promise\ | 无返回结果的Promise对象。当指定设备管理员应用禁止修改系统时间失败时抛出错误对象。 | **错误码**: @@ -196,7 +196,7 @@ dateTimeManager.disallowModifyDateTime(wantTemp, true).then(() => { isModifyDateTimeDisallowed(admin: Want, callback: AsyncCallback\): void -查询是否允许修改系统时间。使用callback异步回调。 +指定设备管理员应用查询是否允许修改系统时间。使用callback形式返回是否禁止修改系统时间策略。 **需要权限:** ohos.permission.ENTERPRISE_SET_DATETIME @@ -209,7 +209,7 @@ isModifyDateTimeDisallowed(admin: Want, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | -| callback | AsyncCallback\ | 是 | 回调函数。callbac方式返回是否禁止修改系统时间策略。true表示禁止修改系统时间,否则表示允许修改系统时间。 | +| callback | AsyncCallback\ | 是 | 回调函数,callbac方式返回是否禁止修改系统时间策略,true表示禁止修改系统时间,否则表示允许修改系统时间。 | **错误码**: @@ -238,7 +238,7 @@ dateTimeManager.isModifyDateTimeDisallowed(wantTemp, (error) => { isModifyDateTimeDisallowed(admin: Want): Promise\ -查询是否允许修改系统时间。使用Promise异步回调。 +指定设备管理员应用查询是否允许修改系统时间。使用Promise形式返回是否禁止修改系统时间策略。 **需要权限:** ohos.permission.ENTERPRISE_SET_DATETIME @@ -256,7 +256,7 @@ isModifyDateTimeDisallowed(admin: Want): Promise\ | 类型 | 说明 | | ----- | ----------------------------------- | -| Promise\ | Promise对象。promise方式返回是否禁止修改系统时间策略。true表示禁止修改系统时间,否则表示允许修改系统时间。 | +| Promise\ | Promise对象。promise方式返回是否禁止修改系统时间策略,true表示禁止修改系统时间,否则表示允许修改系统时间。 | **错误码**: 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 index d497f07be910d4aeba6949dce61f4ac7b94e9cf6..00dd06e183b4188caa4b800b444e5afc4f21c1fc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @@ -16,7 +16,7 @@ import deviceControl from '@ohos.enterprise.deviceControl' resetFactory(admin: Want, callback: AsyncCallback): void -恢复出厂设置。使用callback异步回调。 +指定设备管理员应用恢复出厂设置。使用callback异步回调。 **需要权限:** ohos.permission.ENTERPRISE_RESET_DEVICE @@ -29,7 +29,7 @@ resetFactory(admin: Want, callback: AsyncCallback): void | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | -| callback | AsyncCallback\ | 是 | 回调函数。当系统时间设置成功err为null,否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -58,7 +58,7 @@ deviceControl.resetFactory(wantTemp, (error) => { resetFactory(admin: Want): Promise -恢复出厂设置。使用Promise异步回调。 +恢复出厂设置。使用Promise形式返回设置结果。 **需要权限:** ohos.permission.ENTERPRISE_RESET_DEVICE @@ -76,7 +76,7 @@ resetFactory(admin: Want): Promise | 类型 | 说明 | | ----- | ----------------------------------- | -| Promise\ | Promise对象。无返回结果的Promise对象。 | +| Promise\ | 无返回结果的Promise对象。当恢复出厂设置失败时抛出错误对象。| **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md index 0fc0db10c4ceca845a55eda4d93d6ea54f4cbc66..c62ff21885856223fec6dabe5cbc7fbed5b238a7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @@ -16,7 +16,7 @@ import deviceInfo from '@ohos.enterprise.deviceInfo'; getDeviceSerial(admin: Want, callback: AsyncCallback<string>): void -获取设备序列号,使用callback形式返回设备序列号。 +指定设备管理员应用获取设备序列号,使用callback形式返回设备序列号。 **需要权限:** ohos.permission.ENTERPRISE_GET_DEVICE_INFO @@ -28,8 +28,8 @@ getDeviceSerial(admin: Want, callback: AsyncCallback<string>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback<string> | 是 | callback方式返回设备序列号 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当接口调用成功,err为null,data为设备序列号,否则err为错误对象。 | **错误码**: @@ -60,7 +60,7 @@ deviceInfo.getDeviceSerial(wantTemp, (error, result) => { getDeviceSerial(admin: Want): Promise<string> -获取设备序列号,使用callback形式返回设备序列号。 +指定设备管理员应用获取设备序列号,使用Promise形式返回设备序列号。 **需要权限:** ohos.permission.ENTERPRISE_GET_DEVICE_INFO @@ -72,13 +72,13 @@ getDeviceSerial(admin: Want): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<string> | Promise方式返回设备序列号 | +| Promise<string> | Promise对象,返回设备序列号。 | **错误码**: @@ -107,7 +107,7 @@ deviceInfo.getDeviceSerial(wantTemp).then((result) => { getDisplayVersion(admin: Want, callback: AsyncCallback<string>): void; -获取设备版本号,使用callback形式返回设备版本号。 +指定设备管理员应用获取设备版本号,使用callback形式返回设备版本号。 **需要权限:** ohos.permission.ENTERPRISE_GET_DEVICE_INFO @@ -119,8 +119,8 @@ getDisplayVersion(admin: Want, callback: AsyncCallback<string>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback<string> | 是 | callback方式返回设备版本号 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当接口调用成功,err为null,data为设备版本号,否则err为错误对象。 | **错误码**: @@ -151,7 +151,7 @@ deviceInfo.getDisplayVersion(wantTemp, (error, result) => { getDisplayVersion(admin: Want): Promise<string> -获取设备版本号,使用callback形式返回设备版本号。 +指定设备管理员应用获取设备版本号,使用Promise形式返回设备版本号。 **需要权限:** ohos.permission.ENTERPRISE_GET_DEVICE_INFO @@ -163,13 +163,13 @@ getDisplayVersion(admin: Want): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<string> | Promise方式返回设备版本号 | +| Promise<string> | Promise对象,返回设备版本号。 | **错误码**: @@ -198,7 +198,7 @@ deviceInfo.getDisplayVersion(wantTemp).then((result) => { getDeviceName(admin: Want, callback: AsyncCallback<string>): void -获取设备名称,使用callback形式返回设备名称。 +指定设备管理员应用获取设备名称,使用callback形式返回设备名称。 **需要权限:** ohos.permission.ENTERPRISE_GET_DEVICE_INFO @@ -210,8 +210,8 @@ getDeviceName(admin: Want, callback: AsyncCallback<string>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback<string> | 是 | callback方式返回设备名称 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当接口调用成功,err为null,data为设备名称,否则err为错误对象。 | **错误码**: @@ -242,7 +242,7 @@ deviceInfo.getDeviceName(wantTemp, (error, result) => { getDeviceName(admin: Want): Promise<string> -获取设备名称,使用callback形式返回设备名称。 +指定设备管理员应用获取设备名称,使用Promise形式返回设备名称。 **需要权限:** ohos.permission.ENTERPRISE_GET_DEVICE_INFO @@ -254,13 +254,13 @@ getDeviceName(admin: Want): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<string> | Promise方式返回设备名称 | +| Promise<string> | Promise结果,返回设备名称。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md index d42ddca63e9e1e464bbc68ca5eecba4798837a0e..cbe54b4d8f951d5bd317d03de2bde061c309fa44 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @@ -16,7 +16,7 @@ import networkManager from '@ohos.enterprise.networkManager'; getAllNetworkInterfaces(admin: Want, callback: AsyncCallback<Array<string>>): void -获取所有活动的网络接口,使用callback形式返回网络接口名称数组。 +指定设备管理员应用获取所有活动的网络接口,使用callback形式返回网络接口名称数组。 **需要权限:** ohos.permission.GET_NETWORK_INFO @@ -28,8 +28,8 @@ getAllNetworkInterfaces(admin: Want, callback: AsyncCallback<Array<string& | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback<Array<string>> | 是 | callback方式返回网络接口名称数组 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当接口调用成功,err为null,data为网络接口名称数组,否则err为错误对象。 | **错误码**: @@ -60,7 +60,7 @@ networkManager.getAllNetworkInterfaces(admin, (error, result) => { getAllNetworkInterfaces(admin: Want): Promise<Array<string>> -获取所有活动的网络接口,使用promise形式返回网络接口名称数组。 +指定设备管理员应用获取所有活动的网络接口,使用Promise形式返回网络接口名称数组。 **需要权限:** ohos.permission.ENTERPRISE_GET_NETWORK_INFO @@ -72,13 +72,13 @@ getAllNetworkInterfaces(admin: Want): Promise<Array<string>> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<Array<string>> | Promise方式返回网络接口名称数组 | +| Promise<Array<string>> | Promise结果,返回网络接口名称数组。 | **错误码**: @@ -107,7 +107,7 @@ networkManager.getAllNetworkInterfaces(wantTemp).then((result) => { getIpAddress(admin: Want, networkInterface: string, callback: AsyncCallback<string>): void -获取设备IP地址,使用callback形式返回设备IP地址。 +指定设备管理员应用根据networkInterface获取设备IP地址,使用callback形式返回设备IP地址。 **需要权限:** ohos.permission.GET_NETWORK_INFO @@ -119,9 +119,9 @@ getIpAddress(admin: Want, networkInterface: string, callback: AsyncCallback<s | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| networkInterface | string | 是 | 指定网络接口 | -| callback | AsyncCallback<string> | 是 | callback方式返回设备IP地址 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| networkInterface | string | 是 | 指定网络接口。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当接口调用成功,err为null,data为IP地址,否则err为错误对象。 | **错误码**: @@ -152,7 +152,7 @@ networkManager.getIpAddress(wantTemp, "eth0", (error, result) => { getIpAddress(admin: Want, networkInterface: string): Promise<string> -获取设备IP地址,使用promise形式返回设备IP地址。 +指定设备管理员应用根据networkInterface获取设备IP地址,使用Promise形式返回设备IP地址。 **需要权限:** ohos.permission.ENTERPRISE_GET_NETWORK_INFO @@ -164,14 +164,14 @@ getIpAddress(admin: Want, networkInterface: string): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| networkInterface | string | 是 | 指定网络接口 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| networkInterface | string | 是 | 指定网络接口。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<string> | Promise方式返回设备IP地址 | +| Promise<string> | Promise结果,返回设备IP地址。 | **错误码**: @@ -200,7 +200,7 @@ networkManager.getIpAddress(wantTemp, "eth0").then((result) => { getMac(admin: Want, networkInterface: string, callback: AsyncCallback<string>): void -获取设备MAC地址,使用callback形式返回设备MAC地址。 +指定设备管理员应用根据networkInterface获取设备MAC地址,使用callback形式返回设备MAC地址。 **需要权限:** ohos.permission.ENTERPRISE_GET_NETWORK_INFO @@ -212,9 +212,9 @@ getMac(admin: Want, networkInterface: string, callback: AsyncCallback<string& | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| networkInterface | string | 是 | 指定网络接口 | -| callback | AsyncCallback<string> | 是 | callback方式返回设备MAC地址 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| networkInterface | string | 是 | 指定网络接口。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当接口调用成功,err为null,data为设备MAC地址,否则err为错误对象。 | **错误码**: @@ -245,7 +245,7 @@ networkManager.getMac(wantTemp, "eth0", (error, result) => { getIpAddress(admin: Want, networkInterface: string): Promise<string> -获取设备MAC地址,使用promise形式返回设备IP地址。 +指定设备管理员应用根据networkInterface获取设备MAC地址,使用Promise形式返回设备IP地址。 **需要权限:** ohos.permission.ENTERPRISE_GET_NETWORK_INFO @@ -257,14 +257,14 @@ getIpAddress(admin: Want, networkInterface: string): Promise<string> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| networkInterface | string | 是 | 指定网络接口 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| networkInterface | string | 是 | 指定网络接口。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<string> | Promise方式返回设备MAC地址 | +| Promise<string> | Promise结果,返回设备MAC地址。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md index 5969fa90986b14987c0463006e69a47c080d1d9a..2450bf9cb6a746dbaca55ddb6590ef11e86007bd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @@ -16,7 +16,7 @@ import wifiManager from '@ohos.enterprise.wifiManager'; isWifiActive(admin: Want, callback: AsyncCallback<boolean>): void -查询wifi开启状态,使用callback形式返回wifi开启状态。 +指定设备管理员应用查询wifi开启状态,使用callback形式返回wifi开启状态。 **需要权限:** ohos.permission.ENTERPRISE_SET_WIFI @@ -28,8 +28,8 @@ isWifiActive(admin: Want, callback: AsyncCallback<boolean>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| callback | AsyncCallback<boolean> | 是 | callback方式返回wifi开启状态 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数,当接口调用成功,err为null,data为boolean值,true表示wifi开启,false表示wifi关闭,否则err为错误对象。 | **错误码**: @@ -60,7 +60,7 @@ wifiManager.isWifiActive(wantTemp, (error, result) => { isWifiActive(admin: Want): Promise<boolean> -获取wifi开启状态,使用promise形式返回wifi开启状态。 +获取wifi开启状态,使用Promise形式返回wifi开启状态。 **需要权限:** ohos.permission.ENTERPRISE_SET_WIFI @@ -72,13 +72,13 @@ isWifiActive(admin: Want): Promise<boolean> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<boolean> | Promise方式返回wifi开启状态 | +| Promise<boolean> | Promise结果,返回wifi开启状态,true表示wifi开启,false表示wifi关闭。 | **错误码**: @@ -107,7 +107,7 @@ wifiManager.isWifiActive(wantTemp).then((result) => { setWifiProfile(admin: Want, profile: WifiProfile, callback: AsyncCallback<void>): void -配置wifi连接到指定网络,使用callback异步回调。 +配置wifi,使连接到指定网络,使用callback返回配置结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_WIFI @@ -119,9 +119,9 @@ setWifiProfile(admin: Want, profile: WifiProfile, callback: AsyncCallback<voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| profile | [WifiProfile](#wifiprofile) | 是 | WLAN配置信息 | -| callback | AsyncCallback<void> | 是 | 回调函数。当接口调用成功err为null,否则为错误对象。 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| profile | [WifiProfile](#wifiprofile) | 是 | WLAN配置信息。 | +| callback | AsyncCallback<void> | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 | **错误码**: @@ -157,7 +157,7 @@ wifiManager.setWifiProfile(wantTemp, profile, (error) => { setWifiProfile(admin: Want, profile: WifiProfile): Promise<void> -配置wifi连接到指定网络,使用promise异步回调。 +配置wifi,使连接到指定网络,使用Promise返回配置结果。 **需要权限:** ohos.permission.ENTERPRISE_SET_WIFI @@ -169,14 +169,14 @@ setWifiProfile(admin: Want, profile: WifiProfile): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ----- | ----------------------------------- | ---- | ------- | -| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用 | -| profile | [WifiProfile](#wifiprofile) | 是 | WLAN配置信息 | +| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 | +| profile | [WifiProfile](#wifiprofile) | 是 | WLAN配置信息。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。当配置wifi连接到指定网络失败时会抛出错误对象。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-backup.md b/zh-cn/application-dev/reference/apis/js-apis-file-backup.md new file mode 100644 index 0000000000000000000000000000000000000000..903f7fc07acc394651d9c4fdba7976e566ff25d1 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-file-backup.md @@ -0,0 +1,686 @@ +# @ohos.file.backup (备份恢复) + +该模块为应用提供备份/恢复数据的能力。 + +> **说明:** +> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块接口为系统接口。 +> - 本模块支持对错误码进行处理,错误码及其适配方式[参考文档](../errorcodes/errorcode-filemanagement.md#错误码适配指导)。 + +## 导入模块 + +```js +import backup from '@ohos.file.backup'; +``` + +## FileMeta + +文件的元数据,包含一个应用名称以及文件uri。FileMeta在执行备份/恢复时是不可缺少的对象 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ---------------------------------------------------------------------------------------------- | +| bundleName | string | 是 | 应用名称,可通过[bundle.BundleInfo](js-apis-bundle-BundleInfo.md)提供的获取方式获取。 | +| uri | string | 是 | 应用沙箱内待传输文件的名称,当前uri尚未升级为标准格式,仅接受0-9a-zA-Z下划线(_)点(.)组成的名称 | + +## FileData + +文件的元数据,包含一个已经打开的文件描述符。FileData在执行备份/恢复时是不可缺少的对象 + +> **说明:** +> - FileData使用完成后必须关闭,如不关闭会出现内心泄露问题。关闭的方法可参考由[@ohos.file.fs](./js-apis-file-fs.md)提供的[fs.closeSync](js-apis-file-fs.md#fsclosesync)等相关关闭接口 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +| 名称 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ---------------------------------------- | +| fd | number | 是 | 已经打开的文件描述符,通过备份服务获取。 | + +## File + +一个文件对象。 +继承[FileMeta](#filemeta)和[FileData](#filedata) + +> **说明:** +> - file.backup.File与@ohos.file.fs中的提供的[File](js-apis-file-fs.md#file)是带有不同的涵义,前者是继承[FileMeta](#filemeta)和[FileData](#filedata)的对象而后者只有一个文件描述符的对象。请注意做区分,不要混淆。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +## GeneralCallbacks + +备份/恢复过程中的通用回调,备份服务将通过这些回调通知客户端其应用的备份/恢复阶段。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +### onFileReady + +onFileReady : AsyncCallback<File> + +回调函数。当服务端返向客户端发送文件成功,err为undefined,否则为错误对象。 + +> **说明:** +> - AsyncCallback回调中返回的File 所属file.backup.[File](#file)类型,返回的文件归备份服务所有,一旦文件关闭,备份服务将选择合适的实际去清理,但客户端必须关闭文件句柄。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**示例:** + + ```js + import fs from '@ohos.file.fs'; + onFileReady: (err, file) => { + if (err) { + console.error('onFileReady failed with err: ' + err); + } + console.info('onFileReady success with file: ' + file.bundleName + ' ' + file.uri); + fs.closeSync(file.fd); + } + ``` + +### onBundleBegin + +onBundleBegin : AsyncCallback<string> + + 回调函数。当应用备份/恢复开始时返回bundle名称成功,err为undefined,否则为错误对象。 + +> **说明:** +> - 回调函数。当应用备份/恢复开始时,err为undefined,否则为错误对象。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**示例:** + + ```js + onBundleBegin: (err, bundleName) => { + if (err) { + console.error('onBundleBegin failed with err: ' + err); + } + console.info('onBundleBegin success with bundleName: ' + bundleName); + } + ``` + +### onBundleEnd + +onBundleEnd : AsyncCallback<string> + +回调函数。当应用备份/恢复结束后返回bundle名称成功,err为undefined,否则为错误对象。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**示例:** + + ```js + onBundleEnd: (err, bundleName) => { + if (err) { + console.error('onBundleEnd failed with err: ' + err); + } + console.info('onBundleEnd success with bundleName: ' + bundleName); + } + ``` + +### onAllBundlesEnd + +onAllBundlesEnd : AsyncCallback<undefined> + +回调函数。当所有bundle的备份/恢复过程结束成功,err为undefined,否则为错误对象。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**示例:** + + ```js + onAllBundlesEnd: (err) => { + if (err) { + console.error('onAllBundlesEnd failed with err: ' + err); + } + console.info('onAllBundlesEnd success'); + } + ``` + +### onBackupServiceDied + +onBackupServiceDied : Callback<undefined> + +回调函数,返回备份服务死亡。 + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**示例:** + + ```js + onBackupServiceDied: () => { + console.info('onBackupServiceDied success'); + } + ``` + +## getLocalCapabilities + +getLocalCapabilities(callback: AsyncCallback<FileData>): void; + +用于获取一个描述本地能力的Json文件。使用callback异步回调。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------ | +| callback | AsyncCallback<[FileData](#filedata)> | 是 | 回调函数。当获取成功,err为undefined,否则为错误对象。 | + +**示例:** + + ```js + import fs from '@ohos.file.fs'; + try { + backup.getLocalCapabilities((err, fileData) => { + if (err) { + console.error('getLocalCapabilities failed with err: ' + err); + } + console.info('getLocalCapabilities success'); + fs.closeSync(fileData.fd); + }); + } catch (err) { + console.error('getLocalCapabilities failed with err: ' + err); + } + ``` + + +**返回的能力文件内容示例:** + + ```json + { + "bundleInfos" :[{ + "allToBackup" : true, + "extensionName" : "BackupExtensionAbility", + "name" : "com.example.hiworld", + "needToInstall" : false, + "spaceOccupied" : 0, + "versionCode" : 1000000, + "versionName" : "1.0.0" + }], + "deviceType" : "phone", + "systemFullName" : "OpenHarmony-4.0.0.0" + } + ``` + +## getLocalCapabilities + +getLocalCapabilities(): Promise<FileData>; + +用于获取一个描述本地能力的Json文件。使用Promise异步回调。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------ | --------------------------------------------------- | +| Promise<[FileData](#filedata)> | Promise对象,返回描述本地能力的Json文件的FileData。 | + +**示例:** + + ```js + import fs from '@ohos.file.fs'; + try { + let fileData = await backup.getLocalCapabilities(); + console.info('getLocalCapabilities success'); + fs.closeSync(fileData.fd); + } catch (err) { + console.error('getLocalCapabilities failed with err: ' + err); + } + ``` + + **返回的能力文件内容示例:** + + ```json + { + "bundleInfos" :[{ + "allToBackup" : true, + "extensionName" : "BackupExtensionAbility", + "name" : "com.example.hiworld", + "needToInstall" : false, + "spaceOccupied" : 0, + "versionCode" : 1000000, + "versionName" : "1.0.0" + }], + "deviceType" : "phone", + "systemFullName" : "OpenHarmony-4.0.0.0" + } + ``` + +## SessionBackup + +备份流程对象,用来支撑应用备份的流程。在使用前,需要先创建SessionBackup实例。 + +### constructor + +constructor(callbacks: GeneralCallbacks); + +备份流程的构造函数,用于获取SessionBackup类的实例。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------- | ---- | -------------------- | +| callback | [GeneralCallbacks](#generalcallbacks) | 是 | 备份流程所需的回调。 | + +**示例:** + + ```js + import fs from '@ohos.file.fs'; + let sessionBackup = new backup.SessionBackup({ + onFileReady: (err, file) => { + if (err) { + console.error('onFileReady failed with err: ' + err); + } + console.info('onFileReady success'); + fs.closeSync(file.fd); + }, + onBundleBegin: (err, bundleName) => { + if (err) { + console.error('onBundleBegin failed with err: ' + err); + } + console.info('onBundleBegin success'); + }, + onBundleEnd: (err, bundleName) => { + if (err) { + console.error('onBundleEnd failed with err: ' + err); + } + console.info('onBundleEnd success'); + }, + onAllBundlesEnd: (err) => { + if (err) { + console.error('onAllBundlesEnd failed with err: ' + err); + } + console.info('onAllBundlesEnd success'); + }, + onBackupServiceDied: () => { + console.info('service died'); + } + }); + ``` + +### appendBundles + +appendBundles(bundlesToBackup: string[], callback: AsyncCallback<void>): void; + +添加需要备份的应用。当前整个流程中,在获取SessionBackup类的实例后只能调用一次。使用callback异步回调。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------------- | ------------------------- | ---- | -------------------------------------------------------------- | +| bundlesToBackup | string[] | 是 | 需要备份的应用名称的数组。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当添加备份应用成功,err为undefined,否则为错误对象。 | + +**示例:** + + ```js + try { + sessionBackup.appendBundles(['com.example.hiworld'], (err) => { + if (err) { + console.error('appendBundles failed with err: ' + err); + } + console.info('appendBundles success'); + }); + } catch (err) { + console.error('appendBundles failed with err: ' + err); + } + ``` + +### appendBundles + +appendBundles(bundlesToBackup: string[]): Promise<void>; + +添加需要备份的应用。当前整个流程中,在获取SessionBackup类的实例后只能调用一次。使用Promise异步回调。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------------- | -------- | ---- | -------------------------- | +| bundlesToBackup | string[] | 是 | 需要备份的应用名称的数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```js + try { + await sessionBackup.appendBundles(['com.example.hiworld']); + console.info('appendBundles success'); + } catch (err) { + console.error('appendBundles failed with err: ' + err); + } + ``` + +## SessionRestore + +恢复流程对象,用来支撑应用恢复的流程。在使用前,需要先创建SessionRestore实例。 + +### constructor + +constructor(callbacks: GeneralCallbacks); + +恢复流程的构造函数,用于获取SessionRestore类的实例。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------- | ---- | -------------------- | +| callback | [GeneralCallbacks](#generalcallbacks) | 是 | 恢复流程所需的回调。 | + +**示例:** + + ```js + import fs from '@ohos.file.fs'; + let sessionRestore = new backup.SessionRestore({ + onFileReady: (err, file) => { + if (err) { + console.error('onFileReady failed with err: ' + err); + } + console.info('onFileReady success'); + fs.closeSync(file.fd); + }, + onBundleBegin: (err, bundleName) => { + if (err) { + console.error('onBundleBegin failed with err: ' + err); + } + console.info('onBundleBegin success'); + }, + onBundleEnd: (err, bundleName) => { + if (err) { + console.error('onBundleEnd failed with err: ' + err); + } + console.info('onBundleEnd success'); + }, + onAllBundlesEnd: (err) => { + if (err) { + console.error('onAllBundlesEnd failed with err: ' + err); + } + console.info('onAllBundlesEnd success'); + }, + onRestoreServiceDied: () => { + console.info('service died'); + } + }); + ``` + +### appendBundles + +appendBundles(remoteCapabilitiesFd: number, bundlesToBackup: string[], callback: AsyncCallback<void>): void; + +添加需要恢复的应用。当前整个流程中,在获取SessionRestore类的实例后只能调用一次。使用callback异步回调。 + +> **说明:** +> - 服务在恢复时需要其能力文件进行相关校验。 +> - 因此remoteCapabilitiesFd可通过备份端服务所提供的[getLocalCapabilities](#getlocalcapabilities)接口获取,可对其内容根据恢复应用的实际状况修改参数。也可通过getLocalCapabilities提供的json示例自行生成能力文件。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------------- | ------------------------- | ---- | -------------------------------------------------------------- | +| remoteCapabilitiesFd | number | 是 | 用于恢复所需能力文件的文件描述符。 | +| bundlesToBackup | string[] | 是 | 需要恢复的应用名称的数组。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当添加恢复应用成功,err为undefined,否则为错误对象。 | + +**示例:** + + ```js + try { + let fileData = await backup.getLocalCapabilities(); + console.info('getLocalCapabilities success'); + sessionRestore.appendBundles(fileData.fd, ['com.example.hiworld'], (err) => { + if (err) { + console.error('appendBundles failed with err: ' + err); + } + console.info('appendBundles success'); + }); + } catch (err) { + console.error('appendBundles failed with err: ' + err); + } + ``` + +### appendBundles + +appendBundles(remoteCapabilitiesFd: number, bundlesToBackup: string[]): Promise<void>; + +添加需要恢复的应用。当前整个流程中,在获取SessionRestore类的实例后只能调用一次。使用Promise异步回调。 + +> **说明:** +> - 服务在恢复时需要其能力文件进行相关校验。 +> - 因此remoteCapabilitiesFd可通过备份端服务所提供的[getLocalCapabilities](#getlocalcapabilities)接口获取,可对其内容根据恢复应用的实际状况修改参数。也可通过getLocalCapabilities提供的json示例自行生成能力文件。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------------- | -------- | ---- | ---------------------------------- | +| remoteCapabilitiesFd | number | 是 | 用于恢复所需能力文件的文件描述符。 | +| bundlesToBackup | string[] | 是 | 需要恢复的应用包名称的数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```js + try { + let fileData = await backup.getLocalCapabilities(); + console.info('getLocalCapabilities success'); + await sessionRestore.appendBundles(fileData.fd, ['com.example.hiworld']); + console.info('appendBundles success'); + } catch (err) { + console.error('appendBundles failed with err: ' + err); + } + ``` + +### getFileHandle + +getFileHandle(fileMeta: FileMeta, callback: AsyncCallback<void>): void; + +用于请求从服务中获取共享文件。使用callback异步回调。 + +> **说明:** +> - 这个接口是零拷贝特性(减少不必要的内存拷贝,实现了更高效率的传输)的一部分。零拷贝方法可参考由[@ohos.file.fs](./js-apis-file-fs.md)提供的[fs.copyFile](js-apis-file-fs.md#fscopyfile)等相关零拷贝接口。 +> - 使用getFileHandle前需要获取SessionRestore类的实例,并且成功通过appendBundles添加需要待恢复的应用。 +> - 开发者可以通过onFileReady回调来获取文件句柄,当客户端完成文件操作时,需要使用publishFile来进行发布。 +> - 根据所需要恢复的文件个数,可以多次调用getFileHandle。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | -------------------------------------------------------------- | +| fileMeta | [FileMeta](#filemeta) | 是 | 恢复文件的元数据。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当请求文件句柄成功,err为undefined,否则为错误对象。 | + +**示例:** + + ```js + try { + sessionRestore.getFileHandle({ + bundleName: "com.example.hiworld", + uri: "test.txt" + }, (err, file) => { + if (err) { + console.error('getFileHandle failed with err: ' + err); + } + console.info('getFileHandle success'); + }); + } catch (err) { + console.error('getFileHandle failed with err: ' + err); + } + ``` + +### getFileHandle + +getFileHandle(fileMeta: FileMeta): Promise<void>; + +用于请求从服务中获取共享文件。使用Promise异步回调。 + +> **说明:** +> - 这个接口是零拷贝特性(减少不必要的内存拷贝,实现了更高效率的传输)的一部分。零拷贝方法可参考由[@ohos.file.fs](./js-apis-file-fs.md)提供的[fs.copyFile](js-apis-file-fs.md#fscopyfile)等相关零拷贝接口。 +> - 使用getFileHandle前需要获取SessionRestore类的实例,并且成功通过appendBundles添加需要待恢复的应用。 +> - 开发者可以通过onFileReady回调来获取文件句柄,当客户端完成文件操作时,需要使用publishFile来进行发布。 +> - 根据所需要恢复的文件个数,可以多次调用getFileHandle。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ------------------ | +| fileMeta | [FileMeta](#filemeta) | 是 | 恢复文件的元数据。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```js + try { + await sessionRestore.getFileHandle({ + bundleName: "com.example.hiworld", + uri: "test.txt" + }); + console.info('getFileHandle success'); + } catch (err) { + console.error('getFileHandle failed with err: ' + err); + } + ``` + +### publishFile + +publishFile(fileMeta: FileMeta, callback: AsyncCallback<void>): void; + +用于将FileMeta发布到备份服务,使服务知道文件的内容已经准备完成。使用callback异步回调。 + +> **说明:** +> - 这个接口是零拷贝特性(减少不必要的内存拷贝,实现了更高效率的传输)的一部分。零拷贝方法可参考由[@ohos.file.fs](./js-apis-file-fs.md)提供的[fs.copyFile](js-apis-file-fs.md#fscopyfile)等相关零拷贝接口。 +> - 服务端通过onFileReady返回文件句柄后,客户端可通过零拷贝操作将其对应的文件内容拷贝到服务端提供的文件句柄中。 +> - 在完成拷贝操作后可使用publishFile通知备份服务文件已经准备完成。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------------------------------------------- | +| fileMeta | [FileMeta](#filemeta) | 是 | 恢复文件元数据。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当发布文件成功,err为undefined,否则为错误对象。 | + +**示例:** + + ```js + try { + onFileReady: (err, file) => { + if (err) { + console.error('onFileReady failed with err: ' + err); + } + console.info('onFileReady success'); + fs.closeSync(file.fd); + sessionRestore.publishFile({ + bundleName: file.bundleName, + uri: file.uri + }, (err) => { + if (err) { + console.error('publishFile failed with err: ' + err); + } + console.info('publishFile success'); + }); + } + } catch (err) { + console.error('publishFile failed with err: ' + err); + } + ``` + +### publishFile + +publishFile(fileMeta: FileMeta): Promise<void>; + +用于将FileMeta发布到备份服务,使服务知道文件的内容已经准备完成。使用Promise异步回调。 + +> **说明:** +> - 这个接口是零拷贝特性(减少不必要的内存拷贝,实现了更高效率的传输)的一部分。零拷贝方法可参考由[@ohos.file.fs](./js-apis-file-fs.md)提供的[fs.copyFile](js-apis-file-fs.md#fscopyfile)等相关零拷贝接口。 +> - 服务端通过onFileReady返回文件句柄后,客户端可通过零拷贝操作将其对应的文件内容拷贝到服务端提供的文件句柄中。 +> - 在完成拷贝操作后可使用publishFile通知备份服务文件已经准备完成。 + +**需要权限**:ohos.permission.BACKUP + +**系统能力**:SystemCapability.FileManagement.StorageService.Backup + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ---------------- | +| fileMeta | [FileMeta](#filemeta) | 是 | 恢复文件元数据。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```js + try { + onFileReady: (err, file) => { + if (err) { + console.error('onFileReady failed with err: ' + err); + } + console.info('onFileReady success'); + fs.closeSync(file.fd); + await sessionRestore.publishFile({ + bundleName: file.bundleName, + uri: file.uri + }); + console.info('publishFile success'); + }, + } catch (err) { + console.error('publishFile failed with err: ' + err); + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md index dcaf26d5b4cc123caf8eb62d8accf752fc2d8b3b..7b1c68e35a569c2abf385020f5315e1bdbb215b3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @@ -1253,6 +1253,257 @@ try { }; ``` +## FileAccessHelper.query10+ + +query(uri:string, metaJson: string) : Promise<string> + +通过uri查询文件或目录的相关信息,使用Promise异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ---------------------------------------------------- | +| uri | string | 是 | 所选文件或目录的uri(从[FileInfo](#fileinfo)中获取) | +| metaJson | string | 是 | json字符串,包含查询属性[FILEKEY](#filekey10) | + +**返回值:** + +| 类型 | 说明 | +| :-------------------- | :------------------------------- | +| Promise<string> | 返回json字符串,包括查询属性和值 | + +**示例:** + +```js +var imageFileRelativePath = "Download/queryTest/image/01.jpg"; +var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" }); +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + var fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath); + let queryResult = await fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath); + console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path); +} catch (error) { + console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message); +}; +``` + +## FileAccessHelper.query10+ + +query(uri:string, metaJson: string, callback: AsyncCallback<string>) : void + +通过uri查询文件或目录的相关信息,使用callback异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ---------------------------------------------------- | +| uri | string | 是 | 所选文件或目录的uri(从[FileInfo](#fileinfo)中获取) | +| metaJson | string | 是 | json字符串,包含查询属性[FILEKEY](#filekey10) | +| callback | AsyncCallback<string> | 是 | 返回json字符串,包括查询属性和值 | + +**示例:** + +```js +var imageFileRelativePath = "Download/queryTest/image/01.jpg"; +var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" }); +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + var fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath); + fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath, (err, queryResult)=>{ + if (err) { + console.log("query_file_single faf query Failed, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path); + }) +} catch (error) { + console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message); +}; +``` + +## FileAccessHelper.copy10+ + +copy(sourceUri: string, destUri: string, force?: boolean) : Promise<Array<CopyResult>> + +复制文件或目录,使用 Promise 异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------- | ---- | ------------------------------------------------------------ | +| sourceUri | string | 是 | 待拷贝的源文件(夹)的 uri,例如:datashare:///media/file/102 | +| destUri | string | 是 | 目标文件夹的 uri,例如:datashare:///media/file/101 | +| force | boolean | 否 | 含有同名文件时是否强制覆盖文件,force 为 true 时强制覆盖文件,force 为空或 false 时不强制覆盖文件 | + +**返回值:** + +| 类型 | 说明 | +| :------------------------------------------------------ | :----------------------------------------------------------- | +| Promise<Array<[CopyResult](#copyresult10)>> | 返回 copyresult 数组,copyResult 为复制操作失败的返回信息,复制成功无返回信息 | + +**示例 1:force 为空** + +```js +// 以媒体库uri为例 +// 示例代码中的sourceFile表示Download目录下的源文件(夹),destFile表示Download目录下的目标文件夹,该uri对应fileInfo中的uri +// 开发者应根据自己实际获取的uri进行开发 +let sourceFile = "datashare:///media/file/102"; +let destFile = "datashare:///media/file/101"; +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + let copyResult = await fileAccessHelper.copy(sourceFile, destFile); + if (copyResult.length === 0) { + console.log("copy success"); + } else { + for (let i = 0; i < copyResult.length; i++) { + console.error("errCode" + copyResult[i].errCode); + console.error("errMsg" + copyResult[i].errMsg); + console.error("sourceUri" + copyResult[i].sourceUri); + console.error("destUri" + copyResult[i].destUri); + } + } +} catch (error) { + console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message); +} +``` + +**示例 2:force 为 true** + +```js +// 以媒体库uri为例 +// 示例代码中的sourceFile表示Download目录下的源文件(夹),destFile表示Download目录下的目标文件夹,该uri对应fileInfo中的uri +// 开发者应根据自己实际获取的uri进行开发 +let sourceFile = "datashare:///media/file/102"; +let destFile = "datashare:///media/file/101"; +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + let copyResult = await fileAccessHelper.copy(sourceFile, destFile, true); + if (copyResult.length === 0) { + console.log("copy success"); + } else { + for (let i = 0; i < copyResult.length; i++) { + console.error("errCode" + copyResult[i].errCode); + console.error("errMsg" + copyResult[i].errMsg); + console.error("sourceUri" + copyResult[i].sourceUri); + console.error("destUri" + copyResult[i].destUri); + } + } +} catch (error) { + console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message); +} +``` + +## FileAccessHelper.copy10+ + +copy(sourceUri: string, destUri: string, callback: AsyncCallback<Array<CopyResult>>) : void + +复制文件或目录,使用 callback 异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| sourceUri | string | 是 | 待拷贝的源文件(夹)的 uri,例如:datashare:///media/file/102 | +| destUri | string | 是 | 目标文件夹的 uri,例如:datashare:///media/file/101 | +| callback | <Array<[CopyResult](#copyresult10)>> | 是 | 返回 copyresult 数组,copyResult 为复制操作失败的返回信息,复制成功无返回信息 | + +**示例:** + +```js +// 以媒体库uri为例 +// 示例代码中的sourceFile表示Download目录下的源文件(夹),destFile表示Download目录下的目标文件夹,该uri对应fileInfo中的uri +// 开发者应根据自己实际获取的uri进行开发 +let sourceFile = "datashare:///media/file/102"; +let destFile = "datashare:///media/file/101"; +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + fileAccessHelper.copy(sourceFile, destFile, async (err, copyResult) => { + if (err) { + console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + if (copyResult.length === 0) { + console.log("copy success"); + } else { + for (let i = 0; i < copyResult.length; i++) { + console.error("errCode" + copyResult[i].errCode); + console.error("errMsg" + copyResult[i].errMsg); + console.error("sourceUri" + copyResult[i].sourceUri); + console.error("destUri" + copyResult[i].destUri); + } + } + }); +} catch (error) { + console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message); +} +``` + +## FileAccessHelper.copy10+ + +copy(sourceUri: string, destUri: string, force: boolean, callback: AsyncCallback<Array<CopyResult>>) : void + +复制文件或目录,使用 callback 异步回调。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| sourceUri | string | 是 | 待拷贝的源文件(夹)的 uri,例如:datashare:///media/file/102 | +| destUri | string | 是 | 目标文件夹的 uri,例如:datashare:///media/file/101 | +| force | boolean | 是 | 含有同名文件时是否强制覆盖文件,force 为 true 时强制覆盖文件,force 为空或 false 时不强制覆盖文件 | +| callback | <Array<[CopyResult](#copyresult10)>> | 是 | 返回 copyresult 数组,copyResult 为复制操作失败的返回信息,复制成功无返回信息 | + +**示例:** + +```js +// 以媒体库uri为例 +// 示例代码中的sourceFile表示Download目录下的源文件(夹),destFile表示Download目录下的目标文件夹,该uri对应fileInfo中的uri +// 开发者应根据自己实际获取的uri进行开发 +let sourceFile = "datashare:///media/file/102"; +let destFile = "datashare:///media/file/101"; +try { + // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 + fileAccessHelper.copy(sourceFile, destFile, true, async (err, copyResult) => { + if (err) { + console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + if (copyResult.length === 0) { + console.log("copy success"); + } else { + for (let i = 0; i < copyResult.length; i++) { + console.error("errCode" + copyResult[i].errCode); + console.error("errMsg" + copyResult[i].errMsg); + console.error("sourceUri" + copyResult[i].sourceUri); + console.error("destUri" + copyResult[i].destUri); + } + } + }); +} catch (error) { + console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message); +} +``` + ## RootIterator.next next( ) : { value: RootInfo, done: boolean } @@ -1323,6 +1574,23 @@ FileIterator表示文件夹的迭代器对象,可以通过next同步方法获 | mtime | number | 是 | 否 | 文件(夹)的修改时间 | | mimeType | string | 是 | 否 | 文件(夹)的媒体资源类型 | +## CopyResult10+ + +表示复制操作失败时的返回信息,复制成功时则没有返回信息。 + +**系统能力**:SystemCapability.FileManagement.UserFileService + +**需要权限**:ohos.permission.FILE_ACCESS_MANAGER + +### 属性 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ------ | ---- | ---- | ------------------------------------------------------ | +| sourceUri | string | 是 | 否 | 源文件(夹) uri | +| destUri | string | 是 | 否 | 产生冲突的目标文件的 uri。如果非冲突导致的错误,则为空 | +| errCode | number | 是 | 否 | 错误码 | +| errMsg | string | 是 | 否 | 错误信息 | + ## OPENFLAGS 目前支持的文件打开的标志位。 @@ -1334,3 +1602,20 @@ FileIterator表示文件夹的迭代器对象,可以通过next同步方法获 | READ | 0o0 | 读模式。 | | WRITE | 0o1 | 写模式。 | | WRITE_READ | 0o2 | 读写模式。 | + +## FILEKEY10+ + +支持查询的键。 + +**系统能力:** SystemCapability.FileManagement.UserFileService + +| 名称 | 值 | 说明 | +| ------------- | ------------- | ----------------------------------- | +| DISPLAY_NAME | display_name | 文件名 | +| DATE_ADDED | date_added | 文件创建的日期,例如1501925454 | +| DATE_MODIFIED | date_modified | 文件的修改日期,例如1665310670 | +| RELATIVE_PATH | relative_path | 相对路径,例如Pictures/Screenshots/ | +| FILE_SIZE | size | 文件(夹)大小(单位:字节) | +| WIDTH | width | 图像文件的宽度(单位:像素) | +| HEIGHT | height | 图像文件的高度(单位:像素) | +| DURATION | duration | 音频和视频文件的时长(单位:毫秒) | diff --git a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md index 8e113385b7371271107f7afd45c99adc546205f1..1e7eccc4c18451a0c1521c7d0b47c344e586d8fd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -1,4 +1,4 @@ -# 位置服务 +# @ohos.geolocation (位置服务) 位置服务提供GNSS定位、网络定位、地理编码、逆地理编码、国家码和地理围栏等基本功能。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md index fcdd7111bdb85cac4e21a5c6ca38dcde45148840..6e0ff9955904669d81a26636da37297d77821c13 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md @@ -173,7 +173,7 @@ getServiceDump(serviceid : number, fd : number, args : Array\) : void **示例:** ```js -import fileio from '@ohos.fileio' +import fs from '@ohos.file.fs' import hidebug from '@ohos.hidebug' import featureAbility from '@ohos.ability.featureAbility' @@ -181,7 +181,7 @@ let context = featureAbility.getContext(); context.getFilesDir().then((data) => { var path = data + "/serviceInfo.txt" console.info("output path: " + path) - let fd = fileio.openSync(path, 0o102, 0o666) + let fd = fs.openSync(path, 0o102, 0o666) var serviceId = 10 var args = new Array("allInfo") try { @@ -190,7 +190,7 @@ context.getFilesDir().then((data) => { console.info(error.code) console.info(error.message) } - fileio.closeSync(fd); + fs.closeSync(fd); }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index 1affde15177fd27edca009fe043bd7a9bc118332..9db916a4563da925a2ad831e1efb1025a6cefd54 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,6 +1,6 @@ # AbilityResult -定义Ability被拉起并退出后返回的结果码和数据,可以通过[startAbilityForResult](js-apis-ability-context.md#abilitycontextstartabilityforresult)获取被拉起Ability退出后返回的AbilityResult对象,被startAbilityForResult拉起的Ability对象可以通过[terminateSelfWithResult](js-apis-ability-context.md#abilitycontextterminateselfwithresult)返回AbilityResult对象。 +定义Ability被拉起并退出后返回的结果码和数据,可以通过[startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7)获取被拉起Ability退出后返回的AbilityResult对象,被startAbilityForResult拉起的Ability对象可以通过[terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7)返回AbilityResult对象。 > **说明:** > 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 f1e4e395e42bbc0028263ed54067757e07961c91..2f2babef92ca9837fc86209b2fc0eddea5d8d275 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 @@ -859,8 +859,8 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | method | string | 是 | 指示被调用的方法名。 | | arg | string | 是 | 指示需传入的参数。 | -| extras | [PacMap](#pacmap) | 是 | 指示扩展的键值对参数。 | -| callback | AsyncCallback\<[PacMap](#pacmap)> | 是 | 指示数据操作的回调方法,返回操作结果。 | +| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | +| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | 是 | 指示数据操作的回调方法,返回操作结果。 | **示例:** @@ -895,13 +895,13 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\ | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | method | string | 是 | 指示被调用的方法名。 | | arg | string | 是 | 指示需传入的参数。 | -| extras | [PacMap](#pacmap) | 是 | 指示扩展的键值对参数。 | +| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | **返回值:** | 类型 | 说明 | |------ | ------- | -|Promise\<[PacMap](#pacmap)> | 返回操作结果。 | +|Promise\<[PacMap](js-apis-inner-application-pacMap.md)> | 返回操作结果。 | **示例:** @@ -991,14 +991,4 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi console.error('executeBatch failed, error: ${error}'); }); -``` - -## PacMap - -[key: string]: number | string | boolean | Array\ | null; - -**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel - -| 参数名 | 参数类型 | 必填 | 说明 | -| ------ | ------ | ------ | ------ | -| [key: string] | number \| string \| boolean \| Array\ \| null | Yes| 数据存储在键值对中。| \ No newline at end of file +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md index 195a244212a7519294558ab9c7ab1821ec9e81c5..d89ffb47d8e21db0c8ef7ba29933a9e39cc2c505 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -15,10 +15,10 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 | abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | | uri | string | 否 | 表示Uri。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | | type | string | 否 | 表示MIME type类型,打开文件的类型,主要用于文管打开文件。比如:'text/xml' 、 'image/*'等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | -| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantConstant.Flags)。 | -| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md)。 | -| parameters | {[key: string]: Object} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | -| entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity)。 | +| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-ability-wantConstant.md#wantconstantflags)。 | +| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-ability-wantConstant.md#wantconstantaction)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](../../application-models/explicit-implicit-want-mappings.md)。 | +| parameters | {[key: string]: Object} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | +| entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantconstantentity)。 | | moduleName9+ | string | 否 | 表示待启动的Ability所属的模块(module)。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 820115f2635703da5b71e40a5d1e4c572c473393..38cf79906cf55377de45f345b94c32b70a76fb1a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -30,6 +30,14 @@ addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void | monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | 是 | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor)实例 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | AddAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -70,6 +78,14 @@ addAbilityMonitor(monitor: AbilityMonitor): Promise\; | -------------- | ------------------- | | Promise\ | 以Promise形式返回。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | AddAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -105,6 +121,14 @@ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): v | monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | 是 | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor)实例 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | RemoveAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -145,6 +169,14 @@ removeAbilityMonitor(monitor: AbilityMonitor): Promise\; | -------------- | ------------------- | | Promise\ | 以Promise形式返回。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | RemoveAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + - 示例 ```ts @@ -180,6 +212,14 @@ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\) | monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | 是 | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor)实例 | | callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | WaitAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -220,6 +260,14 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCall | timeout | number | 否 | 最大等待时间,单位毫秒(ms) | | callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | WaitAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -268,6 +316,14 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\ | 以Promise形式返回Ability。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | WaitAbilityMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -360,6 +416,14 @@ getCurrentTopAbility(callback: AsyncCallback\): void; | -------- | ------------------------------------------------------------ | ---- | ------------------ | | callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | GetCurrentTopAbility failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -387,6 +451,14 @@ getCurrentTopAbility(): Promise\; | ----------------------------------------------------------- | -------------------------------------- | | Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | 以Promise形式返回当前应用顶部ability。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | GetCurrentTopAbility failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -415,6 +487,26 @@ startAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-want.md) | 是 | 启动Ability参数 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -450,6 +542,26 @@ startAbility(want: Want): Promise\; | -------------- | ------------------- | | Promise\ | 以Promise形式返回。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -480,6 +592,14 @@ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void; | ability | UIAbility | 是 | 指定Ability对象 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法
\- true:成功
\- false:失败 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | DoAbilityForeground failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -516,6 +636,14 @@ doAbilityForeground(ability: UIAbility): Promise\; | ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回执行结果。
\- true:成功
\- false:失败 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | DoAbilityForeground failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -547,6 +675,14 @@ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void; | ability | UIAbility | 是 | 指定Ability对象 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法
\- true:成功
\- false:失败 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | DoAbilityBackground failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -583,6 +719,14 @@ doAbilityBackground(ability: UIAbility): Promise\; | ----------------- | ------------------------------------------------------------ | | Promise\ | 以Promise形式返回执行结果。
\- true:成功
\- false:失败 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | DoAbilityBackground failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -788,6 +932,14 @@ finishTest(msg: string, code: number, callback: AsyncCallback\): void; | code | number | 是 | 日志码 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | FinishTest failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -821,6 +973,14 @@ finishTest(msg: string, code: number): Promise\; | -------------- | ------------------- | | Promise\ | 以Promise形式返回。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | FinishTest failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -848,6 +1008,14 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | AddAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -884,6 +1052,14 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; | -------------- | ------------------- | | Promise\ | 以Promise形式返回。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | AddAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -915,6 +1091,14 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ | monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | 是 | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) 实例 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | RemoveAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -951,6 +1135,14 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; | -------------- | ------------------- | | Promise\ | 以Promise形式返回。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | RemoveAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -982,6 +1174,14 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ | 是 | 成功返回AbilityStage对象,失败返回空。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | WaitAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1023,6 +1223,14 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise | -------------- | ------------------- | | Promise\ | 成功返回AbilityStage对象,失败返回空。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | WaitAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1059,6 +1267,14 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: | timeout | number | 否 | 超时最大等待时间,以毫秒为单位。 | | callback | AsyncCallback\ | 是 | 成功返回AbilityStage对象,失败返回空。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000100 | WaitAbilityStageMonitor failed. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-appStateData.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-appStateData.md index a4cc1898ff2001de1b7147012cf6ef37eff5afa5..00a9014cc34cf89dbec26bec6f1c6d6dc8c744d2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-appStateData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-appStateData.md @@ -20,7 +20,7 @@ import appManager from '@ohos.app.ability.appManager'; function getForegroundAppInfos() { appManager.getForegroundApplications((error, data) => { if (error) { - console.log('getForegroundApplications failed, error.code: ${error.code}, error.message: ${error.message}'); + console.log('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } for (let i = 0; i < data.length; i++) { 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 3d448221a104a1f763276380995ab36911123888..44e683a0961defa502ef29e61f2d5914b1420096 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 @@ -291,6 +291,15 @@ getRunningProcessInformation(): Promise\>; | -------- | -------- | | Promise\> | 以Promise方式返回接口运行结果及有关运行进程的信息,可进行错误处理或其他自定义处理。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -320,6 +329,15 @@ getRunningProcessInformation(callback: AsyncCallback\ | -------- | -------- | |AsyncCallback\> | 以回调方式返回接口运行结果及有关运行进程的信息,可进行错误处理或其他自定义处理。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -347,6 +365,14 @@ killAllProcesses(): Promise\; | -------- | -------- | | Promise\ | 以Promise方式返回杀死应用所在的进程结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000011 | The context does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -368,6 +394,14 @@ killAllProcesses(callback: AsyncCallback\); | -------- | -------- | |AsyncCallback\ | 以callback方式返回杀死应用所在的进程结果。 | +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000011 | The context does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts 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 618cae585d94f5d1bbfbfd1204672925147bd38d..8fe7e62465b288d5468dee12bb58174c4d62eec6 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 @@ -20,7 +20,7 @@ Context模块提供了ability或application的上下文的能力,包括访问 | filesDir | string | 是 | 否 | 文件目录。 | | databaseDir | string | 是 | 否 | 数据库目录。 | | preferencesDir | string | 是 | 否 | preferences目录。 | -| bundleCodeDir | string | 是 | 否 | 安装包目录。 | +| bundleCodeDir | string | 是 | 否 | 安装包目录。不能拼接路径访问资源文件,请使用[资源管理接口](js-apis-resource-manager.md)访问资源。 | | distributedFilesDir | string | 是 | 否 | 分布式文件目录。 | | eventHub | [EventHub](js-apis-inner-application-eventHub.md) | 是 | 否 | 事件中心,提供订阅、取消订阅、触发事件对象。 | | area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | 是 | 否 | 文件分区信息。 | @@ -47,14 +47,6 @@ createBundleContext(bundleName: string): Context; | -------- | -------- | | Context | 安装包的上下文。 | -**错误码:** - -| 错误码ID | 错误信息 | -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 - **示例:** ```ts @@ -86,14 +78,6 @@ createModuleContext(moduleName: string): Context; | -------- | -------- | | Context | 模块的上下文。 | -**错误码:** - -| 错误码ID | 错误信息 | -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 - **示例:** ```ts @@ -126,14 +110,6 @@ createModuleContext(bundleName: string, moduleName: string): Context; | -------- | -------- | | Context | 模块的上下文。 | -**错误码:** - -| 错误码ID | 错误信息 | -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 - **示例:** ```ts 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 e37ca75c65b62e4b0a086461dad437589c0a1c9b..97efeab178d0ba376d2c47bbc39c77380c27aa54 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 @@ -33,7 +33,7 @@ let upperLimit = 1; function getExtensionInfos() { abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { if (error) { - console.error('getForegroundApplications failed, error.code: ${error.code}, error.message: ${error.message}'); + console.error('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index 15734b7eb09bd941548b4ec9f1cfd6a63fe4697d..4a8293605d88b32b8569a8afca06b4fb01b34113 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -41,6 +41,18 @@ startAbility(want: Want, callback: AsyncCallback<void>): void **系统能力**:SystemCapability.Ability.Form +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16500101 | The application is not a system application. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -65,7 +77,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { 'message': message } }; - this.context.startAbility(want, (error, data) => { + this.context.startAbility(want, (error) => { if (error) { console.error('FormExtensionContext startAbility, error:${JSON.stringify(error)}'); } else { @@ -98,6 +110,18 @@ startAbility(want: Want): Promise<void> | ------------ | ---------------------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 202 | The application is not a system application. | +| 401 | If the input parameter is not valid parameter. | +| 16500050 | An IPC connection error happened. | +| 16500100 | Failed to obtain the configuration information. | +| 16500101 | The application is not a system application. | +| 16501000 | An internal functional error occurred. | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| + **示例:** ```ts 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 e5654595bc7b1c2aa4b1770725d816d847665ea7..4fb11aecd33bc78210e3e8c07a47ddd8e836159d 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 @@ -27,7 +27,7 @@ try { missionManager.getMissionInfos('', 10, (error, missions) => { if (error) { - console.error('getMissionInfos failed, error.code: ${error.code}, error.message: ${error.message}'); + console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } console.log('size = ${missions.length}'); @@ -36,7 +36,7 @@ missionManager.getMissionSnapShot('', id, (err, snapshot) => { if (err) { - console.error('getMissionInfos failed, err.code: ${err.code}, err.message: ${err.message}'); + console.error('getMissionInfos failed, err.code: ${JSON.stringify(err.code)}, err.message: ${JSON.stringify(err.message)}'); return; } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-pacMap.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-pacMap.md new file mode 100644 index 0000000000000000000000000000000000000000..aa62c06d90ec15bf2b2850c1c565736d31b6a069 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-pacMap.md @@ -0,0 +1,9 @@ +## PacMap + +[key: string]: number | string | boolean | Array\ | null; + +**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel + +| 参数名 | 参数类型 | 必填 | 说明 | +| ------ | ------ | ------ | ------ | +| [key: string] | number \| string \| boolean \| Array\ \| null | Yes| 数据存储在键值对中。| \ No newline at end of file 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 38e5c8b92677af47b7493f8d841b425c75460387..70bf03ef4bfefc91a671814da61b308c289cbf25 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 @@ -46,26 +46,21 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -118,26 +113,21 @@ startAbility(want: Want, options?: StartOptions): Promise\; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -188,26 +178,21 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -264,27 +249,21 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -340,27 +319,21 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -425,27 +398,21 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -497,18 +464,16 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -561,18 +526,16 @@ startServiceExtensionAbility(want: Want): Promise\; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -623,19 +586,16 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -693,19 +653,16 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -754,15 +711,15 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -815,15 +772,15 @@ stopServiceExtensionAbility(want: Want): Promise\; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -874,16 +831,15 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -940,16 +896,15 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -997,12 +952,14 @@ terminateSelf(callback: AsyncCallback<void>): void; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -1038,12 +995,14 @@ terminateSelf(): Promise<void>; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** @@ -1084,14 +1043,13 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | | 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000011 | Context does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1145,15 +1103,13 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | | 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000011 | Context does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1202,13 +1158,11 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback< | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000003 | Input error. The specified id does not exist. | -| 16000011 | Context does not exist. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1259,13 +1213,11 @@ disconnectServiceExtensionAbility(connection: number): Promise<void>; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000003 | Input error. The specified id does not exist. | -| 16000011 | Context does not exist. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + **示例:** ```ts @@ -1322,16 +1274,17 @@ startAbilityByCall(want: Want): Promise<Caller>; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | | 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Incorrect ability type. | | 16000004 | Visibility verification failed. | | 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000006 | Cross-user operations are not allowed. | | 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000017 | The previous ability is starting, wait start later. | +| 16000011 | The context does not exist. | | 16000050 | Internal Error. | +| 16200001 | The caller has been released. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 **示例:** 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 014aef08334b4be383b7f56529ba5be43f2caa83..af98dbea4d4b39c5800d3f9ff5ee606929da3c71 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 @@ -54,12 +54,13 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -118,12 +119,13 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -191,12 +193,13 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -260,12 +263,13 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -328,12 +332,13 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -406,12 +411,13 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityRes | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -477,12 +483,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -549,12 +556,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -629,12 +637,13 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO | 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | -| 16000017 | The previous ability is starting, wait start later. | | 16000050 | Internal error. | | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -693,6 +702,8 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -747,6 +758,8 @@ startServiceExtensionAbility(want: Want): Promise\; | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -805,6 +818,8 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -863,6 +878,8 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -917,6 +934,8 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -970,6 +989,8 @@ stopServiceExtensionAbility(want: Want): Promise\; | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1027,6 +1048,8 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1084,6 +1107,8 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | 16000050 | Internal error. | | 16200001 | The caller has been released. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1135,6 +1160,8 @@ terminateSelf(callback: AsyncCallback<void>): void; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1180,6 +1207,8 @@ terminateSelf(): Promise<void>; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1226,6 +1255,8 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1288,6 +1319,8 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1348,6 +1381,8 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1414,6 +1449,8 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1469,11 +1506,11 @@ disconnectServiceExtensionAbility(connection: number): Promise\; | 错误码ID | 错误信息 | | ------- | -------------------------------- | -| 16000001 | The specified ability does not exist. | -| 16000005 | The specified process does not have the permission. | | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -1517,11 +1554,11 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -2010,6 +2060,8 @@ setMissionIcon(icon: image.PixelMap): Promise\; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -2057,6 +2109,8 @@ restoreWindowStage(localStorage: LocalStorage) : void; | 16000011 | The context does not exist. | | 16000050 | Internal error. | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -2083,7 +2137,8 @@ isTerminating(): boolean; | 错误码ID | 错误信息 | | ------- | -------------------------------- | | 16000011 | The context does not exist. | -| 16000050 | Internal error. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** @@ -2112,6 +2167,26 @@ requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestR | want |[Want](js-apis-application-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 | | result | AsyncCallback<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | 是 | 执行结果回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts @@ -2165,6 +2240,26 @@ requestDialogService(want: Want): Promise<dialogRequest.RequestResult>; | -------- | -------- | | Promise<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Promise形式返回执行结果。 +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) + **示例:** ```ts 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 2aeb4f86a6a39b1daa8fa1f58d9b70ada4912bac..b4a9b9f9d610dbd34fa8920cd419a56d6380d228 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -56,15 +56,15 @@ import inputMethodEngine from '@ohos.inputMethodEngine'; getInputMethodAbility(): InputMethodAbility -获取服务端实例。 +为输入法应用获取输入法应用客户端实例[InputMethodAbility](#inputmethodability)。输入法应用获取该实例可订阅软键盘显示/隐藏请求事件、创建/销毁输入法应用面板等。 **系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** -| 类型 | 说明 | -| --------------------------------------- | ------------ | -| [InputMethodAbility](#inputmethodability) | 服务端实例。 | +| 类型 | 说明 | +| ----------------------------------------- | ------------------ | +| [InputMethodAbility](#inputmethodability) | 输入法应用客户端。 | **示例:** @@ -76,15 +76,15 @@ let InputMethodAbility = inputMethodEngine.getInputMethodAbility(); getKeyboardDelegate(): KeyboardDelegate -获取客户端监听实例。 +为输入法应用获取客户端编辑事件监听代理实例[KeyboardDelegate](#keyboarddelegate)。输入法应用获取该实例可订阅物理键盘按键事件、选中文本变化事件等。 **系统能力:** SystemCapability.MiscServices.InputMethodFramework **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ---------------- | -| [KeyboardDelegate](#keyboarddelegate) | 客户端监听实例。 | +| 类型 | 说明 | +| ------------------------------------- | ------------------------ | +| [KeyboardDelegate](#keyboarddelegate) | 客户端编辑事件监听代理。 | **示例:** @@ -96,7 +96,7 @@ let KeyboardDelegate = inputMethodEngine.getKeyboardDelegate(); getInputMethodEngine(): InputMethodEngine -获取服务端实例。 +为输入法应用获取输入法应用客户端实例[InputMethodEngine](#inputmethodengine-1)。输入法应用获取该实例可订阅软键盘显示/隐藏请求事件等。 > **说明:** > @@ -106,9 +106,9 @@ getInputMethodEngine(): InputMethodEngine **返回值:** -| 类型 | 说明 | -| --------------------------------------- | ------------ | -| [InputMethodEngine](#inputmethodengine-1) | 服务端实例。 | +| 类型 | 说明 | +| ----------------------------------------- | ------------------ | +| [InputMethodEngine](#inputmethodengine-1) | 输入法应用客户端。 | **示例:** @@ -120,7 +120,7 @@ let InputMethodEngine = inputMethodEngine.getInputMethodEngine(); createKeyboardDelegate(): KeyboardDelegate -获取客户端监听实例。 +为输入法应用获取客户端编辑事件监听代理实例[KeyboardDelegate](#keyboarddelegate)。输入法应用获取该实例可订阅物理键盘按键事件、选中文本变化事件等。 > **说明:** > @@ -130,9 +130,9 @@ createKeyboardDelegate(): KeyboardDelegate **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ---------------- | -| [KeyboardDelegate](#keyboarddelegate) | 客户端监听实例。 | +| 类型 | 说明 | +| ------------------------------------- | ------------------------ | +| [KeyboardDelegate](#keyboarddelegate) | 客户端编辑事件监听代理。 | **示例:** @@ -478,6 +478,186 @@ inputMethodEngine.getInputMethodAbility().off('setSubtype', () => { }); ``` +### createPanel10+ + +createPanel(ctx: BaseContext, info: PanelInfo, callback: AsyncCallback\): void + +创建输入法应用面板。仅支持输入法应用或者具有system_core权限的系统应用调用。单个输入法应用仅仅允许创建一个SOFT_KEYBOARD及一个STATUS_BAR类型的面板。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------- | ---- | ------------------------ | +| ctx | [BaseContext](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md) | 是 | 当前输入法应用上下文信息。 | +| info | [PanelInfo](#panelinfo10) | 是 | 输入法面板信息。 | +| callback | AsyncCallback\<[Panel](#panel10)> | 是 | 回调函数。当输入法面板创建成功,返回当前创建的输入法面板对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ---------- | ----------------------------- | +| 12800004 | not an input method extension | + +**示例:** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +try { + inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo, (err, panel) => { + if (err !== undefined) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); + return; + } + console.log('Succeed in creating panel.'); + }) +} catch(err) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +} +``` + +### createPanel10+ + +createPanel(ctx: BaseContext, info: PanelInfo): Promise\ + +创建输入法应用面板。仅支持输入法应用或者具有system_core权限的系统应用调用。单个输入法应用仅仅允许创建一个SOFT_KEYBOARD及一个STATUS_BAR类型的面板。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------- | ---- | ------------------------ | +| ctx | [BaseContext](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-inner-application-baseContext.md) | 是 | 当前输入法应用上下文信息。 | +| info | [PanelInfo](#panelinfo10) | 是 | 输入法面板信息。 | + +**返回值:** +| 类型 | 说明 | +| ------- | ------------------------------------------------------------------ | +| Promise\<[Panel](#panel10)> | 回调函数。当输入法面板创建成功,返回当前创建的输入法面板对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ---------- | ----------------------------- | +| 12800004 | not an input method extension | + +**示例:** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo).then((panel) => { + console.log('Succeed in creating panel.'); +}).catch((err) => { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +}) +``` + +### destroyPanel10+ + +destroyPanel(panel: Panel, callback: AsyncCallback\): void; + +销毁输入法应用面板。使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------- | ---- | ------------------------ | +| panel | [Panel](#panel10) | 是 | 要销毁的panel对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当输入法面板销毁成功,err为undefined,否则为错误对象。 | + +**示例:** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +try { + inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo, (err, panel) => { + if (err !== undefined) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); + return; + } + globalThis.inputMethodPanel = panel; + console.log('Succeed in creating panel.'); + }) +} catch(err) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +} + +try { + inputMethodEngine.getInputMethodAbility().destroyPanel(globalThis.inputMethodPanel, (err) => { + if(err !== undefined) { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); + return; + } + console.log('Succeed in destroying panel.'); + }) +} catch(err) { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); +} +``` + +### destroyPanel10+ + +destroyPanel(panel: Panel): Promise\; + +销毁输入法应用面板。使用promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------| ----------- | ---- | ------------------------ | +| panel | [Panel](#panel10) | 是 | 要销毁的panel对象。 | + +**返回值:** +| 类型 | 说明 | +| ------- | -------------------------------------------------------------------- | +| Promise\ | 无返回结果的Promise对象。| + +**示例:** + +```js +let panelInfo: inputMethodEngine.PanelInfo = { + panelType: SOFT_KEYBOARD, + panelFlag: FLG_FIXED +} +try { + inputMethodEngine.getInputMethodAbility().createPanel(this.context, panelInfo, (err, panel) => { + if (err !== undefined) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); + return; + } + globalThis.inputMethodPanel = panel; + console.log('Succeed in creating panel.'); + }) +} catch(err) { + console.log('Failed to create panel, err: ' + JSON.stringify(err)); +} + +try { + inputMethodEngine.getInputMethodAbility().destroyPanel(globalThis.inputMethodPanel).then(() => { + console.log('Succeed in destroying panel.'); + }).catch((err) => { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); + }); +} catch (err) { + console.log('Failed to destroy panel, err: ' + JSON.stringify(err)); +} +``` + ## KeyboardDelegate 下列API示例中都需使用[getKeyboardDelegate](#inputmethodenginegetkeyboarddelegate9)回调获取到KeyboardDelegate实例,再通过此实例调用对应方法。 @@ -684,6 +864,455 @@ inputMethodEngine.getKeyboardDelegate().off('textChange', (text) => { }); ``` +## Panel10+ + +下列API示例中都需使用[createPanel](#createpanel10)回调获取到Panel实例,再通过此实例调用对应方法。 + +### setUiContent10+ + +setUiContent(path: string, callback: AsyncCallback\): void + +为当前面板加载具体页面内容,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| path | string | 是 | 设置加载页面的路径。 | +| callback | AsyncCallback\ | 是 | 回调函数。当面板页面内容加载成功,err为undefined,否则err为错误对象。 | + +**示例:** + +```js +try { + panel.setUiContent('pages/page2/page2', (err) => { + if (err) { + console.error('Failed to set the content. err:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the content.'); + }); +} catch (exception) { + console.error('Failed to set the content. err:' + JSON.stringify(exception)); +} +``` + +### setUiContent10+ + +setUiContent(path: string): Promise\ + +为当前面板加载具体页面内容,使用Promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| path | string | 是 | 设置加载页面的路径。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------ | +| Promise\ | 无返回结果的Promise对象。 | + +**示例:** + +```js +try { + let promise = panel.setUiContent('pages/page2/page2'); + promise.then(() => { + console.info('Succeeded in setting the content.'); + }).catch((err) =>{ + console.error('Failed to set the content. err: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the content. err: ' + JSON.stringify(exception)); +} +``` + +### setUiContent10+ + +setUiContent(path: string, storage: LocalStorage, callback: AsyncCallback\): void + +为当前面板加载与LocalStorage相关联的具体页面内容,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| path | string | 是 | 设置加载页面的路径。 | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。| +| callback | AsyncCallback\ | 是 | 回调函数。当面板页面内容加载成功,err为undefined,否则err为错误对象。 | + +**示例:** + +```js +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +try { + panel.setUiContent('pages/page2/page2', storage, (err) => { + if (err) { + console.error('Failed to set the content. err:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the content.'); + }); +} catch (exception) { + console.error('Failed to set the content. err:' + JSON.stringify(exception)); +} +``` + +### setUiContent10+ + +setUiContent(path: string, storage: LocalStorage): Promise\ + +为当前面板加载与LocalStorage相关联的具体页面内容,使用Promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| path | string | 是 | 设置加载页面的路径。 | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。| + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------ | +| Promise\ | 无返回结果的Promise对象。 | + +**示例:** + +```js +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +try { + let promise = panel.setUiContent('pages/page2/page2'); + promise.then(() => { + console.info('Succeeded in setting the content.'); + }).catch((err) =>{ + console.error('Failed to set the content. err: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the content. err: ' + JSON.stringify(exception)); +} +``` + +### resize10+ + +resize(width: number, height: number, callback: AsyncCallback\): void + +改变当前面板大小,使用callback异步回调。 +面板存在大小限制,面板宽度不超出屏幕宽度,面板高度不高于屏幕高度的二分之一。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| width | number | 是 | 目标面板的宽度,单位为px。| +| height | number | 是 | 目标面板的高度,单位为px。| +| callback | AsyncCallback\ | 是 | 回调函数。当面板大小改变成功,err为undefined,否则err为错误对象。 | + +**示例:** + +```js +try { + panel.resize(500, 1000, (err) => { + if (err) { + console.error('Failed to change the panel size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the panel size.'); + }); +} catch (exception) { + console.error('Failed to change the panel size. Cause:' + JSON.stringify(exception)); +} +``` + +### resize10+ + +resize(width: number, height: number): Promise\; + +改变当前面板大小,使用Promise异步回调。 +面板存在大小限制,面板宽度不超出屏幕宽度,面板高度不高于屏幕高度的二分之一。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| width | number | 是 | 目标面板的宽度,单位为px。| +| height | number | 是 | 目标面板的高度,单位为px。| + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------ | +| Promise | 无返回结果的Promise对象。 | + +**示例:** + +```js +try { + let promise = panel.resize(500, 1000); + promise.then(() => { + console.info('Succeeded in changing the panel size.'); + }).catch((err) =>{ + console.error('Failed to change the panel size. err: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to change the panel size. err: ' + JSON.stringify(exception)); +} +``` + +### moveTo10+ + +moveTo(x: number, y: number, callback: AsyncCallback\): void + +移动面板位置,使用callback异步回调。 +对FLG_FIXED状态的panel不产生实际移动效果。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| x | number | 是 | 面板在x轴方向移动的值,值为正表示右移,单位为px。| +| y | number | 是 | 面板在y轴方向移动的值,值为正表示下移,单位为px。| +| callback | AsyncCallback\ | 是 | 回调函数。当面板位置移动成功,err为undefined,否则err为错误对象。 | + +**示例:** + +```js +try { + panel.moveTo(300, 300, (err) =>{ + if (err) { + console.error('Failed to move the panel. err:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the panel.'); + }); +} catch (exception) { + console.error('Failed to move the panel. err:' + JSON.stringify(exception)); +} +``` + +### moveTo10+ + +moveTo(x: number, y: number): Promise\ + +移动面板位置,使用callback异步回调。 +对FLG_FIXED状态的panel不产生实际移动效果。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| x | number | 是 | 面板在x轴方向移动的值,值为正表示右移,单位为px。| +| y | number | 是 | 面板在y轴方向移动的值,值为正表示下移,单位为px。| + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------ | +| Promise | 无返回结果的Promise对象。 | + +**示例:** + +```js +try { + let promise = windowClass.moveTo(300, 300); + promise.then(() => { + console.info('Succeeded in moving the panel.'); + }).catch((err) =>{ + console.error('Failed to move the panel. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to move the panel. Cause:' + JSON.stringify(exception)); +} +``` + +### show10+ + +show(callback: AsyncCallback\): void + +显示当前面板,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback\ | 是 | 回调函数。当面板显示成功,err为undefined,否则err为错误对象。 | + +**示例:** + +```js +panel.show((err) => { + if (err) { + console.error('Failed to show the panel. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the panel.'); +}); +``` + +### show10+ + +show(): Promise\ + +显示当前面板,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------ | +| Promise\ | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promise = panel.show(); +promise.then(() => { + console.info('Succeeded in showing the panel.'); +}).catch((err) =>{ + console.error('Failed to show the panel. err: ' + JSON.stringify(err)); +}); +``` + +### hide10+ + +hide(callback: AsyncCallback\): void + +隐藏当前面板,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback\ | 是 | 回调函数。当面板隐藏成功,err为undefined,否则err为错误对象。 | + +**示例:** + +```js +panel.hide((err) => { + if (err) { + console.error('Failed to hide the panel. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hiding the panel.'); +}); +``` + +### hide10+ + +hide(): Promise\ + +隐藏当前面板,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------ | +| Promise\ | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promise = panel.hide(); +promise.then(() => { + console.info('Succeeded in hiding the panel.'); +}).catch((err) =>{ + console.error('Failed to hide the panel. err: ' + JSON.stringify(err)); +}); +``` + +### on10+ + +on(type: 'show' | 'hide', callback: () => void): void + +监听当前面板状态,可监听面板类型为show或者hide, 使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| type | 'show'\|'hide' | 是 | 监听当前面板的状态类型,show表示显示状态,hide表示隐藏状态 | +| callback | () => void | 是 | 回调函数。 | + +**示例:** + +```js +panel.on('show', () => { + console.info('Panel is showing.'); +}); +``` + +### off10+ + +off(type: 'show' | 'hide', callback?: () => void): void + +取消监听当前面板状态,可取消监听的面板类型为show或者hide,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| type | 'show'/'hide' | 是 | 要取消监听的当前面板状态类型,show表示显示状态,hide表示隐藏状态 | +| callback | () => void | 否 | 回调函数。 | + +**示例:** + +```js +panel.off('show'); +``` + +### changeFlag10+ + +changeFlag(flag: PanelFlag): void + +改变面板状态为固定态或者悬浮态。仅对SOFT_KEYBOARD类型生效。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | -------- | +| flag | [PanelFlag](#panelflag10) | 是 | 要切换到的面板状态类型。 | + +**示例:** + +```js +let panelFlag = inputMethodEngine.getInputMethodAbility().PanelFlag.FLG_FIXED; +panel.changeFlag(panelFlag); +``` + ## KeyboardController 下列API示例中都需使用[on('inputStart')](#oninputstart9)回调获取到KeyboardController实例,再通过此实例调用对应方法。 @@ -1752,6 +2381,39 @@ inputClient.getTextIndexAtCursor().then((index) => { | keyCode | number | 是 | 否 | 按键的键值。 | | keyAction | number | 是 | 否 | 按键的状态。 | +## PanelFlag10+ + +输入法面板状态类型枚举。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 值 | 说明 | +| ------------ | -- | ------------------ | +| FLG_FIXED | 0 | 固定态面板类型。 | +| FLG_FLOATING | 1 | 悬浮态面板类型。 | + +## PanelType10+ + +输入法面板类型枚举。 + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +| 名称 | 值 | 说明 | +| ------------ | -- | ------------------ | +| SOFT_KEYBOARD | 0 | 软键盘类型。 | +| STATUS_BAR | 1 | 状态栏类型。 | + +## PanelInfo10+ + +**系统能力:** SystemCapability.MiscServices.InputMethodFramework + +输入法面板属性。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | -------- | ---- | ---- | ------------ | +| type | number | 是 | 是 | 面板的类型。 | +| flag | number | 是 | 是 | 面板的状态类型。 | + ## TextInputClient(deprecated) > **说明:** @@ -2250,3 +2912,4 @@ textInputClient.getEditorAttribute().then((editorAttribute) => { console.error('Failed to getEditorAttribute: ' + JSON.stringify(err)); }); ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-installer.md b/zh-cn/application-dev/reference/apis/js-apis-installer.md index 8c1b00eba5496302c74536da3d28c0ebb4bada7b..079649bbbdb3af1851fdac372fb1ce1a71ea9412 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-installer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-installer.md @@ -149,6 +149,64 @@ try { console.error('getBundleInstaller failed. Cause: ' + error.message); } ``` +## BundleInstaller.install +install(hapFilePaths: Array<string>, callback: AsyncCallback<void>): void; + +以异步方法安装应用,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| hapFilePaths | Array<string> | 是 | 存储应用程序包的路径。路径应该是当前应用程序中存放HAP的数据目录。当传入的路径是一个目录时, 该目录下只能放同一个应用的HAP,且这些HAP的签名需要保持一致。 | +| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700010 | Failed to install the HAP because the HAP fails to be parsed. | +| 17700011 | Failed to install the HAP because the HAP signature fails to be verified. | +| 17700012 | Failed to install the HAP because the HAP path is invalid or the HAP is too large. | +| 17700015 | Failed to install the HAPs because they have different configuration information. | +| 17700016 | Failed to install the HAP because of insufficient system disk space. | +| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. | +| 17700018 | Failed to install because the dependent module does not exist. | +| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. | +| 17700036 | Failed to install the HSP because lacks appropriate permissions. | +| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | +| 17700041 | Failed to install because enterprise device management disallow install. | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; + +try { + installer.getBundleInstaller().then(data => { + data.install(hapFilePaths, err => { + if (err) { + console.error('install failed:' + err.message); + } else { + console.info('install successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` ## BundleInstaller.install @@ -209,9 +267,9 @@ try { installer.getBundleInstaller().then(data => { data.install(hapFilePaths, installParam) .then((data) => { - console.info('install success: ' + JSON.stringify(data)); + console.info('install successfully: ' + JSON.stringify(data)); }).catch((error) => { - console.error('install failed:' + err.message); + console.error('install failed:' + error.message); }); }).catch(error => { console.error('getBundleInstaller failed. Cause: ' + error.message); @@ -247,7 +305,8 @@ uninstall(bundleName: string, installParam: InstallParam, callback: AsyncCallbac | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | -| 17700004 | The specified user ID is not found. | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | @@ -279,11 +338,11 @@ try { } ``` -## BundleInstaller.uninstall10+ +## BundleInstaller.uninstall -uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : void ; +uninstall(bundleName: string, callback: AsyncCallback<void>): void; -以异步方法卸载一个共享包,使用callback形式返回结果。 +以异步方法卸载应用,使用callback形式返回结果。 **系统接口:** 此接口为系统接口。 @@ -293,10 +352,10 @@ uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : voi **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ----------------------------------- | ---- | -------------------------------------------------------- | -| uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | -| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | 是 | 待卸载应用的包名。 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | **错误码:** @@ -304,21 +363,19 @@ uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : voi | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundle name is not found. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | -| 17700037 | The version of shared bundle is dependent on other applications. | -| 17700038 | The specified shared bundle does not exist. | +| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | **示例:** ```ts import installer from '@ohos.bundle.installer'; -let uninstallParam = { - bundleName : "com.ohos.demo", -}; +let bundleName = 'com.ohos.demo'; try { installer.getBundleInstaller().then(data => { - data.uninstall(uninstallParam, err => { + data.uninstall(bundleName, err => { if (err) { console.error('uninstall failed:' + err.message); } else { @@ -332,12 +389,11 @@ try { console.error('getBundleInstaller failed. Cause: ' + error.message); } ``` +## BundleInstaller.uninstall -## BundleInstaller.uninstall10+ - -uninstall(uninstallParam: UninstallParam) : Promise\; +uninstall(bundleName: string, installParam?: InstallParam) : Promise\; -以异步方法卸载一个共享包,使用Promise形式返回结果。 +以异步方法卸载应用,使用Promise形式返回结果。 **系统接口:** 此接口为系统接口。 @@ -347,14 +403,15 @@ uninstall(uninstallParam: UninstallParam) : Promise\; **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ----------------------------------- | ---- | ---------------------------- | -| uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 待卸载应用的包名。 | +| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数。 | **返回值:** -| 类型 | 说明 | -| ------------- | -------------------------------------- | +| 类型 | 说明 | +| --------------- | -------------------------------------- | | Promise\ | Promise对象。无返回结果的Promise对象。 | **错误码:** @@ -363,26 +420,28 @@ uninstall(uninstallParam: UninstallParam) : Promise\; | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified userId is not existed. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | -| 17700037 | The version of shared bundle is dependent on other applications. | -| 17700038 | The specified shared bundle does not exist. | +| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | **示例:** - ```ts import installer from '@ohos.bundle.installer'; -let uninstallParam = { - bundleName : "com.ohos.demo", +let bundleName = 'com.ohos.demo'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, }; try { installer.getBundleInstaller().then(data => { - data.uninstall(uninstallParam, err => { - if (err) { - console.error('uninstall failed:' + err.message); - } else { - console.info('uninstall successfully.'); - } + data.uninstall(bundleName, installParam) + .then((data) => { + console.info('uninstall successfully: ' + JSON.stringify(data)); + }).catch((error) => { + console.error('uninstall failed:' + error.message); }); }).catch(error => { console.error('getBundleInstaller failed. Cause: ' + error.message); @@ -396,7 +455,7 @@ try { recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback<void>): void; -以异步方法回滚应用,使用callback形式返回结果。 +以异步方法回滚应用到初次安装时的状态,使用callback形式返回结果。 **系统接口:** 此接口为系统接口。 @@ -418,6 +477,7 @@ recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback& | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 17700001 | The specified bundle name is not found. | | 17700004 | The specified user ID is not found. | **示例:** @@ -448,6 +508,229 @@ try { } ``` + +## BundleInstaller.recover + +recover(bundleName: string, callback: AsyncCallback<void>): void; + +以异步方法回滚应用到初次安装时的状态,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | 是 | 待恢复应用的包名。 | +| callback | AsyncCallback<void> | 是 | 回调函数,回滚应用成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 17700001 | The specified bundle name is not found. | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let bundleName = 'com.ohos.demo'; + +try { + installer.getBundleInstaller().then(data => { + data.recover(bundleName, err => { + if (err) { + console.error('recover failed:' + err.message); + } else { + console.info('recover successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.recover + +recover(bundleName: string, installParam?: InstallParam) : Promise\; + +以异步方法回滚应用到初次安装时的状态,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 待卸载应用的包名。 | +| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数。 | + +**返回值:** + +| 类型 | 说明 | +| --------------- | -------------------------------------- | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user ID is not found. | + +**示例:** +```ts +import installer from '@ohos.bundle.installer'; +let bundleName = 'com.ohos.demo'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +try { + installer.getBundleInstaller().then(data => { + data.recover(bundleName, installParam) + .then((data) => { + console.info('recover successfully: ' + JSON.stringify(data)); + }).catch((error) => { + console.error('recover failed:' + error.message); + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.uninstall10+ + +uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : void ; + +以异步方法卸载一个共享包,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | +| 17700037 | The version of shared bundle is dependent on other applications. | +| 17700038 | The specified shared bundle does not exist. | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let uninstallParam = { + bundleName : "com.ohos.demo", +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(uninstallParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.uninstall10+ + +uninstall(uninstallParam: UninstallParam) : Promise\; + +以异步方法卸载一个共享包,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| uninstallParam | [UninstallParam](#uninstallparam10) | 是 | 共享包卸载需指定的参数信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------- | -------------------------------------- | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------------------------ | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | +| 17700037 | The version of shared bundle is dependent on other applications. | +| 17700038 | The specified shared bundle does not exist. | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let uninstallParam = { + bundleName : "com.ohos.demo", +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(uninstallParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` ## HashParam 应用程序安装卸载哈希参数信息。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-logs.md b/zh-cn/application-dev/reference/apis/js-apis-logs.md index 40213556ac95c072d5b85679700734315d2e9470..31dd38d1423d394442eafa6978746e051941944a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-logs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-logs.md @@ -83,7 +83,7 @@ error(message: string): void | message | string | 是 | 表示要打印的文本信息。 | -## 示例 +**示例:** ``` export default { @@ -99,3 +99,260 @@ export default { 在DevEco Studio的底部,切换到“HiLog”窗口。选择当前的设备及进程,日志级别选择Info,搜索内容设置为“Hello World”。此时窗口仅显示符合条件的日志,效果如图所示: ![zh-cn_image_0000001200913929](figures/zh-cn_image_0000001200913929.png) + +## console.assert10+ + +assert(value?: Object, ...arguments: Object[]): void + +若value为假,打印后续内容。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| value | Object | 否 | 值 | +| arguments | Object | 否 | 错误消息打印。 | + +**示例:** +``` +console.assert(true, 'does nothing'); + +console.assert(false, 'console %s work', 'didn\'t'); +// Assertion console:ohos didn't work + +console.assert(); +// Assertion failed +``` +## console.count10+ + +count(label?: string): void + +维护一个内部计数器, 并输出调用label的console.count()次数。默认值为'default'。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| label | string | 否 | 计数器标签名。 | + +**示例:** +``` +console.count() +// default: 1 +console.count('default') +// default: 2 +console.count('abc') +// abc: 1 +console.count('xyz') +// xyz: 1 +console.count('abc') +abc: 2 +console.count() +// default: 3 +``` + +## console.countReset10+ + +countReset(label?: string): void + +清除label名的计数。默认值为'default'。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| label | string | 否 | 计数器标签名。 | + +**示例:** +``` +console.count('abc'); +// abc: 1 +console.countReset('abc'); +console.count('abc'); +// abc: 1 +``` + +## console.dir10+ + +dir(dir?: Object): void + +打印对象内容。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| dir | Object | 否 | 需要打印内容的对象。 | + +## console.dirxml10+ + +dirxml(...arguments: Object[]): void + +此方法调用 console.log() 将接收到的参数传给它。此方法不会产生任何 XML 格式。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| arguments | Object | 否 | 要打印的信息。 | + +## console.group10+ + +group(...arguments: Object[]): void + +将后续行的缩进增加 groupIndentation 长度的空格。 +如果提供需要打印的信息,首先先打印信息,没有额外的缩进。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| arguments | Object | 否 | 要打印的信息。 | +## console.groupCollapsed10+ + +groupCollapsed(...arguments: Object[]): void + +group的别名。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| arguments | Object | 否 | 要打印的信息。| + +## console.groupEnd10+ + +groupEnd(): void + +将后续行的缩进减少 groupIndentation 长度的空格。 + +**系统能力:** SystemCapability.Utils.Lang + +## console.table10+ + +table(tableData?: Object): void + +以表格形式打印数据。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| tableData | Object | 否 | 要打印为表格形式的对象。 | + +**示例:** +``` +console.table([1, 2, 3]); +// ┌─────────┬────────┐ +// │ (index) │ Values │ +// ├─────────┼────────┤ +// │ 0 │ 1 │ +// │ 1 │ 2 │ +// │ 2 │ 3 │ +// └─────────┴────────┘ + +console.table({ a: [1, 2, 3, 4, 5], b: 5, c: { e: 5 } }); + +// ┌─────────┬───┬───┬───┬───┬───┬───┬────────┐ +// │ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ e │ Values │ +// ├─────────┼───┼───┼───┼───┼───┼───┼────────┤ +// │ a │ 1 │ 2 │ 3 │ 4 │ 5 │ │ │ +// │ b │ │ │ │ │ │ │ 5 │ +// │ c │ │ │ │ │ │ 5 │ │ +// └─────────┴───┴───┴───┴───┴───┴───┴────────┘ +``` +## console.time10+ + +time(label?: string): void + +启动可用于计算操作持续时间的计时器。默认值为'default'。可使用console.timeEnd()关闭计时器并打印结果。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| label | string | 否 | 计时器标识。 | + +## console.timeEnd10+ + +timeEnd(label?: string): void + +停止之前通过调用 console.time() 启动的计时器并将结果打印。默认值为'default'。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| label | string | 否 | 计时器标识。 | + +**示例:** +``` +console.time('abc'); +console.timeEnd('abc'); +// abc: 225.438ms +``` + +## console.timeLog10+ + +timeLog(label?: string, ...arguments: Object[]): void + +对于先前通过调用 console.time() 启动的计时器,打印经过时间和其他 data 参数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| label | string | 否 | 计时器标识。 | +| arguments | Object | 否 | 需要打印的其他日志。 | + +**示例:** +``` +console.time('timer1'); +const value = aaa(); // 返回 17 +console.timeLog('timer1', value); +// timer1: 365.227ms 17 +console.timeEnd('timer1'); +// timer1: 513.22ms +``` + +## console.trace10+ + +trace(...arguments: Object[]): void + +打印当前堆栈。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------- | +| arguments | Object | 否 | 需要打印的其他日志。 | + +**示例:** +``` +console.trace(); +console.trace("Show the trace"); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-measure.md b/zh-cn/application-dev/reference/apis/js-apis-measure.md index 07c24796a1f6325ba3cce2ae41fafe22cc565341..9b6a74cd976bea0e277631025fe3c9f5c5c1322e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-measure.md +++ b/zh-cn/application-dev/reference/apis/js-apis-measure.md @@ -15,7 +15,7 @@ import measure from '@ohos.measure' ## measure.measureText -measureText(options: MeasureOptions): double +measureText(options: MeasureOptions): number 计算指定文本单行布局下的宽度。 @@ -31,7 +31,7 @@ measureText(options: MeasureOptions): double | 类型 | 说明 | | ------------ | --------- | -| double | 文本宽度。
**说明:** 单位px。 | +| number | 文本宽度。
**说明:** 单位px。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md b/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md index bb2de659db473c3e52555009445d620a87b2b012..5244b2c693a4c372a6cdf2e0e5a2272f9b36cd67 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md +++ b/zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @@ -26,7 +26,7 @@ matchMediaSync(condition: string): MediaQueryListener | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------------------------------------- | -| condition | string | 是 | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/ui-ts-layout-mediaquery.md#语法规则)。 | +| condition | string | 是 | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/arkts-layout-development-media-query.md#语法规则)。 | **返回值:** 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 a488330246c1304b205b44471a07066955849d0c..bd367fc4d2d43e7921032a97b36782870f460d86 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 @@ -1169,6 +1169,11 @@ connection.getAddressesByName(host).then(function (data) { 网络连接的句柄。 +> **说明:** +> 设备从无网络到有网络会触发netAvailable事件、netCapabilitiesChange事件和netConnectionPropertiesChange事件; +> 设备从有网络到无网络状态会触发netLost事件; +> 设备从WiFi到蜂窝会触发netLost事件(WiFi丢失)之后触发 netAvaliable事件(蜂窝可用); + ### register register(callback: AsyncCallback\): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md b/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md index 51337d1ff5a06d8747ab4661bc61aaad10319b21..4ddf1deca564c3302ab92a06c625e5332b50fea7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md +++ b/zh-cn/application-dev/reference/apis/js-apis-net-mdns.md @@ -23,7 +23,7 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: Async | 参数名 | 类型 | 必填 | 说明 | |-------------|----------------------------------|-----------|-------------------------------------------------| -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceInfo | [LocalServiceInfo](#localserviceinfo) | 是 | mDNS服务的信息。 | | callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | 是 | 回调函数。成功添加error为undefined,data为添加到本地的mdns服务信息。 | @@ -43,7 +43,13 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: Async **示例:** +FA模型示例: + ```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + let localServiceInfo = { serviceType: "_print._tcp", serviceName: "servicename", @@ -58,8 +64,39 @@ let localServiceInfo = { } mdns.addLocalService(context, localServiceInfo, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +Stage模型示例: + +```ts +// 获取context +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.addLocalService(context, localServiceInfo, function (error, data) { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -75,7 +112,7 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceInfo | [LocalServiceInfo](#localserviceinfo) | 是 | mDNS服务的信息。 | **返回值:** @@ -100,7 +137,13 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceInfo | [LocalServiceInfo](#localserviceinfo) | 是 | mDNS服务的信息。 | | callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | 是 | 回调函数。成功移除error为undefined,data为移除本地的mdns服务信息。 | @@ -151,7 +224,44 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: As **示例:** +FA模型示例: + ```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.removeLocalService(context, localServiceInfo, function (error, data) { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +Stage模型示例: + +```ts +// 获取context +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { serviceType: "_print._tcp", serviceName: "servicename", @@ -166,8 +276,8 @@ let localServiceInfo = { } mdns.removeLocalService(context, localServiceInfo, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -183,7 +293,7 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceInfo | [LocalServiceInfo](#localserviceinfo) | 是 | mDNS服务的信息。 | **返回值:** @@ -208,7 +318,13 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceType | string | 是 | 需要发现的mDNS服务类型。| **返回值:** @@ -248,11 +394,32 @@ createDiscoveryService(context: Context, serviceType: string): DiscoveryService | ----------------------------- |---------------------------------| | DiscoveryService | 基于指定serviceType和Context的发现服务对象。 | -**Example** +**示例** + +FA模型示例: ```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + let serviceType = "_print._tcp"; +let discoveryService = mdns.createDiscoveryService(context, serviceType); +``` + +Stage模型示例: +```ts +// 获取context +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + +let serviceType = "_print._tcp"; let discoveryService = mdns.createDiscoveryService(context, serviceType); ``` @@ -268,7 +435,7 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: A | 参数名 | 类型 | 必填 | 说明 | |-------------|----------------------------------|-----------|-------------------------------------------------------------| -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceInfo | [LocalServiceInfo](#localserviceinfo) | 是 | mDNS服务的信息。 | | callback | AsyncCallback\<[LocalServiceInfo](#localserviceinfo)> | 是 | 回调函数。成功移除error为undefined,data为解析的mdns服务信息。 | @@ -288,7 +455,44 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: A **示例:** +FA模型示例: + ```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let localServiceInfo = { + serviceType: "_print._tcp", + serviceName: "servicename", + port: 5555, + host: { + address: "10.14.**.***", + }, + serviceAttribute: [{ + key: "111", + value: [1] + }] +} + +mdns.resolveLocalService(context, localServiceInfo, function (error, data) { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +Stage模型示例: + +```ts +// 获取context +import UIAbility from '@ohos.app.ability.UIAbility'; +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + globalThis.context = this.context; + } +} +let context = globalThis.context; + let localServiceInfo = { serviceType: "_print._tcp", serviceName: "servicename", @@ -303,8 +507,8 @@ let localServiceInfo = { } mdns.resolveLocalService(context, localServiceInfo, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); }); ``` @@ -320,7 +524,7 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-app-ability-uiAbility.md)。 | | serviceInfo | [LocalServiceInfo](#localserviceinfo) | 是 | mDNS服务的信息。 | **返回值:** @@ -345,7 +549,13 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\): void +on(type: 'serviceFound', callback: Callback\): void 订阅发现mDNS服务的通知。 @@ -487,7 +770,7 @@ discoveryService.stopSearchingMDNS(); ### on('serviceLost') -on(type: 'serviceLost', callback: Callback<[LocalServiceInfo](#localserviceinfo)>): void +on(type: 'serviceLost', callback: Callback\): void 订阅移除mDNS服务的通知。 @@ -547,6 +830,6 @@ mDNS错误信息。 | 名称 | 值 | 说明 | | --------------- | ---- | ----------- | -| INTERNAL_ERROR | 0 | 内部错误导致操作失败。 | -| ALREADY_ACTIVE | 1 | 服务已经存在导致操作失败。 | +| INTERNAL_ERROR | 0 | 内部错误导致操作失败。(暂不支持) | +| ALREADY_ACTIVE | 1 | 服务已经存在导致操作失败。(暂不支持) | | MAX_LIMIT | 2 | 请求超过最大限制导致操作失败。(暂不支持) | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index d7ebd70b23d8889b5d04fda6832cda2f340f55da..32415c68aa57bcca2e42fee15c968a0019833955 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -382,7 +382,7 @@ getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) ## tag.getMifareClassic9+ -getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) 获取MIFARE Classic类型Tag对象,通过该对象访问支持MIFARE Classic技术类型的Tag。 @@ -766,8 +766,8 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 | -------- | -------- | -------- | -------- | -------- | | uid9+ | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。| | technology9+ | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 | -| supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#taginfo)替代。| -| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。| +| supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。| +| extrasData9+ | [PacMap](js-apis-inner-application-pacMap.md)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。| | tagRfDiscId9+ | number | 是 | 否 | 标签发现时分配的ID值。
**系统接口:** 此接口为系统接口。| | remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。
**系统接口:** 此接口为系统接口。| ## NdefRecord9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md index c1c30a09a349303b3daaa6c28f8df9216421a066..7384faeb10636aa3850ae29e789a07cc47d1d079 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md @@ -33,12 +33,14 @@ publish(request: NotificationRequest, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | | 1600004 | Notification is not enabled. | | 1600005 | Notification slot is not enabled. | | 1600009 | Over max number notifications per second. | +| 1600012 | No memory space. | **示例:** @@ -86,12 +88,15 @@ publish(request: NotificationRequest): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------------- | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | | 1600004 | Notification is not enabled. | | 1600005 | Notification slot is not enabled. | | 1600009 | Over max number notifications per second. | +| 1600012 | No memory space. | **示例:** @@ -140,6 +145,8 @@ publish(request: NotificationRequest, userId: number, callback: AsyncCallback\ | 错误码ID | 错误信息 | | -------- | ----------------------------------------- | +| 201 | Permission denied. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -208,6 +218,7 @@ publish(request: NotificationRequest, userId: number): Promise\ | 1600005 | Notification slot is not enabled. | | 1600008 | The user is not exist. | | 1600009 | Over max number notifications per second. | +| 1600012 | No memory space. | **示例:** @@ -254,6 +265,7 @@ cancel(id: number, label: string, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -294,6 +306,7 @@ cancel(id: number, label?: string): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -328,6 +341,7 @@ cancel(id: number, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -361,6 +375,7 @@ cancelAll(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -399,6 +414,7 @@ cancelAll(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -436,9 +452,13 @@ addSlot(slot: NotificationSlot, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -482,9 +502,13 @@ addSlot(slot: NotificationSlot): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -519,9 +543,11 @@ addSlot(type: SlotType, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -557,9 +583,11 @@ addSlot(type: SlotType): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -594,9 +622,13 @@ addSlots(slots: Array\, callback: AsyncCallback\): voi | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -644,9 +676,13 @@ addSlots(slots: Array\): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -685,6 +721,7 @@ getSlot(slotType: SlotType, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -730,6 +767,7 @@ getSlot(slotType: SlotType): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -763,6 +801,7 @@ getSlots(callback: AsyncCallback>): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -801,6 +840,7 @@ getSlots(): Promise\> | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -834,6 +874,7 @@ removeSlot(slotType: SlotType, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -873,6 +914,7 @@ removeSlot(slotType: SlotType): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -906,6 +948,7 @@ removeAllSlots(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -937,6 +980,7 @@ removeAllSlots(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -975,6 +1019,9 @@ setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCall | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1021,6 +1068,9 @@ setNotificationEnable(bundle: BundleOption, enable: boolean): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1062,6 +1112,9 @@ isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1113,6 +1166,9 @@ isNotificationEnabled(bundle: BundleOption): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1153,6 +1209,9 @@ isNotificationEnabled(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1201,6 +1260,9 @@ isNotificationEnabled(): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1240,6 +1302,9 @@ displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1327,6 +1395,9 @@ isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1378,6 +1449,9 @@ isBadgeDisplayed(bundle: BundleOption): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1412,10 +1486,11 @@ setBadgeNumber(badgeNumber: number): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | -| 1600012 | No memory space. | +| 1600012 | No memory space. | **示例:** @@ -1447,10 +1522,11 @@ setBadgeNumber(badgeNumber: number, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | -| 1600012 | No memory space. | +| 1600012 | No memory space. | **示例:** @@ -1493,6 +1569,9 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCal | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1542,6 +1621,9 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1586,6 +1668,9 @@ getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback> | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1678,6 +1766,9 @@ getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): voi | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1729,6 +1820,9 @@ getSlotNumByBundle(bundle: BundleOption): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1768,6 +1862,9 @@ getAllActiveNotifications(callback: AsyncCallback>) | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1810,6 +1907,9 @@ getAllActiveNotifications(): Promise\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1880,6 +1981,7 @@ getActiveNotificationCount(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1912,6 +2014,7 @@ getActiveNotifications(callback: AsyncCallback>): v | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -1950,6 +2053,7 @@ getActiveNotifications(): Promise\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2023,6 +2128,7 @@ cancelGroup(groupName: string): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2062,6 +2168,9 @@ removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCall | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2109,6 +2218,9 @@ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2149,9 +2261,13 @@ setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): vo | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -2197,9 +2313,13 @@ setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -2241,10 +2361,14 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallb | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | | 1600008 | The user is not exist. | +| 1600012 | No memory space. | **示例:** @@ -2293,10 +2417,14 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | | 1600008 | The user is not exist. | +| 1600012 | No memory space. | **示例:** @@ -2339,9 +2467,13 @@ getDoNotDisturbDate(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -2381,9 +2513,13 @@ getDoNotDisturbDate(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -2419,10 +2555,14 @@ getDoNotDisturbDate(userId: number, callback: AsyncCallback\) | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | | 1600008 | The user is not exist. | +| 1600012 | No memory space. | **示例:** @@ -2470,10 +2610,14 @@ getDoNotDisturbDate(userId: number): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | | 1600008 | The user is not exist. | +| 1600012 | No memory space. | **示例:** @@ -2508,6 +2652,9 @@ notificationManager.getDoNotDisturbDate(userId).then((data) => { | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2550,6 +2697,9 @@ isSupportDoNotDisturbMode(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2583,6 +2733,7 @@ isSupportTemplate(templateName: string, callback: AsyncCallback\): voi | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2629,6 +2780,7 @@ isSupportTemplate(templateName: string): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2664,6 +2816,7 @@ requestEnableNotification(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2696,6 +2849,7 @@ requestEnableNotification(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2735,6 +2889,9 @@ setDistributedEnable(enable: boolean, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2780,6 +2937,9 @@ setDistributedEnable(enable: boolean): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2816,6 +2976,7 @@ isDistributedEnabled(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2857,6 +3018,7 @@ isDistributedEnabled(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2898,6 +3060,9 @@ setDistributedEnableByBundle(bundle: BundleOption, enable: boolean, callback: As | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -2951,6 +3116,9 @@ setDistributedEnableByBundle(bundle: BundleOption, enable: boolean): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3093,6 +3267,9 @@ getDeviceRemindType(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3135,6 +3312,9 @@ getDeviceRemindType(): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3175,6 +3355,9 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 错误码ID | 错误信息 | | -------- | ----------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3182,6 +3365,7 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 1600005 | Notification slot is not enabled. | | 1600008 | The user is not exist. | | 1600009 | Over max number notifications per second. | +| 1600012 | No memory space. | **示例:** @@ -3241,6 +3425,9 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 错误码ID | 错误信息 | | -------- | ----------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3248,6 +3435,7 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 1600005 | Notification slot is not enabled. | | 1600008 | The user is not exist. | | 1600009 | Over max number notifications per second. | +| 1600012 | No memory space. | **示例:** @@ -3303,6 +3491,9 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number, callbac | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3356,6 +3547,9 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number): Promis | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3402,6 +3596,9 @@ setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3452,6 +3649,9 @@ setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean) | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3495,6 +3695,9 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncC | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -3549,6 +3752,9 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md index cfc61dacf914744662371b7530e785f3d0e97474..0d986594532e10b6a7e6070b0d7db089322fabd6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -40,9 +40,13 @@ subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, c | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -92,9 +96,13 @@ subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -142,9 +150,13 @@ subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | +| 1600012 | No memory space. | **示例:** @@ -187,6 +199,9 @@ unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -234,6 +249,9 @@ unsubscribe(subscriber: NotificationSubscriber): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -279,6 +297,9 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -334,6 +355,9 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -382,6 +406,9 @@ remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -428,6 +455,9 @@ remove(hashCode: string, reason: RemoveReason): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -468,6 +498,9 @@ removeAll(bundle: BundleOption, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -513,6 +546,9 @@ removeAll(callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -555,6 +591,9 @@ removeAll(bundle?: BundleOption): Promise\ | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -594,6 +633,9 @@ removeAll(userId: number, callback: AsyncCallback\): void | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | @@ -639,6 +681,9 @@ removeAll(userId: number): Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------- | +| 201 | Permission denied. | +| 202 | Not system application to call the interface. | +| 401 | The parameter check failed. | | 1600001 | Internal error. | | 1600002 | Marshalling or unmarshalling error. | | 1600003 | Failed to connect service. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index ffedac9eb368d5deb17fc638f97132bfe73c213a..f1b0cd323a58af7b79795ccad728bceefd9d88df 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -6147,7 +6147,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; | localName | string | 是 | 系统帐号名称。 | | type | [OsAccountType](#osaccounttype) | 是 | 系统帐号类型 | | constraints | Array<string> | 否 | 系统帐号[约束](#系统帐号约束列表) | -| isVerified8+ | boolean | 是 | 帐号是否锁屏 | +| isVerified8+ | boolean | 是 | 帐号是否验证 | | photo8+ | string | 否 | 系统帐号头像 | | createTime8+ | number | 是 | 系统帐号创建时间 | | lastLoginTime8+ | number | 否 | 系统帐号最后一次登录时间 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-radio.md b/zh-cn/application-dev/reference/apis/js-apis-radio.md index c5746422ef06f7aa7bd5a198c17e5281d74f0564..92cac4d69345aa5a635e5b202b0e9936a6865b1d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-radio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-radio.md @@ -2513,7 +2513,7 @@ off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------ | ---- | -------------------------------------- | -| type | string | 是 | 通话结束时取消监听通话详情的变化。 | +| type | string | 是 | 取消监听IMS注册状态的变化。 | | slotId | number | 是 | 卡槽ID。
- 0:卡槽1
- 1:卡槽2 | | imsType | [ImsServiceType](#imsservicetype9) | 是 | IMS服务类型。 | | callback | Callback<[ImsRegInfo](#imsreginfo9)> | 否 | 回调函数。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index 8a3d0f58ca91cae5161036a7974d46df96e43d2e..8c2d6a082ca0b7d5ea317815f04494b1b9447444 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @@ -1234,9 +1234,9 @@ getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback< ``` -### getPluralString9+ +### getPluralStringValue9+ -getPluralString(resource: Resource, num: number): Promise<string> +getPluralStringValue(resource: Resource, num: number): Promise<string> 根据指定数量获取对指定resource对象表示的单复数字符串,使用Promise形式返回字符串。 @@ -1273,10 +1273,10 @@ getPluralString(resource: Resource, num: number): Promise<string> id: $r('app.plural.test').id }; try { - this.context.resourceManager.getPluralString(resource, 1).then(value => { + this.context.resourceManager.getPluralStringValue(resource, 1).then(value => { let str = value; }).catch(error => { - console.log("getPluralString promise error is " + error); + console.log("getPluralStringValue promise error is " + error); }); } catch (error) { console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`) @@ -2406,8 +2406,8 @@ getNumber(resId: number): number **返回值:** | 类型 | 说明 | -| ------ | ---------- | -| number | 资源ID值对应的数值 | +| ------ | ---------- | +| number | 资源ID值对应的数值。Integer对应的是原数值,float对应的是真实像素点值 | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 @@ -2422,13 +2422,13 @@ getNumber(resId: number): number **示例:** ```ts try { - this.context.resourceManager.getNumber($r('app.integer.integer_test').id); + this.context.resourceManager.getNumber($r('app.integer.integer_test').id); // integer对应返回的是原数值 } catch (error) { console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`) } try { - this.context.resourceManager.getNumber($r('app.float.float_test').id); + this.context.resourceManager.getNumber($r('app.float.float_test').id); // float对应返回的是真实像素点值 } catch (error) { console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`) } @@ -2452,7 +2452,7 @@ getNumber(resource: Resource): number | 类型 | 说明 | | ------ | --------------- | -| number | resource对象对应的数值 | +| number | resource对象对应的数值。Integer对应的是原数值,float对应的是真实像素点值 | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 @@ -2472,7 +2472,7 @@ getNumber(resource: Resource): number id: $r('app.integer.integer_test').id }; try { - this.context.resourceManager.getNumber(resource); + this.context.resourceManager.getNumber(resource);// integer对应返回的是原数值, float对应返回的是真实像素点值 } catch (error) { console.error(`getNumber failed, error code: ${error.code}, message: ${error.message}.`) } diff --git a/zh-cn/application-dev/reference/apis/js-apis-router.md b/zh-cn/application-dev/reference/apis/js-apis-router.md index fde185a857f3003328e25b39b80d3838061c6fd2..d5821a1d124d51c927f76909ff723fde6d634b56 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-router.md +++ b/zh-cn/application-dev/reference/apis/js-apis-router.md @@ -395,7 +395,7 @@ back(options?: RouterOptions ): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| options | [RouterOptions](#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面栈里面的page不会回收,出栈后会被回收。 | +| options | [RouterOptions](#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 | **示例:** @@ -573,8 +573,8 @@ router.getParams(); | 名称 | 说明 | | -------- | ------------------------------------------------------------ | -| Standard | 标准模式。
目标页面会被添加到页面路由栈顶,无论栈中是否存在相同url的页面。
**说明:** 不使用路由跳转模式时,按标准模式跳转。 | -| Single | 单实例模式。
如果目标页面的url在页面栈中已经存在同url页面,离栈顶最近的页面会被移动到栈顶,移动后的页面为新建页。
如目标页面的url在页面栈中不存在同url页面,按标准模式跳转。 | +| Standard | 多实例模式,也是默认情况下的跳转模式。
目标页面会被添加到页面栈顶,无论栈中是否存在相同url的页面。
**说明:** 不使用路由跳转模式时,则按照默认的多实例模式进行跳转。 | +| Single | 单实例模式。
如果目标页面的url已经存在于页面栈中,则会将离栈顶最近的同url页面移动到栈顶,该页面成为新建页。
如果目标页面的url在页面栈中不存在同url页面,则按照默认的多实例模式进行跳转。 | ## 完整示例 diff --git a/zh-cn/application-dev/reference/apis/js-apis-rpc.md b/zh-cn/application-dev/reference/apis/js-apis-rpc.md index edf7e7169821b9950ddd0f7cd28cd2e6df300c16..b5e1808f23bee943f177affcdf7d733e883975a9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-rpc.md +++ b/zh-cn/application-dev/reference/apis/js-apis-rpc.md @@ -97,9 +97,9 @@ writeRemoteObject(object: [IRemoteObject](#iremoteobject)): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900008 | proxy or remote object is invalid | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | + | 1900009 | write data to message sequence failed | **示例:** @@ -138,9 +138,9 @@ readRemoteObject(): IRemoteObject 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | + | 1900010 | read data from message sequence failed | **示例:** @@ -180,8 +180,8 @@ writeInterfaceToken(token: string): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -214,8 +214,8 @@ readInterfaceToken(): string 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ----- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -266,7 +266,7 @@ getCapacity(): number **返回值:** - | 类型 | 说明 | + | 类型 | 说明 | | ------ | ----- | | number | 获取的MessageSequence实例的容量大小。以字节为单位。 | @@ -288,7 +288,7 @@ setSize(size: number): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------ | | size | number | 是 | MessageSequence实例的数据大小。以字节为单位。 | @@ -324,8 +324,8 @@ setCapacity(size: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------ | - | 1900011 | parcel memory alloc failed | + | -------- | -------- | + | 1900011 | parcel memory alloc failed | **示例:** @@ -350,7 +350,7 @@ getWritableBytes(): number **返回值:** - | 类型 | 说明 | + | 类型 | 说明 | | ------ | ------ | | number | 获取到的MessageSequence实例的可写字节空间。以字节为单位。 | @@ -376,7 +376,7 @@ getReadableBytes(): number **返回值:** - | 类型 | 说明 | + | 类型 | 说明 | | ------ | ------- | | number | 获取到的MessageSequence实例的可读字节空间。以字节为单位。 | @@ -402,7 +402,7 @@ getReadPosition(): number **返回值:** - | 类型 | 说明 | + | 类型 | 说明 | | ------ | ------ | | number | 返回MessageSequence实例中的当前读取位置。 | @@ -424,7 +424,7 @@ getWritePosition(): number **返回值:** - | 类型 | 说明 | + | 类型 | 说明 | | ------ | ----- | | number | 返回MessageSequence实例中的当前写入位置。 | @@ -447,7 +447,7 @@ rewindRead(pos: number): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | pos | number | 是 | 开始读取数据的目标位置。 | @@ -479,7 +479,7 @@ rewindWrite(pos: number): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ----- | | pos | number | 是 | 开始写入数据的目标位置。 | @@ -509,17 +509,17 @@ writeByte(val: number): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ----- | ------ | ---- | ----- | - | val | number | 是 | 要写入的字节值。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------ | ------ | ---- | ----- | + | val | number | 是 | 要写入的字节值。 | **错误码:** 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900009 | write data to message sequence failed | + | -------- | ------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -543,7 +543,7 @@ readByte(): number **返回值:** - | 类型 | 说明 | + | 类型 | 说明 | | ------ | ----- | | number | 返回字节值。 | @@ -585,16 +585,16 @@ writeShort(val: number): void **参数:** | 参数名 | 类型 | 必填 | 说明 | - | ------ | ------ | --- | --- | - | val | number | 是 | 要写入的短整数值。 | + | ------ | ------ | --- | --- | + | val | number | 是 | 要写入的短整数值。 | **错误码:** 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------ | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -627,8 +627,8 @@ readShort(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -668,8 +668,8 @@ writeInt(val: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -702,8 +702,8 @@ readInt(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -743,8 +743,8 @@ writeLong(val: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -777,8 +777,8 @@ readLong(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -809,17 +809,17 @@ writeFloat(val: number): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ----- | ---- | ---- | ----- | - | val | number | 是 | 要写入的浮点值。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------ | ------ | ---- | ----- | + | val | number | 是 | 要写入的浮点值。 | **错误码:** 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -852,8 +852,8 @@ readFloat(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -893,8 +893,8 @@ writeDouble(val: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -927,8 +927,8 @@ readDouble(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -968,8 +968,8 @@ writeBoolean(val: boolean): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1002,8 +1002,8 @@ readBoolean(): boolean 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1043,8 +1043,8 @@ writeChar(val: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1077,8 +1077,8 @@ readChar(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------ | --------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1118,8 +1118,8 @@ writeString(val: string): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1152,8 +1152,8 @@ readString(): string 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1193,8 +1193,8 @@ writeParcelable(val: Parcelable): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1239,16 +1239,16 @@ readParcelable(dataIn: Parcelable): void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------- | ---- | ----------------------------------------- | - | dataIn | Parcelable | 是 | 需要从MessageSequence读取成员变量的对象。 | + | dataIn | Parcelable | 是 | 需要从MessageSequence读取成员变量的对象。 | **错误码:** 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900010 | read data from message sequence failed | - | 1900012 | call js callback function failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | + | 1900012 | call js callback function failed | **示例:** @@ -1302,8 +1302,8 @@ writeByteArray(byteArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1337,8 +1337,8 @@ readByteArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1379,8 +1379,8 @@ readByteArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1421,8 +1421,8 @@ writeShortArray(shortArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ----- | ----- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1455,8 +1455,8 @@ readShortArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------ | ------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1496,8 +1496,8 @@ readShortArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1537,8 +1537,8 @@ writeIntArray(intArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ----- | --------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1571,8 +1571,8 @@ readIntArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1612,8 +1612,8 @@ readIntArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ----- | ------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1653,8 +1653,8 @@ writeLongArray(longArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ----- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1687,8 +1687,8 @@ readLongArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------ | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1728,8 +1728,8 @@ readLongArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1769,8 +1769,8 @@ writeFloatArray(floatArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1803,8 +1803,8 @@ readFloatArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1844,8 +1844,8 @@ readFloatArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1885,8 +1885,8 @@ writeDoubleArray(doubleArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -1919,8 +1919,8 @@ readDoubleArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -1960,8 +1960,8 @@ readDoubleArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2001,8 +2001,8 @@ writeBooleanArray(booleanArray: boolean[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -2035,8 +2035,8 @@ readBooleanArray(dataIn: boolean[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2076,8 +2076,8 @@ readBooleanArray(): boolean[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2117,8 +2117,8 @@ writeCharArray(charArray: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------ | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -2151,8 +2151,8 @@ readCharArray(dataIn: number[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2192,8 +2192,8 @@ readCharArray(): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2234,8 +2234,8 @@ writeStringArray(stringArray: string[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -2268,8 +2268,8 @@ readStringArray(dataIn: string[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2309,8 +2309,8 @@ readStringArray(): string[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2344,8 +2344,8 @@ writeNoException(): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -2386,15 +2386,17 @@ readException(): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -2412,7 +2414,11 @@ readException(): void "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendMessageRequest接口方法发送消息 @@ -2466,8 +2472,8 @@ writeParcelableArray(parcelableArray: Parcelable[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -2522,9 +2528,9 @@ readParcelableArray(parcelableArray: Parcelable[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | - | 1900012 | call js callback function failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | + | 1900012 | call js callback function failed | **示例:** @@ -2583,8 +2589,8 @@ writeRemoteObjectArray(objectArray: IRemoteObject[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -2630,8 +2636,8 @@ readRemoteObjectArray(objects: IRemoteObject[]): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2683,8 +2689,8 @@ readRemoteObjectArray(): IRemoteObject[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -2729,11 +2735,11 @@ static closeFileDescriptor(fd: number): void **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); try { - rpc.MessageSequence.closeFileDescriptor(fd); + rpc.MessageSequence.closeFileDescriptor(file.fd); } catch(error) { console.info("rpc close file descriptor fail, errorCode " + error.code); console.info("rpc close file descriptor fail, errorMessage" + error.message); @@ -2765,17 +2771,17 @@ static dupFileDescriptor(fd: number) :number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900013 | call os dup function failed | + | -------- | -------- | + | 1900013 | call os dup function failed | **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); try { - let newFd = rpc.MessageSequence.dupFileDescriptor(fd); + let newFd = rpc.MessageSequence.dupFileDescriptor(file.fd); } catch(error) { console.info("rpc dup file descriptor fail, errorCode " + error.code); console.info("rpc dup file descriptor fail, errorMessage" + error.message); @@ -2800,13 +2806,13 @@ containFileDescriptors(): boolean ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; let r1 = sequence.containFileDescriptors(); - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); try { - sequence.writeFileDescriptor(fd); + sequence.writeFileDescriptor(file.fd); } catch(error) { console.info("rpc write file descriptor fail, errorCode " + error.code); console.info("rpc write file descriptor fail, errorMessage" + error.message); @@ -2839,18 +2845,18 @@ writeFileDescriptor(fd: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------ | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); try { - sequence.writeFileDescriptor(fd); + sequence.writeFileDescriptor(file.fd); } catch(error) { console.info("rpc write file descriptor fail, errorCode " + error.code); console.info("rpc write file descriptor fail, errorMessage" + error.message); @@ -2876,18 +2882,18 @@ readFileDescriptor(): number 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); try { - sequence.writeFileDescriptor(fd); + sequence.writeFileDescriptor(file.fd); } catch(error) { console.info("rpc write file descriptor fail, errorCode " + error.code); console.info("rpc write file descriptor fail, errorMessage" + error.message); @@ -2919,8 +2925,8 @@ writeAshmem(ashmem: Ashmem): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------- | - | 1900003 | write to ashmem failed | + | -------- | ------- | + | 1900003 | write to ashmem failed | **示例:** @@ -2961,8 +2967,8 @@ readAshmem(): Ashmem 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900004 | read from ashmem failed | + | -------- | -------- | + | 1900004 | read from ashmem failed | **示例:** @@ -3032,8 +3038,8 @@ writeRawData(rawData: number[], size: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------ | - | 1900009 | write data to message sequence failed | + | -------- | -------- | + | 1900009 | write data to message sequence failed | **示例:** @@ -3073,8 +3079,8 @@ readRawData(size: number): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900010 | read data from message sequence failed | + | -------- | -------- | + | 1900010 | read data from message sequence failed | **示例:** @@ -4027,8 +4033,8 @@ writeSequenceable(val: Sequenceable): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4068,14 +4074,14 @@ readSequenceable(dataIn: Sequenceable): boolean **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------ | ----------------------------- | ---- | --------------------------------------- | + | 参数名 | 类型 | 必填 | 说明 | + | ------ | ----------------------------- | ------- | ---------------------------------------------- | | dataIn | [Sequenceable](#sequenceabledeprecated) | 是 | 需要从MessageParcel读取成员变量的对象。 | **返回值:** - | 类型 | 说明 | - | ------- | ------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------------- | | boolean | true:反序列化成功,false:反序列化失败。| **示例:** @@ -4124,8 +4130,8 @@ writeByteArray(byteArray: number[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4203,8 +4209,8 @@ writeShortArray(shortArray: number[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4279,8 +4285,8 @@ writeIntArray(intArray: number[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4425,14 +4431,14 @@ writeFloatArray(floatArray: number[]): boolean **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ---------- | -------- | ---- | --- | | floatArray | number[] | 是 | 要写入的浮点数组。由于系统内部对float类型的数据是按照double处理的,使用时对于数组所占的总字节数应按照double类型来计算。 | **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4453,7 +4459,7 @@ readFloatArray(dataIn: number[]): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------ | | dataIn | number[] | 是 | 要读取的浮点数组。由于系统内部对float类型的数据是按照double处理的,使用时对于数组所占的总字节数应按照double类型来计算。 | @@ -4507,8 +4513,8 @@ writeDoubleArray(doubleArray: number[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4583,8 +4589,8 @@ writeBooleanArray(booleanArray: boolean[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4659,8 +4665,8 @@ writeCharArray(charArray: number[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4729,14 +4735,14 @@ writeStringArray(stringArray: string[]): boolean **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ----------- | -------- | ---- | ---------------- | | stringArray | string[] | 是 | 要写入的字符串数组,数组单个元素的长度应小于40960字节。 | **返回值:** | 类型 | 说明 | - | ------- | --------------------------------- | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -4846,11 +4852,13 @@ readException(): void **系统能力**:SystemCapability.Communication.IPC.Core **示例:** - - 获取服务 + + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.;featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -4868,7 +4876,11 @@ readException(): void "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendMessageRequest接口方法发送消息 @@ -4914,8 +4926,8 @@ writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -5004,14 +5016,14 @@ writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ----------- | --------------- | ---- | ----- | | objectArray | IRemoteObject[] | 是 | 要写入MessageParcel的IRemoteObject对象数组。 | **返回值:** | 类型 | 说明 | - | ------- | -------------------------------------------------------------------------------------------------------------------- | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -5056,7 +5068,7 @@ readRemoteObjectArray(objects: IRemoteObject[]): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | + | 参数名 | 类型 | 必填 | 说明 | | ------- | --------------- | ---- | --------- | | objects | IRemoteObject[] | 是 | 从MessageParcel读取的IRemoteObject对象数组。 | @@ -5103,8 +5115,8 @@ readRemoteObjectArray(): IRemoteObject[] **返回值:** - | 类型 | 说明 | - | --------------- | -------- | + | 类型 | 说明 | + | --------------- | --------------------------- | | IRemoteObject[] | 返回IRemoteObject对象数组。 | **示例:** @@ -5158,10 +5170,10 @@ static closeFileDescriptor(fd: number): void **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - rpc.MessageParcel.closeFileDescriptor(fd); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + rpc.MessageParcel.closeFileDescriptor(file.fd); ``` ### dupFileDescriptor8+ @@ -5187,10 +5199,10 @@ static dupFileDescriptor(fd: number) :number **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let newFd = rpc.MessageParcel.dupFileDescriptor(fd); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let newFd = rpc.MessageParcel.dupFileDescriptor(file.fd); ``` ### containFileDescriptors8+ @@ -5203,19 +5215,19 @@ containFileDescriptors(): boolean **返回值:** - | 类型 | 说明 | - | ------- | ------------------------------------------------------------------ | + | 类型 | 说明 | + | ------- | --------------------------------------------- | | boolean |true:包含文件描述符,false:未包含文件描述符。| **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; let r1 = parcel.containFileDescriptors(); - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let writeResult = parcel.writeFileDescriptor(file.fd); console.log("RpcTest: parcel writeFd result is : " + writeResult); let containFD = parcel.containFileDescriptors(); console.log("RpcTest: parcel after write fd containFd result is : " + containFD); @@ -5237,18 +5249,18 @@ writeFileDescriptor(fd: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:操作成功,false:操作失败。| **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let writeResult = parcel.writeFileDescriptor(file.fd); console.log("RpcTest: parcel writeFd result is : " + writeResult); ``` @@ -5269,11 +5281,11 @@ readFileDescriptor(): number **示例:** ```ts - import fileio from '@ohos.fileio'; + import fs from '@ohos.file.fs'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; - let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let writeResult = parcel.writeFileDescriptor(file.fd); let readFD = parcel.readFileDescriptor(); console.log("RpcTest: parcel read fd is : " + readFD); ``` @@ -5294,8 +5306,8 @@ writeAshmem(ashmem: Ashmem): boolean **返回值:** - | 类型 | 说明 | - | ------- | -------------------------------------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -5371,8 +5383,8 @@ writeRawData(rawData: number[], size: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:写入成功,false:写入失败。| **示例:** @@ -5435,9 +5447,9 @@ marshalling(dataOut: MessageSequence): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | - | boolean | true:封送成功,false:封送失败。 + | 类型 | 说明 | + | ------- | -------------------------------- | + | boolean | true:封送成功,false:封送失败。| **示例:** ```ts @@ -5484,8 +5496,8 @@ unmarshalling(dataIn: MessageSequence): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------------- | | boolean | true:反序列化成功,false:反序列化失败。| **示例:** @@ -5534,15 +5546,15 @@ marshalling(dataOut: MessageParcel): boolean **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | ----------------------------------------- | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ----------------------------------------- | ---- | ----------------------------------------- | | dataOut | [MessageParcel](#messageparceldeprecated) | 是 | 可序列对象将被封送到的MessageParcel对象。 | **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | - | boolean | true:封送成功,false:封送失败。 + | 类型 | 说明 | + | ------- | -------------------------------- | + | boolean | true:封送成功,false:封送失败。 | **示例:** ```ts @@ -5583,14 +5595,14 @@ unmarshalling(dataIn: MessageParcel): boolean **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------ | ------------------------------- | ---- | --------------------------------------------- | + | 参数名 | 类型 | 必填 | 说明 | + | ------ | ----------------------------------------- | ---- | --------------------------------------------- | | dataIn | [MessageParcel](#messageparceldeprecated) | 是 | 已将可序列对象封送到其中的MessageParcel对象。 | **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------------- | | boolean | true:反序列化成功,false:反序列化失败。| **示例:** @@ -5637,8 +5649,8 @@ asObject(): IRemoteObject **返回值:** - | 类型 | 说明 | - | ---- | ----- | + | 类型 | 说明 | + | ----- | ----- | | [IRemoteObject](#iremoteobject) | 如果调用者是RemoteObject对象,则直接返回本身;如果调用者是[RemoteProxy](#remoteproxy)对象,则返回它的持有者[IRemoteObject](#iremoteobject)。 | **示例:** @@ -5654,20 +5666,22 @@ asObject(): IRemoteObject **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { - onConnect: function (elementName, remoteProxy) { + onConnect: function(elementName, remoteProxy) { console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function (elementName) { + onDisconnect: function(elementName) { console.log("RpcClient: onDisconnect"); }, - onFailed: function () { + onFailed: function() { console.log("RpcClient: onFailed"); } }; @@ -5675,11 +5689,15 @@ asObject(): IRemoteObject "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` - 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的asObject接口方法获取代理或远端对象 + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的asObject接口方法获取代理或远端对象 + ```ts class TestProxy { remote: rpc.RemoteObject; @@ -5691,7 +5709,6 @@ asObject(): IRemoteObject } } let iRemoteObject = new TestProxy(proxy).asObject(); - ``` ## DeathRecipient @@ -5802,17 +5819,17 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | ---- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:发送成功,false:发送失败。| @@ -5828,12 +5845,12 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ---------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -5852,12 +5869,12 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -5876,13 +5893,13 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | - | callback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | callback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | ### sendRequest8+(deprecated) @@ -5896,13 +5913,13 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | - | callback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | callback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | ### registerDeathRecipient9+ @@ -5924,8 +5941,8 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | ### addDeathrecipient(deprecated) @@ -5946,8 +5963,8 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------------- | | boolean | true:回调注册成功,false:回调注册失败。| @@ -5971,8 +5988,8 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | ### removeDeathRecipient(deprecated) @@ -5993,8 +6010,8 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | -----------------------------------------| | boolean | true:回调注销成功,false:回调注销失败。| ### getDescriptor9+ @@ -6016,8 +6033,8 @@ getDescriptor(): string 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | ### getInterfaceDescriptor(deprecated) @@ -6047,8 +6064,8 @@ isObjectDead(): boolean **返回值:** - | 类型 | 说明 | - | ------- | ------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------- | | boolean | true:对象死亡,false:对象未死亡。| @@ -6078,25 +6095,27 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------| | boolean | true:发送成功,false:发送失败。| **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6114,11 +6133,15 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` - 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendRequest接口方法发送消息 + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendRequest接口方法发送消息 + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageParcel.create(); @@ -6148,12 +6171,12 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | - | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -6163,10 +6186,12 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6184,9 +6209,13 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendMessageRequest接口方法发送消息 ```ts @@ -6226,12 +6255,12 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -6241,10 +6270,12 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6262,7 +6293,11 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendRequest接口方法发送消息 @@ -6302,20 +6337,22 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | - | callback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | callback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | **示例:** - - 获取服务 + + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6346,7 +6383,11 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, result.data.reclaim(); result.reply.reclaim(); } - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendMessageRequest接口方法发送消息 @@ -6358,7 +6399,7 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, data.writeInt(1); data.writeString("hello"); try { - proxy.sendRequest(1, data, reply, option, sendRequestCallback); + proxy.sendMessageRequest(1, data, reply, option, sendRequestCallback); } catch(error) { console.info("rpc send sequence request fail, errorCode " + error.code); console.info("rpc send sequence request fail, errorMessage " + error.message); @@ -6377,20 +6418,22 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | - | callback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | callback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6408,7 +6451,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - function sendRequestCallback(result) { + function sendRequestCallback(result) { if (result.errCode === 0) { console.log("sendRequest got result"); result.reply.readException(); @@ -6421,7 +6464,11 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me result.data.reclaim(); result.reply.reclaim(); } - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的sendRequest接口方法发送消息 @@ -6460,22 +6507,24 @@ getLocalInterface(interface: string): IRemoteBroker 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900006 | only remote object permitted | + | -------- | -------- | + | 1900006 | only remote object permitted | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function (elementName) { + onDisconnect: function(elementName) { console.log("RpcClient: onDisconnect"); }, onFailed: function() { @@ -6483,10 +6532,14 @@ getLocalInterface(interface: string): IRemoteBroker } }; let want = { - "bundleName":"com.ohos.server", - "abilityName":"com.ohos.server.EntryAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的getLocalInterface接口方法查询接口对象 @@ -6525,17 +6578,19 @@ queryLocalInterface(interface: string): IRemoteBroker **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function (elementName) { + onDisconnect: function(elementName) { console.log("RpcClient: onDisconnect"); }, onFailed: function() { @@ -6543,12 +6598,16 @@ queryLocalInterface(interface: string): IRemoteBroker } }; let want = { - "bundleName":"com.ohos.server", - "abilityName":"com.ohos.server.EntryAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的queryLocalInterface接口获取接口对象 ```ts @@ -6576,15 +6635,17 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6602,11 +6663,15 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的registerDeathRecipient接口注册死亡回调 - + ```ts class MyDeathRecipient { onRemoteDied() { @@ -6641,16 +6706,18 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------------- | | boolean | true:回调注册成功,false:回调注册失败。| **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6668,9 +6735,13 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的addDeathRecippient接口方法新增死亡回调 ```ts @@ -6703,15 +6774,17 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6729,9 +6802,13 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的unregisterDeathRecipient接口方法注销死亡回调 ```ts @@ -6769,16 +6846,18 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------------- | | boolean | true:回调注销成功,false:回调注销失败。| **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6796,9 +6875,13 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的removeDeathRecipient接口方法去注册死亡回调 ```ts @@ -6831,16 +6914,18 @@ getDescriptor(): string 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900008 | proxy or remote object is invalid | - | 1900007 | communication failed | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | + | 1900007 | communication failed | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6858,7 +6943,11 @@ getDescriptor(): string "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的getDescriptor接口方法获取对象的接口描述符 @@ -6890,10 +6979,12 @@ getInterfaceDescriptor(): string **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6911,9 +7002,13 @@ getInterfaceDescriptor(): string "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); - ``` + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); + ``` + 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的getInterfaceDescriptor接口方法查询当前代理对象接口的描述符 ```ts @@ -6931,16 +7026,18 @@ isObjectDead(): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------------------- | - | boolean | true:对应的对象已经死亡,false:对应的对象未死亡| + | 类型 | 说明 | + | ------- | ------------------------------------------------- | + | boolean | true:对应的对象已经死亡,false:对应的对象未死亡 | **示例:** - 获取服务 + Stage模型的应用在获取服务前需要先获取context,具体方法可参考[获取context](#获取context) ```ts - import FA from "@ohos.ability.featureAbility"; + // 仅FA模型需要导入@ohos.ability.featureAbility + // import FA from "@ohos.ability.featureAbility"; + let proxy; let connect = { onConnect: function(elementName, remoteProxy) { @@ -6958,7 +7055,11 @@ isObjectDead(): boolean "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.EntryAbility", }; - FA.connectAbility(want, connect); + + // FA模型使用此方法连接服务 + // FA.connectAbility(want,connect); + + globalThis.context.connectServiceExtensionAbility(want, connect); ``` 上述onConnect回调函数中的proxy对象需要等ability异步连接成功后才会被赋值,然后才可调用proxy对象的isObjectDead接口方法判断当前对象是否已经死亡 @@ -6976,10 +7077,10 @@ isObjectDead(): boolean | 名称 | 值 | 说明 | | ------------- | ---- | ----------------------------------------------------------- | - | TF_SYNC | 0 | 同步调用标识。 | - | TF_ASYNC | 1 | 异步调用标识。 | + | TF_SYNC | 0 | 同步调用标识。 | + | TF_ASYNC | 1 | 异步调用标识。 | | TF_ACCEPT_FDS | 0x10 | 指示sendMessageRequest9+接口可以返回文件描述符。 | - | TF_WAIT_TIME | 8 | 默认等待时间(单位/秒)。 | + | TF_WAIT_TIME | 8 | 默认等待时间(单位/秒)。 | ### constructor9+ @@ -7041,9 +7142,9 @@ isAsync(): boolean; **返回值:** - | 类型 | 说明 | - | ------- | ------------------------------------ | - | boolean | true:同步调用成功,false:异步调用成功。 | + | 类型 | 说明 | + | ------- | ---------------------------------------- | + | boolean | true:同步调用成功,false:异步调用成功。| **示例:** @@ -7349,8 +7450,8 @@ static isLocalCalling(): boolean **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------------------------- | | boolean | true:调用在同一台设备,false:调用未在同一台设备。| **示例:** @@ -7522,8 +7623,8 @@ static setCallingIdentity(identity: string): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | ---------------------------------| | boolean | true:设置成功,false:设置失败。| **示例:** @@ -7575,17 +7676,17 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** - | 类型 | 说明 | - | ------- | --------------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:发送成功,false:发送失败。| **示例:** @@ -7641,12 +7742,12 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -7711,12 +7812,12 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | **返回值:** @@ -7767,13 +7868,13 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | | data | [MessageSequence](#messagesequence9) | 是 | 保存待发送数据的 MessageSequence对象。 | | reply | [MessageSequence](#messagesequence9) | 是 | 接收应答数据的MessageSequence对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | - | AsyncCallback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | AsyncCallback | AsyncCallback<RequestResult> | 是 | 接收发送结果的回调。 | **示例:** @@ -7817,13 +7918,13 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | - | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | - | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | - | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | - | AsyncCallback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | 是 | 本次请求调用的消息码,由通信双方确定。如果接口由IDL工具生成,则消息代码由IDL自动生成。 | + | data | [MessageParcel](#messageparceldeprecated) | 是 | 保存待发送数据的 MessageParcel对象。 | + | reply | [MessageParcel](#messageparceldeprecated) | 是 | 接收应答数据的MessageParcel对象。 | + | options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 | + | AsyncCallback | AsyncCallback<SendRequestResult> | 是 | 接收发送结果的回调。 | **示例:** @@ -7881,17 +7982,17 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里处理 **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------ | ------------------------------- | ---- | --------------------------------------- | - | code | number | 是 | 对端发送的服务请求码。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------ | ----------------------------------------- | ---- | --------------------------------------- | + | code | number | 是 | 对端发送的服务请求码。 | | data | [MessageParcel](#messageparceldeprecated) | 是 | 携带客户端调用参数的MessageParcel对象。 | | reply | [MessageParcel](#messageparceldeprecated) | 是 | 写入结果的MessageParcel对象。 | - | option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 | + | option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 | **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:操作成功,false:操作失败。| **示例:** @@ -7942,17 +8043,17 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步 **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | ------ | ------------------------------- | ---- | ----------------------------------------- | - | code | number | 是 | 对端发送的服务请求码。 | + | 参数名 | 类型 | 必填 | 说明 | + | ------ | ------------------------------------ | ---- | ----------------------------------------- | + | code | number | 是 | 对端发送的服务请求码。 | | data | [MessageSequence](#messagesequence9) | 是 | 携带客户端调用参数的MessageSequence对象。 | | reply | [MessageSequence](#messagesequence9) | 是 | 写入结果的MessageSequence对象。 | - | option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 | + | option | [MessageOption](#messageoption) | 是 | 指示操作是同步还是异步。 | **返回值:** - | 类型 | 说明 | - | ----------------- | ---------------------------------------------------------------------------------------------- | + | 类型 | 说明 | + | ----------------- | ----------------------------------------------------------------------------------------------- | | boolean | 若在onRemoteMessageRequest中同步地处理请求,则返回一个布尔值:true:操作成功,false:操作失败。 | | Promise\ | 若在onRemoteMessageRequest中异步地处理请求,则返回一个Promise对象。 | @@ -8233,8 +8334,8 @@ getDescriptor(): string 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | + | -------- | -------- | + | 1900008 | proxy or remote object is invalid | **示例:** @@ -8625,8 +8726,8 @@ mapTypedAshmem(mapType: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | ------ | - | 1900001 | call mmap function failed | + | -------- | -------- | + | 1900001 | call mmap function failed | **示例:** @@ -8658,8 +8759,8 @@ mapAshmem(mapType: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:映射成功,false:映射失败。| **示例:** @@ -8683,8 +8784,8 @@ mapReadWriteAshmem(): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900001 | call mmap function failed | + | -------- | -------- | + | 1900001 | call mmap function failed | **示例:** @@ -8710,8 +8811,8 @@ mapReadAndWriteAshmem(): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:映射成功,false:映射失败。| **示例:** @@ -8735,8 +8836,8 @@ mapReadonlyAshmem(): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900001 | call mmap function failed | + | -------- | -------- | + | 1900001 | call mmap function failed | **示例:** @@ -8762,8 +8863,8 @@ mapReadOnlyAshmem(): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:映射成功,false:映射失败。| **示例:** @@ -8793,8 +8894,8 @@ setProtectionType(protectionType: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | -------- | ------- | - | 1900002 | call os ioctl function failed | + | -------- | -------- | + | 1900002 | call os ioctl function failed | **示例:** @@ -8826,8 +8927,8 @@ setProtection(protectionType: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------- | + | 类型 | 说明 | + | ------- | -------------------------------- | | boolean | true:设置成功,false:设置失败。| **示例:** @@ -8859,8 +8960,8 @@ writeAshmem(buf: number[], size: number, offset: number): void 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) | 错误码ID | 错误信息 | - | ------- | -------- | - | 1900003 | write to ashmem failed | + | -------- | -------- | + | 1900003 | write to ashmem failed | **示例:** @@ -8896,9 +8997,9 @@ writeToAshmem(buf: number[], size: number, offset: number): boolean **返回值:** - | 类型 | 说明 | - | ------- | ----------------------------------------------------------------------------------------- | - | boolean | true:如果数据写入成功,false:在其他情况下,如数据写入越界或未获得写入权限。。 | + | 类型 | 说明 | + | ------- | ----------------------------------------------------------------------------- | + | boolean | true:如果数据写入成功,false:在其他情况下,如数据写入越界或未获得写入权限。 | **示例:** @@ -8936,9 +9037,9 @@ readAshmem(size: number, offset: number): number[] 以下错误码的详细介绍请参见[ohos.rpc错误码](../errorcodes/errorcode-rpc.md) - | 错误码ID | 错误信息 | + | 错误码ID | 错误信息 | | -------- | -------- | - | 1900004 | read from ashmem failed | + | 1900004 | read from ashmem failed | **示例:** @@ -8981,7 +9082,7 @@ readFromAshmem(size: number, offset: number): number[] **示例:** - ```ts + ``` ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); console.info("RpcTest map ashmem result is " + mapResult); @@ -8990,4 +9091,38 @@ readFromAshmem(size: number, offset: number): number[] console.log("RpcTest: write to Ashmem result is : " + writeResult); let readResult = ashmem.readFromAshmem(5, 0); console.log("RpcTest: read to Ashmem result is : " + readResult); - ``` \ No newline at end of file + ``` + +## 获取context + +**示例:** + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[Demo] MainAbility onCreate"); + globalThis.context = this.context; + } + onDestroy() { + console.log("[Demo] MainAbility onDestroy"); + } + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[Demo] MainAbility onWindowStageCreate"); + } + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + console.log("[Demo] MainAbility onWindowStageDestroy"); + } + onForeground() { + // Ability has brought to foreground + console.log("[Demo] MainAbility onForeground"); + } + onBackground() { + // Ability has back to background + console.log("[Demo] MainAbility onBackground"); + } + }; + ``` + 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 2ad6cfdbd0bb03dccb912bd2d67d67c6e24c1cd8..ec90213b049c0a140bea2d3837d6ee697ddab435 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-screen.md +++ b/zh-cn/application-dev/reference/apis/js-apis-screen.md @@ -744,7 +744,7 @@ try { | id | number | 是 | 否 | 屏幕的id。 | | parent | number | 是 | 否 | 屏幕所属群组的id。 | | supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | 是 | 否 | 屏幕支持的模式集合。 | -| activeModeIndex | number | 是 | 否 | 当前屏幕所处模式索引。 | +| activeModeIndex | number | 是 | 否 | 当前屏幕所处模式索引。模式索引的当前值和值的范围,会根据屏幕当前分辨率、刷新率和设备硬件差异产生变化。 | | orientation | [Orientation](#orientation) | 是 | 否 | 屏幕方向。 | | sourceMode10+ | [ScreenSourceMode](#screensourcemode10) | 是 | 否 | 屏幕来源模式。 | @@ -836,7 +836,7 @@ setScreenActiveMode(modeIndex: number, callback: AsyncCallback<void>): voi | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| modeIndex | number | 是 | 模式索引。 | +| modeIndex | number | 是 | 模式索引。模式索引的当前值和值的范围,会根据屏幕当前分辨率、刷新率和设备硬件差异产生变化。 | | callback | AsyncCallback<void> | 是 | 回调函数。当设置屏幕当前显示模式成功,err为undefined,否则为错误对象。 | **错误码:** @@ -874,7 +874,7 @@ setScreenActiveMode(modeIndex: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------- | -| modeIndex | number | 是 | 模式索引。 | +| modeIndex | number | 是 | 模式索引。模式索引的当前值和值的范围,会根据屏幕当前分辨率、刷新率和设备硬件差异产生变化。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index 1de7bc927994102e956ddd4d4a9fe9818174e9bf..0e34a4bffb1eefdc22b922f869219fe05ed62d3a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -31,7 +31,7 @@ on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse> | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | | type | [SensorId](#sensorid9).ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -71,7 +71,7 @@ on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Acceleromete | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).ACCELEROMETER_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerUncalibratedResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -112,7 +112,7 @@ on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, option | -------- | ----------------------------------------------- | ---- | --------------------------------------------------- | | type | [SensorId](#sensorid9).AMBIENT_LIGHT | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | | callback | Callback<[LightResponse](#lightresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LightResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -148,7 +148,7 @@ on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureR | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).AMBIENT_TEMPERATURE | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AmbientTemperatureResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -184,7 +184,7 @@ on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, option | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | | type | [SensorId](#sensorid9).BAROMETER | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | | callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为BarometerResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -220,7 +220,7 @@ on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: O | -------- | --------------------------------------------------- | ---- | ----------------------------------------------------- | | type | [SensorId](#sensorid9).GRAVITY | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | | callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GravityResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -260,7 +260,7 @@ on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | | type | [SensorId](#sensorid9).GYROSCOPE | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -301,7 +301,7 @@ on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalib | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).GYROSCOPE_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeUncalibratedResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -342,7 +342,7 @@ on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Option | -------- | --------------------------------------------- | ---- | -------------------------------------------------- | | type | [SensorId](#sensorid9).HALL | 是 | 传感器类型,该值固定为SensorId.HALL。 | | callback | Callback<[HallResponse](#hallresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HallResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -380,7 +380,7 @@ on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,option | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | | type | [SensorId](#sensorid9).HEART_RATE | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | | callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HeartRateResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -416,7 +416,7 @@ on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: | -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------ | | type | [SensorId](#sensorid9).HUMIDITY | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | | callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HumidityResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -455,7 +455,7 @@ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAcceleromete | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).LINEAR_ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELEROMETER。 | | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LinearAccelerometerResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -493,7 +493,7 @@ on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse> | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | | type | [SensorId](#sensorid9).MAGNETIC_FIELD | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -531,7 +531,7 @@ on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFie | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldUncalibratedResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -580,7 +580,7 @@ on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,opt | -------- | ----------------------------------------------------------- | ---- | --------------------------------------------------------- | | type | [SensorId](#sensorid9).ORIENTATION | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | | callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 回调函数,异步上报的传感器数据固定为OrientationResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -620,7 +620,7 @@ on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, option | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | | type | [SensorId](#sensorid9).PEDOMETER | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | | callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -651,7 +651,7 @@ on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionR | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).PEDOMETER_DETECTION | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerDetectionResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -687,7 +687,7 @@ on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, option | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | | type | [SensorId](#sensorid9).PROXIMITY | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | | callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为ProximityResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -724,7 +724,7 @@ on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse& | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).ROTATION_VECTOR | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 回调函数,异步上报的传感器数据固定为RotationVectorResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -764,7 +764,7 @@ on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionRes | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为SignificantMotionResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -801,7 +801,7 @@ on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse> | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | | type | [SensorId](#sensorid9).WEAR_DETECTION | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为WearDetectionResponse。 | -| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **错误码**: @@ -3851,7 +3851,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<Acceler | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER | 是 | 要订阅的加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -3883,7 +3883,7 @@ on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Line | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_LINEAR_ACCELERATION | 是 | 要订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | ### ACCELEROMETER_UNCALIBRATED(deprecated) @@ -3903,7 +3903,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 是 | 要订阅的未校准加速度计传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3935,9 +3935,10 @@ on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityRespons | -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_GRAVITY | 是 | 要订阅的重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | | callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); @@ -3966,7 +3967,7 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeRes | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE | 是 | 要订阅的陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3997,7 +3998,7 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<G | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 是 | 要订阅的未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4029,7 +4030,7 @@ on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<Sig | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 是 | 要订阅的大幅动作传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4058,7 +4059,7 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<Pe | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER_DETECTION | 是 | 要订阅的计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4087,7 +4088,7 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerRes | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER | 是 | 要订阅的计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | | callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4114,7 +4115,7 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<Ambi | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 是 | 要订阅的环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4142,7 +4143,7 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<Magneti | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD | 是 | 要订阅的磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4172,7 +4173,7 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callbac | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 是 | 要订阅的未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4204,7 +4205,7 @@ on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityRes | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_PROXIMITY | 是 | 要订阅的接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | | callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4231,7 +4232,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityRespo | -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_HUMIDITY | 是 | 要订阅的湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | | callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4259,7 +4260,7 @@ on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerRes | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_BAROMETER | 是 | 要订阅的气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | | callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4287,7 +4288,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, | -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_HALL | 是 | 要订阅的霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | | callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4314,7 +4315,7 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightRes | -------- | ------------------------------------------------------ | ---- | ----------------------------------------------------------- | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_LIGHT | 是 | 要订阅的环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | | callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4342,7 +4343,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<Orientatio | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_ORIENTATION | 是 | 要订阅的方向传感器类型为SENSOR_TYPE_ID_ORIENTATION | | callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4390,7 +4391,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<Rotatio | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_ROTATION_VECTOR | 是 | 要订阅的旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4420,7 +4421,7 @@ on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDet | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | [SensorType](#sensortype).SENSOR_TYPE_ID_WEAR_DETECTION | 是 | 要订阅的佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| options | [Options](#options) | 否 | 可选参数列表列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md index 28402007b002e0f214060f8dc9a629d2d042a311..a3f5ed1d72ab614ad2180c16468b793674b9f0c3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @@ -1,10 +1,10 @@ -# 用户界面外观 +# @ohos.uiAppearance (用户界面外观) 用户界面外观提供管理系统外观的一些基础能力,目前仅包括深浅色模式配置。 > **说明:** > -> 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > > 本模块接口为系统接口。 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 dace2c497344d7c126e240376c80b6ccf8f43872..0994ad1615e8dd2616eb543a394076d00ade2ba8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -66,7 +66,7 @@ import window from '@ohos.window'; | 名称 | 值 | 说明 | | -------------------------------- | ---- | ------------------------------------------------------------ | -| TYPE_SYSTEM | 0 | 表示系统默认区域。一般包括状态栏、导航栏和Dock栏,各设备系统定义可能不同。 | +| TYPE_SYSTEM | 0 | 表示系统默认区域。一般包括状态栏、导航栏,各设备系统定义可能不同。 | | TYPE_CUTOUT | 1 | 表示刘海屏区域。 | | TYPE_SYSTEM_GESTURE9+ | 2 | 表示手势区域。 | | TYPE_KEYBOARD9+ | 3 | 表示软键盘区域。 | @@ -2050,7 +2050,9 @@ try { setWindowLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void -设置窗口的布局是否为全屏显示状态,使用callback异步回调。 +设置窗口的布局是否为沉浸式布局,使用callback异步回调。 +沉浸式布局是指布局不避让状态栏与导航栏,组件可能产生与其重叠的情况。 +非沉浸式布局是指布局避让状态栏与导航栏,组件不会与其重叠。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2058,7 +2060,7 @@ setWindowLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback&l | 参数名 | 类型 | 必填 | 说明 | | ------------------ | ------------------------- | -- | --------- | -| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为全屏显示状态(该全屏状态下状态栏、导航栏仍然显示)。true表示全屏显示;false表示非全屏显示。 | +| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为沉浸式布局(该沉浸式布局状态栏、导航栏仍然显示)。true表示沉浸式布局;false表示非沉浸式布局。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -2091,7 +2093,9 @@ try { setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> -设置窗口的布局是否为全屏显示状态,使用Promise异步回调。 +设置窗口的布局是否为沉浸式布局,使用Promise异步回调。 +沉浸式布局是指布局不避让状态栏与导航栏,组件可能产生与其重叠的情况。 +非沉浸式布局是指布局避让状态栏与导航栏,组件不会与其重叠。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2099,7 +2103,7 @@ setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------------------ | ------- | -- | ------------------------------------------------------------------------------------------------ | -| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为全屏显示状态(该全屏状态下状态栏、导航栏仍然显示)。true表示全屏显示;false表示非全屏显示。 | +| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为沉浸式布局(该沉浸式布局状态栏、导航栏仍然显示)。true表示沉浸式布局;false表示非沉浸式布局。 | **返回值:** @@ -4159,7 +4163,7 @@ promise.then((pixelMap)=> { opacity(opacity: number): void -设置窗口透明度。 +设置窗口不透明度。仅支持在[自定义系统窗口的显示与隐藏动画](../../windowmanager/system-window-stage.md#自定义系统窗口的显示与隐藏动画)中使用。 **系统接口:** 此接口为系统接口。 @@ -4167,9 +4171,9 @@ opacity(opacity: number): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------ | ---- | --------------------- | -| opacity | number | 是 | 透明度,范围0.0~1.0。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------------------------------------------------------- | +| opacity | number | 是 | 不透明度,范围0.0~1.0。0.0表示完全透明,1.0表示完全不透明。 | **错误码:** @@ -4194,7 +4198,7 @@ try { scale(scaleOptions: ScaleOptions): void -设置窗口缩放参数。 +设置窗口缩放参数。仅支持在[自定义系统窗口的显示与隐藏动画](../../windowmanager/system-window-stage.md#自定义系统窗口的显示与隐藏动画)中使用。 **系统接口:** 此接口为系统接口。 @@ -4235,7 +4239,7 @@ try { rotate(rotateOptions: RotateOptions): void -设置窗口旋转参数。 +设置窗口旋转参数。仅支持在[自定义系统窗口的显示与隐藏动画](../../windowmanager/system-window-stage.md#自定义系统窗口的显示与隐藏动画)中使用。 **系统接口:** 此接口为系统接口。 @@ -4277,7 +4281,7 @@ try { translate(translateOptions: TranslateOptions): void -设置窗口平移参数。 +设置窗口平移参数。仅支持在[自定义系统窗口的显示与隐藏动画](../../windowmanager/system-window-stage.md#自定义系统窗口的显示与隐藏动画)中使用。 **系统接口:** 此接口为系统接口。 @@ -4285,9 +4289,9 @@ translate(translateOptions: TranslateOptions): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------------- | -------------------------------------- | ---- | ---------- | -| translateOptions | [TranslateOptions](#translateoptions9) | 是 | 平移参数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------------- | -------------------------------------- | ---- | -------------------- | +| translateOptions | [TranslateOptions](#translateoptions9) | 是 | 平移参数,单位为px。 | **错误码:** @@ -5381,7 +5385,7 @@ setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | 是 | 是否设为全屏状态(该全屏状态隐藏状态栏导航栏)。true表示全屏;false表示非全屏。 | +| isFullScreen | boolean | 是 | 是否设为全屏状态(该全屏状态隐藏状态栏导航栏)。true表示全屏;false表示非全屏。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** @@ -5437,7 +5441,9 @@ promise.then(()=> { setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void -设置窗口的布局是否为全屏显示状态,使用callback异步回调。 +设置窗口的布局是否为沉浸式布局,使用callback异步回调。 +沉浸式布局是指布局不避让状态栏与导航栏,组件可能产生与其重叠的情况。 +非沉浸式布局是指布局避让状态栏与导航栏,组件不会与其重叠。 > **说明:** > @@ -5449,7 +5455,7 @@ setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void | 参数名 | 类型 | 必填 | 说明 | | ------------------ | ------------------------- | ---- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为全屏显示状态(该全屏状态下状态栏、导航栏仍然显示)。true表示全屏;false表示非全屏。 | +| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为沉浸式布局(该沉浸式布局状态栏、导航栏仍然显示)。true表示沉浸式布局;false表示非沉浸式布局。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** @@ -5469,7 +5475,9 @@ windowClass.setLayoutFullScreen(isLayoutFullScreen, (err) => { setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> -设置窗口的布局是否为全屏显示状态,使用Promise异步回调。 +设置窗口的布局是否为沉浸式布局,使用Promise异步回调。 +沉浸式布局是指布局不避让状态栏与导航栏,组件可能产生与其重叠的情况。 +非沉浸式布局是指布局避让状态栏与导航栏,组件不会与其重叠。 > **说明:** > @@ -5481,7 +5489,7 @@ setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------------------ | ------- | ---- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为全屏显示状态(该全屏状态下状态栏、导航栏仍然显示)。true表示全屏;false表示非全屏。 | +| isLayoutFullScreen | boolean | 是 | 窗口的布局是否为沉浸式布局(该沉浸式布局状态栏、导航栏仍然显示)。true表示沉浸式布局;false表示非沉浸式布局。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-zlib.md b/zh-cn/application-dev/reference/apis/js-apis-zlib.md index 7c5a1c23bfae0d695629b0c4d51df172efd9a5dd..c49189019424cd9d4e1c02dc5b0c0f5b8e5ddf75 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-zlib.md +++ b/zh-cn/application-dev/reference/apis/js-apis-zlib.md @@ -172,6 +172,8 @@ try { } ``` +## zlib.compressFile9+ + compressFile(inFile: string, outFile: string, options: Options): Promise\; 压缩文件,压缩的结果通过promise返回,成功时返回null,失败时返回错误码。 @@ -233,9 +235,9 @@ decompressFile(inFile: string, outFile: string, options: Options, callback: Asyn | 参数名 | 类型 | 必填 | 说明 | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | 是 | 指定的待解压缩文件的文件路径,路径必须为沙箱路径,沙箱路径可以通过context获取,可参考[FA模型](js-apis-inner-app-context.md),[Stage模型](js-apis-inner-application-context.md)。 | -| outFile | string | 是 | 指定的解压后的目录路径。 | -| options | [Options](#options) | 是 | 解压的配置参数。 | -| AsyncCallback<**void**> | callback | 否 | 解压是的回调函数。 | +| outFile | string | 是 | 指定的解压后的文件夹路径,文件夹目录路径需要在系统中存在,不存在则会解压失败。路径必须为沙箱路径,沙箱路径可以通过context获取,具体方法可参考[application/context(Stage模型)](js-apis-inner-application-context.md)或 [app/context(FA模型)](js-apis-inner-app-context.md)。 | +| options | [Options](#options) | 是 | 解压的配置参数。 | +| AsyncCallback<**void**> | callback | 否 | 解压的回调函数。 | **相关错误码** @@ -253,7 +255,7 @@ decompressFile(inFile: string, outFile: string, options: Options, callback: Asyn // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; -let outFile = '/xxx'; +let outFileDir = '/xxx'; let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, @@ -261,7 +263,7 @@ let options = { }; try { - zlib.decompressFile(inFile, outFile, options, (errData) => { + zlib.decompressFile(inFile, outFileDir, options, (errData) => { if (errData !== null) { console.log(`errData is errCode:${errData.code} message:${errData.message}`); } @@ -271,6 +273,8 @@ try { } ``` +## zlib.decompressFile9+ + decompressFile(inFile: string, outFile: string, options: Options): Promise\; 解压文件,解压的结果通过promise返回,成功时返回null,失败时返回错误码。 @@ -282,8 +286,8 @@ decompressFile(inFile: string, outFile: string, options: Options): Promise\ { + zlib.decompressFile(inFile, outFileDir, options).then((data) => { console.info('decompressFile success'); }).catch((errData) => { console.log(`errData is errCode:${errData.code} message:${errData.message}`); diff --git a/zh-cn/application-dev/reference/arkui-js-lite/js-framework-file.md b/zh-cn/application-dev/reference/arkui-js-lite/js-framework-file.md index f79c583bd930c9ba0439b80bef36aadf96d60fc2..77b4940269728279a8a07fcbcbfcc17f5f1c19c9 100644 --- a/zh-cn/application-dev/reference/arkui-js-lite/js-framework-file.md +++ b/zh-cn/application-dev/reference/arkui-js-lite/js-framework-file.md @@ -20,18 +20,16 @@ JS FA应用的JS模块(entry/src/main/js/module)的典型开发目录结构如 各个文件夹的作用: - app.js文件用于全局JavaScript逻辑和应用生命周期管理。 - - pages目录用于存放所有组件页面。 - - common目录用于存放公共资源文件,比如:媒体资源和JS文件。 +- i18n目录用于配置不同语言场景资源内容,比如应用文本词条,图片路径等资源。 > **说明:** -> - 如下文件夹是开发保留文件夹,不可重命名: > +> - i18n是开发保留文件夹,不可重命名。 > -> -> -> - 在使用DevEco Studio进行应用开发时,目录结构中的可选文件夹需要开发者根据实际情况自行创建。 +> +>- 在使用DevEco Studio进行应用开发时,目录结构中的可选文件夹需要开发者根据实际情况自行创建。 ## 文件访问规则 @@ -62,6 +60,14 @@ JS FA应用的JS模块(entry/src/main/js/module)的典型开发目录结构如 | 格式 | 支持版本 | 支持的文件类型 | | -------- | -------- | -------- | -| BMP | API Version 3+ | .bmp | -| JPEG | API Version 3+ | .jpg | -| PNG | API Version 3+ | .png | +| BMP | API Version 4+ | .bmp | +| JPEG | API Version 4+ | .jpg | +| PNG | API Version 4+ | .png | + +## 存储目录定义 + +从API Version 5开始,[image](js-components-basic-image.md)组件支持应用私有目录内的图片资源访问。 + +| 目录类型 | 路径前缀 | 访问可见性 | 说明 | +| ------------ | --------------- | ------------ | --------------------------------------------------- | +| 应用私有目录 | internal://app/ | 仅本应用可见 | 目录随应用卸载删除,路径禁止使用../等方式访问父目录 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/figures/text.png b/zh-cn/application-dev/reference/arkui-js/figures/js-text.png similarity index 100% rename from zh-cn/application-dev/reference/arkui-js/figures/text.png rename to zh-cn/application-dev/reference/arkui-js/figures/js-text.png diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker-view.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker-view.md index d5311a381b6e5cc61d8e6b10b56109645a68039d..e686e7e6f2acea233acccef2d8ea35770a0714a8 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker-view.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker-view.md @@ -120,228 +120,232 @@ ## 示例 -1. 文本选择器 - ```html - -
- - 选中值:{{value}} 选中下标: {{index}} - - -
- ``` - - ```css - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 50%; - } - .title { - font-size: 30px; - text-align: center; - margin-top: 50%; - } - ``` - - ```js - /* xxx.js */ - export default { - data: { - options: ['选项1', '选项2', '选项3'], - value: "选项1", - index: 0 - }, - handleChange(data) { - this.value = data.newValue; - this.index = data.newSelected; - }, - } - ``` - ![picker-view0](figures/picker-view0.gif) - -2. 时间选择器 - ```html - -
- - Selected:{{time}} - - -
- ``` - - ```css - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 50%; - } - .title { - font-size: 31px; - text-align: center; - margin-top: 50%; - } - ``` - - ```js - /* xxx.js */ - export default { - data: { - defaultTime: "", - time: "", - }, - onInit() { - this.defaultTime = this.now(); - }, - handleChange(data) { - this.time = this.concat(data.hour, data.minute); - }, - now() { - const date = new Date(); - const hours = date.getHours(); - const minutes = date.getMinutes(); - return this.concat(hours, minutes); - }, - fill(value) { - return (value > 9 ? "" : "0") + value; - }, - concat(hours, minutes) { - return `${this.fill(hours)}:${this.fill(minutes)}`; - }, - } - ``` - - ![picker-view1](figures/picker-view1.gif) - -3. 日期选择器 - ```html - -
- - Selected:{{date}} - - -
- ``` - - ```css - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 50%; - } - .title { - font-size: 31px; - text-align: center; - margin-top: 50%; - } - ``` - - ```js - /* xxx.js */ - export default { - data: { - date: "", - }, - handleChange(data) { - this.date = data.year + "年" + data.month + "月" + data.day + "日"; - }, - } - ``` - ![picker-view2](figures/picker-view2.gif) - -4. 日期时间选择器 - ```html - -
- - Selected:{{datetime}} - - -
- ``` - - ```css - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 50%; - } - .title { - font-size: 31px; - text-align: center; - margin-top: 50%; - } - ``` - - ```js - /* xxx.js */ - export default { - data: { - datetime: "", - }, - handleChange(data) { - this.datetime = data.year + "年" + data.month + "月" + data.day + "日" + data.hour + "时" + data.minute + "分"; - }, - } - ``` - ![picker-view3](figures/picker-view3.gif) - -5. 多列文本选择器 - - ```html - -
- - Selected:{{ value }} - - -
- ``` - - ```css - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 50%; - } - .title { - font-size: 31px; - text-align: center; - margin-top: 50%; - } - ``` - - ```js - /* xxx.js */ - export default { - data: { - multitext: [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9], - ], - value: "" - }, - handleChange(data) { - this.value = data.column + "列," + "值为" + data.newValue + ",下标为" + data.newSelected; - }, - } - ``` - ![picker-view4](figures/picker-view4.gif) \ No newline at end of file +### 文本选择器 + +```html + +
+ + 选中值:{{value}} 选中下标: {{index}} + + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 50%; +} +.title { + font-size: 30px; + text-align: center; + margin-top: 50%; +} +``` + +```js +/* xxx.js */ +export default { + data: { + options: ['选项1', '选项2', '选项3'], + value: "选项1", + index: 0 + }, + handleChange(data) { + this.value = data.newValue; + this.index = data.newSelected; + }, +} +``` +![picker-view0](figures/picker-view0.gif) + +### 时间选择器 + +```html + +
+ + Selected:{{time}} + + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 50%; +} +.title { + font-size: 31px; + text-align: center; + margin-top: 50%; +} +``` + +```js +/* xxx.js */ +export default { + data: { + defaultTime: "", + time: "", + }, + onInit() { + this.defaultTime = this.now(); + }, + handleChange(data) { + this.time = this.concat(data.hour, data.minute); + }, + now() { + const date = new Date(); + const hours = date.getHours(); + const minutes = date.getMinutes(); + return this.concat(hours, minutes); + }, + fill(value) { + return (value > 9 ? "" : "0") + value; + }, + concat(hours, minutes) { + return `${this.fill(hours)}:${this.fill(minutes)}`; + }, +} +``` + +![picker-view1](figures/picker-view1.gif) + +### 日期选择器 + +```html + +
+ + Selected:{{date}} + + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 50%; +} +.title { + font-size: 31px; + text-align: center; + margin-top: 50%; +} +``` + +```js +/* xxx.js */ +export default { + data: { + date: "", + }, + handleChange(data) { + this.date = data.year + "年" + data.month + "月" + data.day + "日"; + }, +} +``` +![picker-view2](figures/picker-view2.gif) + +### 日期时间选择器 + +```html + +
+ + Selected:{{datetime}} + + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 50%; +} +.title { + font-size: 31px; + text-align: center; + margin-top: 50%; +} +``` + +```js +/* xxx.js */ +export default { + data: { + datetime: "", + }, + handleChange(data) { + this.datetime = data.year + "年" + data.month + "月" + data.day + "日" + data.hour + "时" + data.minute + "分"; + }, +} +``` +![picker-view3](figures/picker-view3.gif) + +### 多列文本选择器 + +```html + +
+ + Selected:{{ value }} + + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 50%; +} +.title { + font-size: 31px; + text-align: center; + margin-top: 50%; +} +``` + +```js +/* xxx.js */ +export default { + data: { + multitext: [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ], + value: "" + }, + handleChange(data) { + this.value = data.column + "列," + "值为" + data.newValue + ",下标为" + data.newSelected; + }, +} +``` +![picker-view4](figures/picker-view4.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-text.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-text.md index d3b8dbe68f3073c3cde2cee2c1ad0b85943a1458..61f266a3d790cbdb92721fc1d446d860ba545bde 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-text.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-text.md @@ -76,7 +76,7 @@ ## 示例 -1. +1. ​ ```html
@@ -137,5 +137,5 @@ ``` -![zh-cn_image_0000001167823076](figures/text.png) +![zh-cn_image_0000001167823076](figures/js-text.png) diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index a729e82a2490d80e25295f5f83173831e6fe4765..80e1fced38bfce12740fe9c04130e9748aeaf8dc 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -1025,7 +1025,7 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ```html
- +
``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-list-item-group.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-list-item-group.md index 1fdb3cbdc86883d35884ff080e716f66407c777c..0982188e5582a0edc675a2fbb1c889ff272cae75 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-list-item-group.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-list-item-group.md @@ -1,7 +1,7 @@ # list-item-group > **说明:** -> 从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 <[list](../arkui-js/js-components-container-list.md)>的子组件,用来展示分组,宽度默认充满list组件。 @@ -30,7 +30,7 @@ > **说明:** > -> - 通用属性中的id用来标识一个group。list中相关的函数的入参以及事件的信息皆以此标识一个唯一的group。 +> - 通用属性中的id用来标识一个group。list中相关的函数的入参以及事件的信息皆以此标识一个唯一的group。 ## 样式 @@ -125,48 +125,55 @@ // xxx.js import promptAction from '@ohos.promptAction'; export default { - data: { - direction: 'column', - list: [], - listAdd: [] - }, - onInit() { - this.list = [] - this.listAdd = [] - for (var i = 1; i <= 3; i++) { - var dataItem = { - value: 'GROUP' + i, - }; - this.list.push(dataItem); + data: { + direction: 'column', + list: [], + listAdd: [] + }, + onInit() { + this.list = [] + this.listAdd = [] + for (var i = 1; i <= 3; i++) { + var dataItem = { + value: 'GROUP' + i, + }; + this.list.push(dataItem); + } + }, + collapseOne(e) { + this.$element('mylist').collapseGroup({ + groupid: 'GROUP1' + }) + }, + expandOne(e) { + this.$element('mylist').expandGroup({ + groupid: 'GROUP1' + }) + }, + collapseAll(e) { + this.$element('mylist').collapseGroup({ + groupid: '' + }) + }, + expandAll(e) { + this.$element('mylist').expandGroup({ + groupid: '' + }) + }, + collapse(e) { + promptAction.showToast({ + message: 'Close ' + e.groupid + }) + }, + expand(e) { + promptAction.showToast({ + message: 'Open ' + e.groupid + }) } - }, - collapseOne(e) { - this.$element('mylist').collapseGroup({ - groupid: 'GROUP1' - }) - }, - expandOne(e) { - this.$element('mylist').expandGroup({ - groupid: 'GROUP1' - }) - }, - collapseAll(e) { - this.$element('mylist').collapseGroup() - }, - expandAll(e) { - this.$element('mylist').expandGroup() - }, - collapse(e) { - promptAction.showToast({ - message: 'Close ' + e.groupid - }) - }, - expand(e) { - promptAction.showToast({ - message: 'Open ' + e.groupid - }) - } } + + + ``` ![zh-cn_image_0000001127284978](figures/zh-cn_image_0000001127284978.gif) diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md index 75c4249b57fe899efe5110456a38cf8948f5dff1..4932696e40bd61e59713be726d9ebbdd246edff5 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md @@ -130,7 +130,7 @@ text { ```js // xxx.js -import prompt from '@system.prompt'; +import prompt from '@ohos.promptAction'; export default { data: { diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/LoadingProgress.gif b/zh-cn/application-dev/reference/arkui-ts/figures/LoadingProgress.gif new file mode 100644 index 0000000000000000000000000000000000000000..90d9c7bba27ef616fb6bfdea407358df25ac6f91 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/LoadingProgress.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif b/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif index b00b7fad991682b2cd81b0afdd149a3b7f73dc49..0d83b0a08128d1e43f3fa633eb72cca66114a3d6 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/datePicker.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/drag-drop.gif b/zh-cn/application-dev/reference/arkui-ts/figures/drag-drop.gif new file mode 100644 index 0000000000000000000000000000000000000000..05b0d0a29dfff526df15e64914f77d598124581c Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/drag-drop.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/ifButton.gif b/zh-cn/application-dev/reference/arkui-ts/figures/ifButton.gif new file mode 100644 index 0000000000000000000000000000000000000000..d92e24eadd8b744c17ee098ae876c2e9ef605325 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/ifButton.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/imagespan.png b/zh-cn/application-dev/reference/arkui-ts/figures/imagespan.png new file mode 100644 index 0000000000000000000000000000000000000000..6b0684be4d1e785c4301f97ca50016b0ccd83623 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/imagespan.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/loadProgress.jpeg b/zh-cn/application-dev/reference/arkui-ts/figures/loadProgress.jpeg deleted file mode 100644 index 141bc03c7528681e90fc3ed91b4c05611355e092..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/loadProgress.jpeg and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/rating.gif b/zh-cn/application-dev/reference/arkui-ts/figures/rating.gif index 58cab3e9455db71825d0533d5619a2e12f8b0975..fe6a69b71ecd5d8094d2431e39ff9b07ca3852b0 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/rating.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/rating.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422904.jpg b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422904.jpg deleted file mode 100644 index bf5c3a49c58818ec9dec43db3c2d4c5e16949a94..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422904.jpg and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422904.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422904.png new file mode 100644 index 0000000000000000000000000000000000000000..0bbc2e605057072db375a583813ba69a67de34bf Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001174422904.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001232775585.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001232775585.gif index 070ae9d042d5211b2ccc6c187ec0f87a90d2c963..36e5cf928d08d719eab8bb0c417da0bc23472798 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001232775585.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001232775585.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001239032420.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001239032420.png new file mode 100644 index 0000000000000000000000000000000000000000..faf9e54e927094688fc3d086903d27cc895760f1 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001239032420.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md index ffb0167d050e18a7deefb55d0a14f91f5945ddfa..8d436ee457008f7271c4cf479c2f69fc6c145261 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -54,8 +54,6 @@ ## TouchType -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ------ | ------------------------------ | | Down | 手指按下时触发。 | @@ -65,8 +63,6 @@ ## MouseButton -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ------- | ---------------- | | Left | 鼠标左键。 | @@ -78,8 +74,6 @@ ## MouseAction -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ------- | -------------- | | Press | 鼠标按键按下。 | @@ -109,7 +103,7 @@ ## AnimationStatus -从API version 9开始,该接口支持在ArkTS卡片中使用。 +从API version 10开始,该接口支持在ArkTS卡片中使用。 | 名称 | 描述 | | ------- | ------------------ | @@ -120,7 +114,7 @@ ## FillMode -从API version 9开始,该接口支持在ArkTS卡片中使用。 +从API version 10开始,该接口支持在ArkTS卡片中使用。 | 名称 | 描述 | | --------- | ------------------------------------------------------------ | @@ -142,8 +136,6 @@ ## KeyType -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ---- | ---------- | | Down | 按键按下。 | @@ -151,8 +143,6 @@ ## KeySource -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | -------- | -------------------- | | Unknown | 输入设备类型未知。 | @@ -172,8 +162,6 @@ ## Week -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | -------- | ---------------------- | | Mon | 星期一 | @@ -242,8 +230,6 @@ ## RelateType -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ------ | ------------------------------- | | FILL | 缩放当前子组件以填充满父组件 | @@ -307,12 +293,12 @@ | 名称 | 描述 | | -------- | ------------------------------------------------------------ | -| Auto | 使用Flex容器中默认配置。 | -| Start | 元素在Flex容器中,交叉轴方向首部对齐。 | -| Center | 元素在Flex容器中,交叉轴方向居中对齐。 | -| End | 元素在Flex容器中,交叉轴方向底部对齐。 | -| Stretch | 元素在Flex容器中,交叉轴方向拉伸填充。容器为Flex且设置Wrap为FlexWrap.Wrap或FlexWrap.WrapReverse时,元素拉伸到与当前行/列交叉轴长度最长的元素尺寸。其余情况在元素未设置尺寸时,拉伸到容器尺寸。 | -| Baseline | 元素在Flex容器中,交叉轴方向文本基线对齐。 | +| Auto | 使用Flex、GridRow容器中默认配置。 | +| Start | 元素在Flex、GridRow容器中,交叉轴方向首部对齐。 | +| Center | 元素在Flex、GridRow容器中,交叉轴方向居中对齐。 | +| End | 元素在Flex、GridRow容器中,交叉轴方向底部对齐。 | +| Stretch | 元素在Flex、GridRow容器中,交叉轴方向拉伸填充。容器为Flex且设置Wrap为FlexWrap.Wrap或FlexWrap.WrapReverse时,元素拉伸到与当前行/列交叉轴长度最长的元素尺寸。其余情况在元素未设置尺寸时,拉伸到容器尺寸。 | +| Baseline | 元素在Flex、GridRow容器中,交叉轴方向文本基线对齐。 | ## FlexDirection @@ -384,8 +370,6 @@ ## SharedTransitionEffectType -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ----------- | ---------- | | Static | 目标页面元素的位置保持不变,可以配置透明度动画。目前,只有为重定向到目标页面而配置的静态效果才会生效。 | @@ -458,8 +442,6 @@ ## ResponseType8+ -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ---------- | -------------------------- | | LongPress | 通过长按触发菜单弹出。 | @@ -467,8 +449,6 @@ ## HoverEffect8+ -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | --------- | ---------------------------- | | Auto | 使用组件的系统默认悬浮效果。 | @@ -478,8 +458,6 @@ ## Placement8+ -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ------------- | ------------------------------------------------------------ | | Left | 气泡提示位于组件左侧,与组件左侧中心对齐。 | @@ -507,8 +485,6 @@ ## HitTestMode9+ -从API version 9开始,该接口支持在ArkTS卡片中使用。 - | 名称 | 描述 | | ----------- | -------------------- | | Default | 自身节点和子节点都响应触摸事件的命中测试,但会阻止被该节点屏蔽的其他节点的命中测试。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md index 981b1dac65ef09d51faf3ddfa4e0be3f109dc9ac..b5c9301887044d2bd3c4d709e12f02efefe4b1d3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -80,6 +80,8 @@ 支持[通用事件](ts-universal-events-click.md)。 ## 示例 +### 示例1 + ```ts // xxx.ets @Entry @@ -136,4 +138,34 @@ struct ButtonExample { } ``` -![button](figures/button.gif) \ No newline at end of file +![button](figures/button.gif) + +### 示例2 + +```ts +// xxx.ets +@Entry +@Component +struct SwipeGestureExample { + @State count: number = 0 + + build() { + Column() { + Text(`${this.count}`) + .fontSize(30) + .onClick(() => { + this.count++ + }) + if (this.count <= 0) { + Button('count is negative').fontSize(30).height(50) + } else if (this.count % 2 === 0) { + Button('count is even').fontSize(30).height(50) + } else { + Button('count is odd').fontSize(30).height(50) + } + }.height('100%').width('100%').justifyContent(FlexAlign.Center) + } +} +``` + +![ifButton](figures/ifButton.gif) \ No newline at end of file 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 0b161e3976cb3be23829e420f1f2f8c2d3bdeb07..d21ed937c49f9d90109c24aca11514a46424fb4a 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 @@ -4,7 +4,7 @@ > **说明:** > -> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 ## 子组件 @@ -20,45 +20,45 @@ DatePicker(options?: {start?: Date, end?: Date, selected?: Date}) **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| -------- | -------- | ------------- | -------- | -| start | Date | 否 | 指定选择器的起始日期。
默认值:Date('1970-1-1') | -| end | Date | 否 | 指定选择器的结束日期。
默认值:Date('2100-12-31') | -| selected | Date | 否 | 设置选中项的日期。
默认值:当前系统日期 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | ---- | ---- | -------------------------------------- | +| start | Date | 否 | 指定选择器的起始日期。
默认值:Date('1970-1-1') | +| end | Date | 否 | 指定选择器的结束日期。
默认值:Date('2100-12-31') | +| selected | Date | 否 | 设置选中项的日期。
默认值:当前系统日期 | ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 名称 | 参数类型 | 描述 | -| ------| -------------- | -------- | -| lunar | boolean | 日期是否显示农历。
- true:展示农历。
- false:不展示农历。
默认值:false | -| disappearTextStyle10+ | [PickerTextStyle](#pickertextstyle10类型说明) | 设置所有选项中最上和最下两个选项的文本颜色、字号、字体粗细。 | -| textStyle10+ | [PickerTextStyle](#pickertextstyle10类型说明) | 设置所有选项中除了最上、最下及选中项以外的文本颜色、字号、字体粗细。 | -| selectedTextStyle10+ | [PickerTextStyle](#pickertextstyle10类型说明) | 设置选中项的文本颜色、字号、字体粗细。 | +| 名称 | 参数类型 | 描述 | +| -------------------------------- | ---------------------------------------- | ---------------------------------------- | +| lunar | boolean | 日期是否显示农历。
- true:展示农历。
- false:不展示农历。
默认值:false | +| disappearTextStyle10+ | [PickerTextStyle](#pickertextstyle10类型说明) | 设置所有选项中最上和最下两个选项的文本颜色、字号、字体粗细。 | +| textStyle10+ | [PickerTextStyle](#pickertextstyle10类型说明) | 设置所有选项中除了最上、最下及选中项以外的文本颜色、字号、字体粗细。 | +| selectedTextStyle10+ | [PickerTextStyle](#pickertextstyle10类型说明) | 设置选中项的文本颜色、字号、字体粗细。 | ## PickerTextStyle10+类型说明 -| 参数名 | 参数类型 | 必填 | 参数描述 | -| ------ | ------------------------------------------ | ---- | -------------------------------------------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 文本颜色。 | -| font | [Font](ts-types.md#font) | 否 | 文本样式,picker只支持字号、字体粗细的设置。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ----- | ---------------------------------------- | ---- | ------------------------- | +| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 文本颜色。 | +| font | [Font](ts-types.md#font) | 否 | 文本样式,picker只支持字号、字体粗细的设置。 | ## 事件 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: -| 名称 | 功能描述 | -| -------- | -------- | +| 名称 | 功能描述 | +| ---------------------------------------- | ----------- | | onChange(callback: (value: DatePickerResult) => void) | 选择日期时触发该事件。 | ## DatePickerResult对象说明 -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | -| year | number | 选中日期的年。 | +| 名称 | 参数类型 | 描述 | +| ----- | ------ | --------------------------- | +| year | number | 选中日期的年。 | | month | number | 选中日期的月(0~11),0表示1月,11表示12月。 | -| day | number | 选中日期的日。 | +| day | number | 选中日期的日。 | ## 示例 @@ -75,7 +75,7 @@ struct DatePickerExample { build() { Column() { Button('切换公历农历') - .margin({ top: 30 }) + .margin({ top: 30, bottom: 30 }) .onClick(() => { this.isLunar = !this.isLunar }) 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 e50d18cf966e6bafdd4367aa177eef35a69c6f78..d1d6bf93edd65162cffd1c4aa9442cdd297a78ac 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 @@ -369,7 +369,7 @@ import context from '@ohos.app.ability.common'; struct LoadImageExample { @State resourcesPath: string = '' @State sandboxPath: string = '' - context: context.UIAbility = getContext(this) as context.UIAbilityContext + context: context.UIAbilityContext = getContext(this) as context.UIAbilityContext build() { Column() { @@ -396,6 +396,12 @@ struct LoadImageExample { Image(this.resourcesPath) .width(100) .height(100) + .colorFilter([ + 0.30, 0.59, 0.11, 0, 0, + 0.30, 0.59, 0.11, 0, 0, + 0.30, 0.59, 0.11, 0, 0, + 0, 0, 0, 1.0, 0 + ]) Text(`沙箱图片路径:${this.sandboxPath}`) .fontSize(20) .margin({ bottom: 10 }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md new file mode 100644 index 0000000000000000000000000000000000000000..c17c931c135b54f67aef3fcd25271eef61784dfa --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imagespan.md @@ -0,0 +1,96 @@ +# ImageSpan + +[Text](ts-basic-components-text.md)组件的子组件,用于显示行内图片。 + +> **说明:** +> +> 该组件从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +无 + + +## 接口 + +ImageSpan(value: ResourceStr | PixelMap) + +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| value | [ResourceStr](ts-types.md#ResourceStr) \| [PixelMap](../apis/js-apis-image.md#pixelmap7)  | 是 | 图片的数据源,支持本地图片和网络图片。
当使用相对路径引用图片资源时,例如`ImageSpan("common/test.jpg")`,不支持跨包/跨模块调用该ImageSpan组件,建议使用`$r`方式来管理需全局使用的图片资源。
\- 支持的图片格式包括png、jpg、bmp、svg和gif。
\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]`为`Base64`字符串数据。
\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。 | + + +## 属性 + +[通用属性](ts-universal-attributes-size.md)方法仅支持宽(width)、高(height)和size。 + +| 名称 | 参数类型 | 描述 | +| -------- | -------- | -------- | +| verticalAlign | [ImageSpanAlignment](#imagespanalignment) | 图片基于文本的对齐方式。 | +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover | + +## ImageSpanAlignment + +| 名称 | 描述 | +| -------- | ------------------------------ | +| TOP | 图片上边沿与文本上边沿对齐。 | +| CENTER | 图片中间与文本中间对齐。 | +| BOTTOM | 图片下边沿与文本下边沿对齐。 | +| BASELINE | 图片下边沿与文本BaseLine对齐。 | + +## 事件 + +通用事件仅支持[点击事件](ts-universal-attributes-click.md)。 + +## 示例 + +```ts +// xxx.ets +@Entry +@Component +struct SpanExample { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start}) { + Text() { + Span('This is the Span and ImageSpan component').fontSize(25).textCase(TextCase.Normal) + .decoration({ type: TextDecorationType.None, color: Color.Pink }) + }.width('100%') + Text() { + ImageSpan($r('app.media.icon')) + .width('200px') + .height('200px') + .objectFit(ImageFit.Fill) + .verticalAlign(ImageSpanAlignment.CENTER) + Span('I am LineThrough-span') + .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }).fontSize(25) + ImageSpan($r('app.media.icon')) + .width('50px') + .height('50px') + .verticalAlign(ImageSpanAlignment.TOP) + Span('I am Underline-span') + .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25) + ImageSpan($r('app.media.icon')) + .size({width:'100px', height:'100px'}) + .verticalAlign(ImageSpanAlignment.BASELINE) + Span('I am Underline-span') + .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25) + ImageSpan($r('app.media.icon')) + .width('70px') + .height('70px') + .verticalAlign(ImageSpanAlignment.BOTTOM) + Span('I am Underline-span') + .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(50) + } + .width('100%') + .backgroundColor(Color.Orange) + .textIndent(50) + }.width('100%').height('100%').padding({ left: 0, right: 0, top: 0 }) + } +} +``` + +![imagespan](figures/imagespan.png) + diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index b75519c1419a2d30ec0b4c2ae34112f2ab73b502..0a76407d200709c72058d0c1a788bdc5ed7efdb4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -43,4 +43,4 @@ struct LoadingProgressExample { } ``` -![loadProgress](figures/loadProgress.jpeg) +![LoadingProgress](figures/LoadingProgress.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index ec3dbe733aeaff4e430c166757af68535d35bf9a..4b3a3950f10962b34f6a6f59812fb677c5c6d82e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -21,86 +21,86 @@ Navigation() 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 名称 | 参数类型 | 描述 | -| -------------- | ---------------------------------------- | ---------------------------------------- | -| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle类型说明)9+ \| [NavigationCustomTitle](#navigationcustomtitle类型说明)9+ | 页面标题。
**说明:**
使用NavigationCustomTitle类型设置height高度时,titleMode属性不会生效。
字符串超长时,如果不设置副标题,先缩小再换行(2行)最后...截断。如果设置副标题,先缩小最后...截断。 | -| subTitledeprecated | string | 页面副标题。不设置时不显示副标题。从API Version 9开始废弃,建议使用title代替。 | -| menus | Array<[NavigationMenuItem](#navigationmenuitem类型说明)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 页面右上角菜单。不设置时不显示菜单项。使用Array<[NavigationMenuItem](#navigationmenuitem类型说明)> 写法时,竖屏最多支持显示3个图标,横屏最多支持显示5个图标,多余的图标会被放入自动生成的更多图标。 | -| titleMode | [NavigationTitleMode](#navigationtitlemode枚举说明) | 页面标题栏显示模式。
默认值:NavigationTitleMode.Free | -| toolBar | [object](#object类型说明) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 设置工具栏内容。不设置时不显示工具栏。
items: 工具栏所有项。
**说明:**
items均分底部工具栏,在每个均分内容区布局文本和图标,文本超长时,逐级缩小,缩小之后换行,最后...截断。 | -| hideToolBar | boolean | 隐藏工具栏。
默认值:false
true: 隐藏工具栏。
false: 显示工具栏。 | -| hideTitleBar | boolean | 隐藏标题栏。
默认值:false
true: 隐藏标题栏。
false: 显示标题栏。 | -| hideBackButton | boolean | 隐藏返回键。
默认值:false
true: 隐藏返回键。
false: 显示返回键。
不支持隐藏NavDestination组件标题栏中的返回图标。
**说明:**
返回键键仅针对titleMode为NavigationTitleMode.Mini时才生效。 | -| navBarWidth9+ | [Length](ts-types.md#length) | 导航栏宽度。
默认值:200
单位:vp
**说明:**
仅在Navigation组件分栏时生效。 | -| navBarPosition9+ | [NavBarPosition](#navbarposition枚举说明) | 导航栏位置。
默认值:NavBarPosition.Start
**说明:**
仅在Navigation组件分栏时生效。 | -| mode9+ | [NavigationMode](#navigationmode枚举说明) | 导航栏的显示模式。
默认值:NavigationMode.Auto
自适应:基于组件宽度自适应单栏和双栏。 | -| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | 设置导航栏返回图标。不支持隐藏NavDestination组件标题栏中的返回图标。| -| hideNavBar9+ | boolean | 是否显示导航栏(仅在mode为NavigationMode.Split时生效)。 | +| 名称 | 参数类型 | 描述 | +| ----------------------------- | ---------------------------------------- | ---------------------------------------- | +| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle类型说明)9+ \| [NavigationCustomTitle](#navigationcustomtitle类型说明)9+ | 页面标题。
**说明:**
使用NavigationCustomTitle类型设置height高度时,titleMode属性不会生效。
字符串超长时,如果不设置副标题,先缩小再换行(2行)最后...截断。如果设置副标题,先缩小最后...截断。 | +| subTitledeprecated | string | 页面副标题。不设置时不显示副标题。从API Version 9开始废弃,建议使用title代替。 | +| menus | Array<[NavigationMenuItem](#navigationmenuitem类型说明)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 页面右上角菜单。不设置时不显示菜单项。使用Array<[NavigationMenuItem](#navigationmenuitem类型说明)> 写法时,竖屏最多支持显示3个图标,横屏最多支持显示5个图标,多余的图标会被放入自动生成的更多图标。 | +| titleMode | [NavigationTitleMode](#navigationtitlemode枚举说明) | 页面标题栏显示模式。
默认值:NavigationTitleMode.Free | +| toolBar | [object](#object类型说明) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 设置工具栏内容。不设置时不显示工具栏。
items: 工具栏所有项。
**说明:**
items均分底部工具栏,在每个均分内容区布局文本和图标,文本超长时,逐级缩小,缩小之后换行,最后...截断。 | +| hideToolBar | boolean | 隐藏工具栏。
默认值:false
true: 隐藏工具栏。
false: 显示工具栏。 | +| hideTitleBar | boolean | 隐藏标题栏。
默认值:false
true: 隐藏标题栏。
false: 显示标题栏。 | +| hideBackButton | boolean | 隐藏返回键。
默认值:false
true: 隐藏返回键。
false: 显示返回键。
不支持隐藏NavDestination组件标题栏中的返回图标。
**说明:**
返回键键仅针对titleMode为NavigationTitleMode.Mini时才生效。 | +| navBarWidth9+ | [Length](ts-types.md#length) | 导航栏宽度。
默认值:200
单位:vp
**说明:**
仅在Navigation组件分栏时生效。 | +| navBarPosition9+ | [NavBarPosition](#navbarposition枚举说明) | 导航栏位置。
默认值:NavBarPosition.Start
**说明:**
仅在Navigation组件分栏时生效。 | +| mode9+ | [NavigationMode](#navigationmode枚举说明) | 导航栏的显示模式。
默认值:NavigationMode.Auto
自适应:基于组件宽度自适应单栏和双栏。 | +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | 设置导航栏返回图标。不支持隐藏NavDestination组件标题栏中的返回图标。 | +| hideNavBar9+ | boolean | 是否显示导航栏(仅在mode为NavigationMode.Split时生效)。 | ## NavigationMenuItem类型说明 -| 名称 | 类型 | 必填 | 描述 | -| ------ | ----------------------- | ---- | ------------------------------ | -| value | string | 是 | 菜单栏单个选项的显示文本。 | -| icon | string | 否 | 菜单栏单个选项的图标资源路径。 | -| action | () => void | 否 | 当前选项被选中的事件回调。 | +| 名称 | 类型 | 必填 | 描述 | +| ------ | ----------------------- | ---- | --------------- | +| value | string | 是 | 菜单栏单个选项的显示文本。 | +| icon | string | 否 | 菜单栏单个选项的图标资源路径。 | +| action | () => void | 否 | 当前选项被选中的事件回调。 | ## object类型说明 -| 名称 | 类型 | 必填 | 描述 | -| ------ | ----------------------- | ---- | ------------------------------ | -| value | string | 是 | 工具栏单个选项的显示文本。 | -| icon | string | 否 | 工具栏单个选项的图标资源路径。 | -| action | () => void | 否 | 当前选项被选中的事件回调。 | +| 名称 | 类型 | 必填 | 描述 | +| ------ | ----------------------- | ---- | --------------- | +| value | string | 是 | 工具栏单个选项的显示文本。 | +| icon | string | 否 | 工具栏单个选项的图标资源路径。 | +| action | () => void | 否 | 当前选项被选中的事件回调。 | ## NavigationTitleMode枚举说明 | 名称 | 描述 | | ---- | ---------------------------------------- | | Free | 当内容为可滚动组件时,标题随着内容向上滚动而缩小(子标题的大小不变、淡出)。向下滚动内容到顶时则恢复原样。 | -| Mini | 固定为小标题模式。 | -| Full | 固定为大标题模式。 | +| Mini | 固定为小标题模式。 | +| Full | 固定为大标题模式。 | ## NavigationCommonTitle类型说明 -| 名称 | 类型 | 必填 | 描述 | -| ------ | --------- | ---- | -------- | -| main | string | 是 | 设置主标题。 | -| sub | string | 是 | 设置副标题。 | +| 名称 | 类型 | 必填 | 描述 | +| ---- | ------ | ---- | ------ | +| main | string | 是 | 设置主标题。 | +| sub | string | 是 | 设置副标题。 | ## NavigationCustomTitle类型说明 -| 名称 | 类型 | 必填 | 描述 | -| ------ | ----------------------- | ---- | ------------------------------ | -| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 设置标题栏内容。 | -| height | [TitleHeight](#titleheight枚举说明) \| [Length](ts-types.md#length) | 是 | 设置标题栏高度。 | +| 名称 | 类型 | 必填 | 描述 | +| ------- | ---------------------------------------- | ---- | -------- | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 设置标题栏内容。 | +| height | [TitleHeight](#titleheight枚举说明) \| [Length](ts-types.md#length) | 是 | 设置标题栏高度。 | ## NavBarPosition枚举说明 -| 名称 | 描述 | -| ---- | ---------------------------------------- | +| 名称 | 描述 | +| ----- | ---------------- | | Start | 双栏显示时,主列在主轴方向首部。 | -| End | 双栏显示时,主列在主轴方向尾部。 | +| End | 双栏显示时,主列在主轴方向尾部。 | ## NavigationMode枚举说明 -| 名称 | 描述 | -| ---- | ---------------------------------------- | -| Stack | 导航栏与内容区独立显示,相当于两个页面。 | -| Split | 导航栏与内容区分两栏显示。 | -| Auto | 窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。 | +| 名称 | 描述 | +| ----- | ---------------------------------------- | +| Stack | 导航栏与内容区独立显示,相当于两个页面。 | +| Split | 导航栏与内容区分两栏显示。 | +| Auto | 窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。 | ## TitleHeight枚举说明 -| 名称 | 描述 | -| ---- | ---------------------------------------- | -| MainOnly | 只有主标题时标题栏的推荐高度(56vp)。 | +| 名称 | 描述 | +| ----------- | -------------------------- | +| MainOnly | 只有主标题时标题栏的推荐高度(56vp)。 | | MainWithSub | 同时有主标题和副标题时标题栏的推荐高度(82vp)。 | > **说明:** -> 目前可滚动组件只支持List。 +> 目前可滚动组件只支持List。 ## 事件 @@ -147,7 +147,7 @@ struct NavigationExample { .fontSize(14) .lineHeight(19) .opacity(0.4) - .margin({ top: 2 }) + .margin({ top: 2, bottom: 20 }) }.alignItems(HorizontalAlign.Start) } @@ -192,7 +192,7 @@ struct NavigationExample { Column() { Navigation() { TextInput({ placeholder: 'search...' }) - .width(336) + .width('90%') .height(40) .backgroundColor('#FFFFFF') .margin({ top: 8 }) @@ -201,7 +201,7 @@ struct NavigationExample { ForEach(this.arr, (item) => { ListItem() { Text('' + item) - .width(336) + .width('90%') .height(72) .backgroundColor('#FFFFFF') .borderRadius(24) @@ -212,8 +212,8 @@ struct NavigationExample { }, item => item) } .height(324) - .width(336) - .margin({ top: 12 }) + .width('100%') + .margin({ top: 12, left: '10%' }) } .title(this.NavigationTitle) .menus(this.NavigationMenus) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md index 5805ebdc0642cc7d873fab4cc32f2d992a11cf91..b137ec163412bcc8686b12f1bcf6129d2dff5797 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-rating.md @@ -20,18 +20,18 @@ Rating(options?: { rating: number, indicator?: boolean }) **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -| rating | number | 是 | 设置并接收评分值。
默认值:0
取值范围: [0, stars]
小于0取0,大于stars取最大值stars。 | -| indicator | boolean | 否 | 设置评分组件作为指示器使用,不可改变评分。
默认值:false, 可进行评分
**说明:**
indicator=true时,默认组件高度height=12.0vp,组件width=height*stars。
indicator=false时,默认组件高度height=28.0vp,组件width=height*stars。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| --------- | ------- | ---- | ---------------------------------------- | +| rating | number | 是 | 设置并接收评分值。
默认值:0
取值范围: [0, stars]
小于0取0,大于stars取最大值stars。 | +| indicator | boolean | 否 | 设置评分组件作为指示器使用,不可改变评分。
默认值:false, 可进行评分
**说明:**
indicator=true时,默认组件高度height=12.0vp,组件width=height*stars。
indicator=false时,默认组件高度height=28.0vp,组件width=height*stars。 | ## 属性 -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | -| stars | number | 设置评分总数。
默认值:5
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按默认值显示。 | -| stepSize | number | 操作评级的步长。
默认值:0.5
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按默认值显示。
取值范围为[0.1, stars]。 | +| 名称 | 参数类型 | 描述 | +| --------- | ---------------------------------------- | ---------------------------------------- | +| stars | number | 设置评分总数。
默认值:5
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按默认值显示。 | +| stepSize | number | 操作评级的步长。
默认值:0.5
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
设置为小于0的值时,按默认值显示。
取值范围为[0.1, stars]。 | | starStyle | {
backgroundUri: string,
foregroundUri: string,
secondaryUri?: string
} | backgroundUri:未选中的星级的图片链接,可由用户自定义或使用系统默认图片。
foregroundUri:选中的星级的图片路径,可由用户自定义或使用系统默认图片。
secondaryUir:部分选中的星级的图片路径,可由用户自定义或使用系统默认图片。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
startStyle属性所支持的图片类型能力参考[Image](ts-basic-components-image.md)组件。
支持加载本地图片和网络图片,暂不支持PixelMap类型和Resource资源。
默认图片加载方式为异步,暂不支持同步加载。
设置值为undefined或者空字符串时,rating会选择加载系统默认星型图源。 | > **说明:** @@ -43,8 +43,8 @@ Rating(options?: { rating: number, indicator?: boolean }) ## 事件 -| 名称 | 功能描述 | -| -------- | -------- | +| 名称 | 功能描述 | +| ---------------------------------------- | ---------------------------------------- | | onChange(callback:(value: number) => void) | 操作评分条的评星发生改变时触发该回调。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 @@ -86,7 +86,7 @@ struct RatingExample { .fontColor('#182431') .fontWeight(500) Row() { - Rating({ rating: 3.5, indicator: true }).margin({ top: 1, right: 8 }) + Rating({ rating: 3.5, indicator: false }).margin({ top: 1, right: 8 }) Text('2021/06/02') .fontSize(10) .fontColor('#182431') 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 fe680d987c2ac0dcea2deba8d22b63c0ba34f4bd..0f9582a81ce84019b6a6ab8703b6079b5cd749b8 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 @@ -46,7 +46,7 @@ ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: B @Component struct ScrollBarExample { private scroller: Scroller = new Scroller() - private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] build() { Column() { @@ -56,8 +56,8 @@ struct ScrollBarExample { ForEach(this.arr, (item) => { Row() { Text(item.toString()) - .width('90%') - .height(100) + .width('80%') + .height(60) .backgroundColor('#3366CC') .borderRadius(15) .fontSize(16) @@ -65,17 +65,18 @@ struct ScrollBarExample { .margin({ top: 5 }) } }, item => item) - }.margin({ right: 52 }) + }.margin({ right: 15 }) } + .width('90%') .scrollBar(BarState.Off) .scrollable(ScrollDirection.Vertical) ScrollBar({ scroller: this.scroller, direction: ScrollBarDirection.Vertical,state: BarState.Auto }) { Text() - .width(30) + .width(20) .height(100) .borderRadius(10) .backgroundColor('#C0C0C0') - }.width(30).backgroundColor('#ededed') + }.width(20).backgroundColor('#ededed') } } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md index 1dbc2dd6ebb99eb8f2716566a8903edd002ee848..863e73e9ef2faf1e3040b62d05a30fcf273d2f36 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -9,7 +9,7 @@ ## 子组件 -可以包含[Span](ts-basic-components-span.md)子组件。 +可以包含[Span](ts-basic-components-span.md)和[ImageSpan](ts-basic-components-imagespan.md)子组件。 ## 接口 @@ -31,7 +31,7 @@ Text(content?: string | Resource) | 名称 | 参数类型 | 描述 | | ----------------------- | ----------------------------------- | ------------------------------------------- | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式
默认值:TextAlign.Start
说明:
文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
需配合`maxLines`使用,单独设置不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
当`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,不需要设置`maxLines`属性。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | maxLines | number | 设置文本的最大行数。
默认值:Infinity
**说明:**
默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
}
从API version 9开始,该接口支持在ArkTS卡片中使用。| @@ -43,10 +43,11 @@ Text(content?: string | Resource) | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 组件支持设置文本是否可复制粘贴。
默认值:CopyOptions.None
该接口支持在ArkTS卡片中使用。 | | textShadow10+ | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明) | 设置文字阴影效果。 | | heightAdaptivePolicy10+ | [TextHeightAdaptivePolicy](ts-appendix-enums.md#TextHeightAdaptivePolicy10) | 设置文本自适应高度的方式。 | +| textIndent10+ | number \| string | 设置首行文本缩进,默认值0。 | > **说明:** > -> 不支持Text内同时存在文本内容和Span子组件。如果同时存在,只显示Span内的内容。 +> 不支持Text内同时存在文本内容和Span或ImageSpan子组件。如果同时存在,只显示Span或ImageSpan内的内容。 ## 事件 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 ffa80febf3417ef27c798b4e7d73c3b747e7d9a7..18078cdd83a821c791a67dcbadabe299d08dc693 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 @@ -144,6 +144,9 @@ struct TextInputExample { .margin(20) .fontSize(14) .fontColor(Color.Black) + .inputFilter('[a-z]', (e) => { + console.log(JSON.stringify(e)) + }) .onChange((value: string) => { this.text = value }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 0260d6ac8720c54fc7d42139b9478604ed8f14fb..6e0725e30db7e747778055b03d69f113e1030b32 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -20,20 +20,20 @@ TimePicker(options?: {selected?: Date}) **参数:** -| 参数名 | 参数类型 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -| selected | Date | 否 | 设置选中项的时间。
默认值:当前系统时间 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | ---- | ---- | ------------------------ | +| selected | Date | 否 | 设置选中项的时间。
默认值:当前系统时间 | ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 名称 | 参数类型 | 描述 | -| -------- | -------- | -------- | -| useMilitaryTime | boolean | 展示时间是否为24小时制,不支持动态修改。
默认值:false | -| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 设置所有选项中最上和最下两个选项的文本颜色、字号、字体粗细。 | -| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 设置所有选项中除了最上、最下及选中项以外的文本颜色、字号、字体粗细。 | -| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 设置选中项的文本颜色、字号、字体粗细。 | +| 名称 | 参数类型 | 描述 | +| -------------------------------- | ---------------------------------------- | ----------------------------------- | +| useMilitaryTime | boolean | 展示时间是否为24小时制,不支持动态修改。
默认值:false | +| disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 设置所有选项中最上和最下两个选项的文本颜色、字号、字体粗细。 | +| textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 设置所有选项中除了最上、最下及选中项以外的文本颜色、字号、字体粗细。 | +| selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10类型说明) | 设置选中项的文本颜色、字号、字体粗细。 | ## 事件 @@ -53,9 +53,6 @@ TimePicker(options?: {selected?: Date}) ## 示例 - -### 时间选择器 - ```ts // xxx.ets @Entry 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 44ba81748c5d0e3a5d6e4224a7710e8575dcce3a..c6243e6affdf3f13cec7b60afb0413db1a35b416 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 @@ -3096,7 +3096,7 @@ onFaviconReceived(callback: (event: {favicon: image.PixelMap}) => void) Column() { Web({ src:'www.example.com', controller: this.controller }) .onFaviconReceived((event) => { - console.log('onFaviconReceived:' + JSON.stringify(event)) + console.log('onFaviconReceived'); this.icon = event.favicon; }) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 542fdd7a79f0e8ab512895956af98bfcbeedf313..a68712f809050a77962d2b6e7c15fe481734b1e0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -12,6 +12,8 @@ CanvasRenderingContext2D(setting: RenderingContextSetting) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -25,6 +27,8 @@ RenderingContextSettings(antialias?: boolean) 用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -36,23 +40,23 @@ RenderingContextSettings(antialias?: boolean) | 名称 | 类型 | 描述 | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | +| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 | -| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | -| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt' | -| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter' | -| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10 | -| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
默认值:'normal normal 14px sans-serif' | -| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
默认值:'left' | -| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
默认值:'alphabetic' | -| [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。 | -| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。
默认值:0.0 | -| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。
默认值:'source-over' | -| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。
默认值:0.0 | -| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。 | -| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 | -| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
默认值:true | +| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
默认值:'butt'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
默认值:'miter'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
默认值:10
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
默认值:'normal normal 14px sans-serif'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
默认值:'left'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
默认值:'alphabetic'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。
默认值:0.0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。
默认值:'source-over'
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。
默认值:0.0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
默认值:true
从API version 9开始,该接口支持在ArkTS卡片中使用。 | > **说明:** > @@ -657,6 +661,8 @@ fillRect(x: number, y: number, w: number, h: number): void 填充一个矩形。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -701,6 +707,8 @@ strokeRect(x: number, y: number, w: number, h: number): void 绘制具有边框的矩形,矩形内部不填充。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -745,6 +753,8 @@ clearRect(x: number, y: number, w: number, h: number): void 删除指定区域内的绘制内容。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -791,6 +801,8 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void 绘制填充类文本。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -836,6 +848,8 @@ strokeText(text: string, x: number, y: number, maxWidth?:number): void 绘制描边类文本。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -881,6 +895,8 @@ measureText(text: string): TextMetrics 该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -889,9 +905,9 @@ measureText(text: string): TextMetrics **返回值:** -| 类型 | 说明 | -| ----------- | ---------------- | -| TextMetrics | 文本的尺寸信息。 | +| 类型 | 说明 | +| ----------- | ------------------------------------------------------------ | +| TextMetrics | 文本的尺寸信息。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **TextMetrics类型描述:** @@ -951,6 +967,8 @@ stroke(path?: Path2D): void 进行边框绘制操作。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -997,6 +1015,8 @@ beginPath(): void 创建一个新的绘制路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -1037,6 +1057,8 @@ moveTo(x: number, y: number): void 路径从当前点移动到指定点。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -1082,6 +1104,8 @@ lineTo(x: number, y: number): void 从当前点到指定点进行路径连接。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1127,6 +1151,8 @@ closePath(): void 结束当前路径形成一个封闭路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -1167,12 +1193,14 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu 通过指定图像和重复方式创建图片填充的模板。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 描述 | | ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | 图源对象,具体参考ImageBitmap对象。 | -| repetition | string | 是 | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'。
默认值:'' | +| repetition | string | 是 | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'、'clamp'、'mirror'。
默认值:'' | **返回值:**: @@ -1218,6 +1246,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, 创建三次贝赛尔曲线的路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1267,6 +1297,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void 创建二次贝赛尔曲线的路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1314,6 +1346,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, 绘制弧线路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1362,6 +1396,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void 依据圆弧经过的点和圆弧半径创建圆弧路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1409,6 +1445,8 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number 在规定的矩形区域绘制一个椭圆。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -1459,6 +1497,8 @@ rect(x: number, y: number, w: number, h: number): void 创建矩形路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1504,6 +1544,8 @@ fill(fillRule?: CanvasFillRule): void 对封闭路径进行填充。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1545,6 +1587,8 @@ fill(path: Path2D, fillRule?: CanvasFillRule): void 对封闭路径进行填充。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1598,6 +1642,8 @@ clip(fillRule?: CanvasFillRule): void 设置当前路径为剪切路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1641,6 +1687,8 @@ clip(path: Path2D, fillRule?: CanvasFillRule): void 设置当前路径为剪切路径 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1693,6 +1741,8 @@ filter(filter: string): void 为Canvas图形设置各类滤镜效果。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -1706,6 +1756,8 @@ getTransform(): Matrix2D 获取当前被应用到上下文的转换矩阵。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### resetTransform @@ -1713,6 +1765,8 @@ resetTransform(): void 使用单位矩阵重新设置当前变形。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### direction @@ -1720,6 +1774,8 @@ direction(direction: CanvasDirection): void 绘制文本时,描述当前文本方向的属性。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### rotate @@ -1727,6 +1783,8 @@ rotate(angle: number): void 针对当前坐标轴进行顺时针旋转。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1769,6 +1827,8 @@ scale(x: number, y: number): void 设置canvas画布的缩放变换属性,后续的绘制操作将按照缩放比例进行缩放。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1814,6 +1874,8 @@ transform(a: number, b: number, c: number, d: number, e: number, f: number): voi transform方法对应一个变换矩阵,想对一个图形进行变化的时候,只要设置此变换矩阵相应的参数,对图形的各个定点的坐标分别乘以这个矩阵,就能得到新的定点的坐标。矩阵变换效果可叠加。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + > **说明:** > 变换后的坐标计算方式(x和y为变换前坐标,x'和y'为变换后坐标): > @@ -1874,6 +1936,8 @@ setTransform(a: number, b: number, c: number, d: number, e: number, f: number): setTransform方法使用的参数和transform()方法相同,但setTransform()方法会重置现有的变换矩阵并创建新的变换矩阵。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1931,6 +1995,8 @@ translate(x: number, y: number): void 移动当前坐标系的原点。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1979,7 +2045,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: 进行图像绘制。 -从API version 9开始,该接口支持在ArkTS卡片中使用。 +从API version 9开始,该接口支持在ArkTS卡片中使用,卡片中不支持PixelMap对象。 **参数:** @@ -2032,6 +2098,8 @@ createImageData(sw: number, sh: number): ImageData 创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认 | 描述 | @@ -2044,6 +2112,8 @@ createImageData(imageData: ImageData): ImageData 创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认 | 描述 | @@ -2084,6 +2154,8 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData 以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagedata.md)对象。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2140,6 +2212,8 @@ putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirty 使用[ImageData](ts-components-canvas-imagedata.md)数据填充新的矩形区域。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2194,6 +2268,8 @@ setLineDash(segments: number[]): void 设置画布的虚线样式。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 描述 | @@ -2237,6 +2313,8 @@ getLineDash(): number[] 获得当前画布的虚线样式。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **返回值:** | 类型 | 说明 | @@ -2293,6 +2371,8 @@ imageSmoothingQuality(quality: imageSmoothingQuality) 用于设置图像平滑度。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 描述 | @@ -2307,6 +2387,8 @@ transferFromImageBitmap(bitmap: ImageBitmap): void 显示给定的ImageBitmap对象。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 描述 | @@ -2405,6 +2487,8 @@ restore(): void 对保存的绘图上下文进行恢复。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -2443,6 +2527,8 @@ save(): void 将当前状态放入栈中,保存canvas的全部状态,通常在需要保存绘制状态时调用。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -2481,6 +2567,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void 创建一个线性渐变色。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2530,6 +2618,8 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, 创建一个径向渐变色。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2574,7 +2664,55 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ![zh-cn_image_0000001239032419](figures/zh-cn_image_0000001239032419.png) +### createConicGradient10+ + +createConicGradient(startAngle: number, x: number, y: number): CanvasGradient + +创建一个圆锥渐变色。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ---------- | ------ | ---- | ------ | ------------------------------------------------------------ | +| startAngle | number | 是 | 0 | 开始渐变的角度,以弧度为单位。角度测量从中心右侧水平开始,顺时针移动。 | +| x | number | 是 | 0 | 圆锥渐变的中心x轴坐标。单位:vp | +| y | number | 是 | 0 | 圆锥渐变的中心y轴坐标。单位:vp | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffffff') + .onReady(() => { + var grad = this.context.createConicGradient(0, 50, 80) + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') + this.context.fillStyle = grad + this.context.fillRect(0, 30, 100, 100) + }) + } + .width('100%') + .height('100%') + } +} +``` + + ![zh-cn_image_0000001239032419](figures/zh-cn_image_0000001239032420.png) ## CanvasPattern 一个Object对象, 通过[createPattern](#createpattern)方法创建。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 \ No newline at end of file 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 7c297ede50ec17263b9a6979cb34e9305941c351..d1355645ece52650e091b68c4572ab20cc0bc6a4 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 @@ -4,7 +4,7 @@ > **说明:** > -> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 ## 接口 @@ -12,24 +12,24 @@ 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 | 顺序识别,按照手势的注册顺序识别手势,直到所有手势识别成功。当有一个手势识别失败时,所有手势识别失败。 | -| Parallel | 并发识别,注册的手势同时识别,直到所有手势识别结束,手势识别互相不影响。 | -| Exclusive | 互斥识别,注册的手势同时识别,若有一个手势识别成功,则结束手势识别。 | +| 名称 | 描述 | +| --------- | ---------------------------------------- | +| Sequence | 顺序识别,按照手势的注册顺序识别手势,直到所有手势识别成功。当有一个手势识别失败时,所有手势识别失败。 | +| Parallel | 并发识别,注册的手势同时识别,直到所有手势识别结束,手势识别互相不影响。 | +| Exclusive | 互斥识别,注册的手势同时识别,若有一个手势识别成功,则结束手势识别。 | ## 事件 -| 名称 | 功能描述 | -| -------- | -------- | +| 名称 | 功能描述 | +| ---------------------------------------- | ------------------------------------ | | onCancel(event: () => void) | 顺序组合手势(GestureMode.Sequence)取消后触发回调。 | @@ -50,6 +50,7 @@ struct GestureGroupExample { build() { Column() { Text('sequence gesture\n' + 'LongPress onAction:' + this.count + '\nPanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY) + .fontSize(15) } .translate({ x: this.offsetX, y: this.offsetY, z: 0 }) .height(150) 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 c90a981f22824983ca9bb52e1f2c48cb04e00211..59c55ba2ebf4fe8faff8f281ab72a09926ef29fb 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 @@ -26,10 +26,10 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- | -| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | 否 | FlexDirection.Row | 子组件在Flex容器上排列的方向,即主轴的方向。 | -| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | 否 | FlexWrap.NoWrap | 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容器交叉轴上的对齐格式。 | +| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | 否 | ItemAlign.Start | 所有子组件在Flex容器交叉轴上的对齐格式。 | | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。 | @@ -240,7 +240,7 @@ struct FlexExample4 { } ``` -![zh-cn_image_0000001174422904](figures/zh-cn_image_0000001174422904.jpg) +![zh-cn_image_0000001174422904](figures/zh-cn_image_0000001174422904.png) ```ts // xxx.ets 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 07da0f4523f7d6215398027f8a13780b77f44931..012fa48e92f303e2dc8aae7ae54e93f23d7a88e9 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 @@ -59,6 +59,7 @@ Grid(scroller?: Scroller) | cellLength8+ | number | 当layoutDirection是Row/RowReverse时,表示一行的高度。
当layoutDirection是Column/ColumnReverse时,表示一列的宽度。
默认值:第一个元素的大小 | | multiSelectable8+ | boolean | 是否开启鼠标框选。
默认值:false
- false:关闭框选。
- true:开启框选。 | | supportAnimation8+ | boolean | 是否支持动画。当前支持GridItem拖拽动画。
默认值:false | +| edgeEffect10+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置组件的滑动效果,支持弹簧效果和阴影效果。
默认值:EdgeEffect.None
| Grid组件根据rowsTemplate、columnsTemplate属性的设置情况,可分为以下三种布局模式: @@ -107,7 +108,7 @@ Grid组件根据rowsTemplate、columnsTemplate属性的设置情况,可分为 > **说明:** > -> List组件[通用属性clip](ts-universal-attributes-sharp-clipping.md)的默认值为true。 +> Grid组件[通用属性clip](ts-universal-attributes-sharp-clipping.md)的默认值为true。 ## 事件 @@ -181,6 +182,7 @@ struct GridExample { .columnsTemplate('1fr 1fr 1fr 1fr 1fr') .columnsGap(10) .rowsGap(10) + .edgeEffect(EdgeEffect.Spring) .onScrollIndex((first: number) => { console.info(first.toString()) }) @@ -196,4 +198,4 @@ struct GridExample { } ``` -![zh-cn_image_0000001219744183](figures/zh-cn_image_0000001219744183.gif) \ No newline at end of file +![zh-cn_image_0000001219744183](figures/zh-cn_image_0000001219744183.gif) 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 ff4fce4cb2691b29c509187627ce8911d8585686..83f518f5d2488421e9c17ca7db240ccfee297721 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 @@ -130,7 +130,7 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt | 名称 | 参数类型 | 描述 | | ----------------------- | ----------------------------------- | ------------------------------------------- | -| alignItems10+ | [ItemAlign](ts-appendix-enums.md#itemalign) | 设置GridRow中的GridCol垂直主轴方向对齐方式,默认值:ItemAlign.Start
说明:
GridCol本身也可通过alignSelf([ItemAlign](ts-appendix-enums.md#itemalign))设置自身对齐方式。当上述两种对齐方式都设置时,以GridCol自身设置为准。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | +| alignItems10+ | [ItemAlign](ts-appendix-enums.md#itemalign) | 设置GridRow中的GridCol垂直主轴方向对齐方式,默认值:ItemAlign.Start
说明:
在ItemAlign中,实际支持的参数枚举值仅为Start、Center、End、Stretch。
GridCol本身也可通过alignSelf([ItemAlign](ts-appendix-enums.md#itemalign))设置自身对齐方式。当上述两种对齐方式都设置时,以GridCol自身设置为准。
从API version 10开始,该接口支持在ArkTS卡片中使用。 | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md index 50843b352e549af74e54c5d840e3bb5c78f3e8ca..b0e404f3c1c0e9e0bfd210526788d7cf134f951f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md @@ -92,7 +92,7 @@ List(value?:{space?: number | string, initialIndex?: number, scroller? | 名称 | 功能描述 | | -------- | -------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | 当List组件在编辑模式时,点击ListItem右边出现的删除按钮时触发。
从API version9开始废弃。
- index: 被删除的列表项的索引值。 | -| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | 列表滑动时触发。
- scrollOffset: 滑动偏移量。
- [scrollState](#scrollstate枚举说明): 当前滑动状态。
使用控制器调用ScrollEdge和ScrollToIndex时不会触发,其余情况有滚动就会触发该事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | 列表滑动时触发。
- scrollOffset: 每帧滚动的偏移量,List的内容向上滚动时偏移量为正,向下滚动时偏移量为负。
- [scrollState](#scrollstate枚举说明): 当前滑动状态。
使用控制器调用ScrollEdge和ScrollToIndex时不会触发,其余情况有滚动就会触发该事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | onScrollIndex(event: (start: number, end: number) => void) | 有子组件划入或划出List显示区域时触发。
计算索引值时,ListItemGroup作为一个整体占一个索引值,不计算ListItemGroup内部ListItem的索引值。
- start: 滑动起始位置索引值。
- end: 滑动结束位置索引值。
触发该事件的条件:列表初始化时会触发一次,List显示区域内第一个子组件的索引值或后一个子组件的索引值有变化时会触发。
List的边缘效果为弹簧效果时,在List划动到边缘继续划动和松手回弹过程不会触发onScrollIndex事件。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | onReachStart(event: () => void) | 列表到达起始位置时触发。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
List初始化时如果initialIndex为0会触发一次,List滚动到起始位置时触发一次。List边缘效果为弹簧效果时,划动经过起始位置时触发一次,回弹回起始位置时再触发一次。 | | onReachEnd(event: () => void) | 列表到底末尾位置时触发。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
List边缘效果为弹簧效果时,划动经过末尾位置时触发一次,回弹回末尾位置时再触发一次。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index bd8d15720086142ef5ce0d40c497bfff2a5730d0..020b18250a8e110f962a5ebaff367aa640378e90 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -33,7 +33,7 @@ Scroll(scroller?: Scroller) | scrollable | [ScrollDirection](#scrolldirection枚举说明) | 设置滚动方向。
默认值:ScrollDirection.Vertical | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Auto
**说明:**
如果容器组件无法滚动,则滚动条不显示。 | | scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 | -| scrollBarWidth | string \| number | 设置滚动条的宽度。
默认值:4
单位:vp | +| scrollBarWidth | string \| number | 设置滚动条的宽度,不支持百分比设置。
默认值:4
单位:vp | | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。
默认值:EdgeEffect.None | ## ScrollDirection枚举说明 @@ -50,9 +50,9 @@ Scroll(scroller?: Scroller) | ------------------------------------------------------------ | ------------------------------------------------------------ | | onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | 每帧开始滚动时触发,事件参数传入即将发生的滚动量,事件处理函数中可根据应用场景计算实际需要的滚动量并作为事件处理函数的返回值返回,Scroll将按照返回值的实际滚动量进行滚动。
\- offset:即将发生的滚动量。
\- state:当前滚动状态。
- offsetRemain:实际滚动量。
触发该事件的条件 :
1、滚动组件触发滚动时触发,包括键鼠操作等其他触发滚动的输入设置。
2、调用控制器接口时不触发。
3、越界回弹不触发。
**说明:**
支持offsetRemain为负值。
若通过onScrollFrameBegine事件和scrollBy方法实现容器嵌套滚动,需设置子滚动节点的EdgeEffect为None。如Scroll嵌套List滚动时,List组件的edgeEffect属性需设置为EdgeEffect.None。 | | onScroll(event: (xOffset: number, yOffset: number) => void) | 滚动事件回调, 返回滚动时水平、竖直方向偏移量。
触发该事件的条件 :
1、滚动组件触发滚动时触发,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用。
3、越界回弹。 | -| onScrollEdge(event: (side: Edge) => void) | 滚动到边缘事件回调。
触发该事件的条件 :
1、滚动组件触发滚动时触发,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用。
3、越界回弹。 | +| onScrollEdge(event: (side: Edge) => void) | 滚动到边缘事件回调。
触发该事件的条件 :
1、滚动组件滚动到边缘时触发,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用。
3、越界回弹。 | | onScrollEnd(deprecated) (event: () => void) | 滚动停止事件回调。
该事件从API version 9开始废弃,使用onScrollStop事件替代。
触发该事件的条件 :
1、滚动组件触发滚动后停止,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用后停止,带过渡动效。 | -| onScrollStart9+(event: () => void) | 滚动开始时触发。手指拖动Scroll或拖动Scroll的滚动条触发的滚动开始时,会触发该事件。使用[Scroller](#scroller)滚动控制器触发的带动画的滚动,动画开始时会触发该事件。
触发该事件的条件 :
1、滚动组件触发滚动后停止,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用后开始,带过渡动效。 | +| onScrollStart9+(event: () => void) | 滚动开始时触发。手指拖动Scroll或拖动Scroll的滚动条触发的滚动开始时,会触发该事件。使用[Scroller](#scroller)滚动控制器触发的带动画的滚动,动画开始时会触发该事件。
触发该事件的条件 :
1、滚动组件开始滚动时触发,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用后开始,带过渡动效。 | | onScrollStop9+(event: () => void) | 滚动停止时触发。手拖动Scroll或拖动Scroll的滚动条触发的滚动,手离开屏幕并且滚动停止时会触发该事件。使用[Scroller](#scroller)滚动控制器触发的带动画的滚动,动画停止时会触发该事件。
触发该事件的条件 :
1、滚动组件触发滚动后停止,支持键鼠操作等其他触发滚动的输入设置。
2、通过滚动控制器API接口调用后开始,带过渡动效,。 | > **说明:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index a0b1209302df5a0697b83e9815bcaa190e144b6d..dbb2e0c3d4050531c52b1070d1671b3a3b09a41f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -104,14 +104,13 @@ SideBarContainer( type?: SideBarContainerType ) @Entry @Component struct SideBarContainerExample { - normalIcon : Resource = $r("app.media.icon") + normalIcon: Resource = $r("app.media.icon") selectedIcon: Resource = $r("app.media.icon") @State arr: number[] = [1, 2, 3] @State current: number = 1 build() { - SideBarContainer(SideBarContainerType.Embed) - { + SideBarContainer(SideBarContainerType.Embed) { Column() { ForEach(this.arr, (item, index) => { Column({ space: 5 }) { @@ -136,6 +135,13 @@ struct SideBarContainerExample { } .margin({ top: 50, left: 20, right: 30 }) } + .controlButton({ + icons: { + hidden: $r('app.media.drawer'), + shown: $r('app.media.drawer'), + switching: $r('app.media.drawer') + } + }) .sideBarWidth(150) .minSideBarWidth(50) .maxSideBarWidth(300) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md index 385f3fa1b2104c4eea94ca61a055ae4115fe45cf..271317c99aa2969dde13af52888df634b9d796b0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-stack.md @@ -28,9 +28,9 @@ Stack(value?: { alignContent?: Alignment }) 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 名称 | 参数类型 | 描述 | -| ------------ | ------------------------------------------- | ------------------------------ | -| alignContent | [Alignment](ts-appendix-enums.md#alignment) | 设置子组件在容器内的对齐方式。
默认值:Alignment.Center
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| 名称 | 参数类型 | 描述 | +| ------------ | ------------------------------------------- | ------------------------------------------------------------ | +| alignContent | [Alignment](ts-appendix-enums.md#alignment) | 设置子组件在容器内的对齐方式。
默认值:Alignment.Center
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
该属性与[通用属性align](ts-universal-attributes-location.md)同时设置时,只有align属性生效。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md index de381076f89d356a3c437333055c18d048fa7bbd..f4e8baf6c69a11342e1f8a2c4d4eaad70e9f665a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -102,12 +102,12 @@ SubTabBarStyle的静态构造函数。 | 名称 | 参数类型 | 必填 | 描述 | | -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | 否 | 设置Label文本超长时的显示方式。文本截断默认是省略号截断。 | -| maxLines | number | 否 | 设置Label文本的最大行数。默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 textOverflow来指定截断方式。 | -| minFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | 否 | 设置Label文本最小显示字号。需配合maxFontSize以及maxLines或布局大小限制使用。 | -| maxFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | 否 | 设置Label文本最大显示字号。需配合minFontSize以及maxLines或布局大小限制使用。 | -| heightAdaptivePolicy | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | 否 | 设置Label文本自适应高度的方式。 | -| font | [Font](ts-types.md#font) | 否 | 设置Label文本字体样式。 | +| overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | 否 | 设置Label文本超长时的显示方式。默认值是省略号截断。 | +| maxLines | number | 否 | 设置Label文本的最大行数。如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过textOverflow来指定截断方式。默认值是1。 | +| minFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | 否 | 设置Label文本最小显示字号。需配合maxFontSize以及maxLines或布局大小限制使用。自适应文本大小生效后,font.size不生效。默认值是0.0fp。| +| maxFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | 否 | 设置Label文本最大显示字号。需配合minFontSize以及maxLines或布局大小限制使用。自适应文本大小生效后,font.size不生效。默认值是0.0fp。|| +| heightAdaptivePolicy | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | 否 | 设置Label文本自适应高度的方式。默认值是最大行数优先。 | +| font | [Font](ts-types.md#font) | 否 | 设置Label文本字体样式。默认值是字体大小16.0fp、字体类型HarmonyOS Sans,字体风格正常,字重正常。 | ## BottomTabBarStyle9+ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md index 3167622399b6bd7f9b0800a77c75836b5da29995..9319bb050d04b4d33e444a10e0cefe5ec8bf0e7b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -45,7 +45,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr | barHeight | number \| Length8+ | TabBar的高度值。
**说明:**
设置为小于0或大于Tabs宽度值时,按默认值显示。 | | animationDuration | number | TabContent滑动动画时长。不设置时,点击切换页签无动画,滑动切换有动画;设置时,点击切换和滑动切换都有动画。
默认值:300
**说明:**
设置为小于0或百分比时,按默认值显示。 | | divider10+ | [DividerStyle](#dividerstyle10对象说明) \| null | 用于设置区分TabBar和TabContent的分割线样式设置分割线样式,默认不显示分割线。
DividerStyle: 分割线的样式;
null: 不显示分割线。 | -| FadingEdge10+ | boolean | 设置页签超过容器宽度时是否渐隐消失
默认值:true | +| fadingEdge10+ | boolean | 设置页签超过容器宽度时是否渐隐消失
默认值:true | ## DividerStyle10+对象说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md index 8be87f8269e96ba280ae5a236231e7b8bd1b1a27..a3e993c20b8c12ede8d546f36490c7cad0e3ae2c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md @@ -253,7 +253,7 @@ struct WaterflowDemo { build() { Column({ space: 2 }) { - WaterFlow({ footer: this.itemFoot, scroller: this.scroller }) { + WaterFlow({ footer: this.itemFoot.bind(this), scroller: this.scroller }) { LazyForEach(this.datasource, (item: number) => { FlowItem() { Column() { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md b/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md index 44971cf244a982f7e7d8cd88ddeb2d4505c2b181..477a9ca18f97c53922be2e37237be1577280a582 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md @@ -88,6 +88,8 @@ onLayout?(children: Array<LayoutChild>, constraint: ConstraintSizeOptions) 框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 类型 | 说明 | @@ -102,6 +104,8 @@ onMeasure?(children: Array<LayoutChild>, constraint: ConstraintSizeOptions 框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 类型 | 说明 | @@ -114,6 +118,8 @@ onMeasure?(children: Array<LayoutChild>, constraint: ConstraintSizeOptions 子组件布局信息。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数 | 参数类型 | 描述 | | ---------- | ---------------------------------------- | ------------------- | | name | string | 子组件名称。 | @@ -129,6 +135,8 @@ onMeasure?(children: Array<LayoutChild>, constraint: ConstraintSizeOptions 子组件border信息。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数 | 参数类型 | 描述 | | ----------- | ------------------------------------ | ----------------------- | | borderWidth | [EdgeWidths](ts-types.md#edgewidths) | 边框宽度类型,用于描述组件边框不同方向的宽度。 | @@ -140,6 +148,8 @@ onMeasure?(children: Array<LayoutChild>, constraint: ConstraintSizeOptions 子组件layout信息。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + | 参数 | 参数类型 | 描述 | | ---------- | ---------------------------------------- | -------- | | position | [Position](ts-types.md#position) | 子组件位置坐标。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index 60d07fe9aafec52b01e133cd83c1b0f229c5b0e6..9fad1261232b195662f37b294e2e8c0d0a17b3f3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -21,7 +21,7 @@ Shape(value?: PixelMap) -从API version 9开始,该接口支持在ArkTS卡片中使用。 +从API version 9开始,该接口支持在ArkTS卡片中使用,卡片中不支持使用PixelMap对象。 **参数:** @@ -52,8 +52,6 @@ Shape(value?: PixelMap) ## 示例 -### 示例1 - ```ts // xxx.ets @Entry diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index a11f94cd800352135a89a613b4e990560295c4e8..98c4bd350c2d8ad1818bb2a25c89be747ff0fac9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -12,6 +12,8 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings) +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数名 | 参数类型 | 必填 | 参数描述 | @@ -25,23 +27,23 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render | 名称 | 类型 | 描述 | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | -| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 | -| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | -| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
- 默认值:'butt'。 | -| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
- 默认值:'miter'。 | -| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
- 默认值:10。 | -| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
- 默认值:'normal normal 14px sans-serif'。 | -| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
> **说明:**
> ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
- 默认值:'left'。 | -| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
- 默认值:'alphabetic'。 | +| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 指定绘制的填充色。
- 类型为string时,表示设置填充区域的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | 设置描边的颜色。
- 类型为string时,表示设置描边使用的颜色。
- 类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。
- 类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:
- 'butt':线端点以方形结束。
- 'round':线端点以圆形结束。
- 'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。
- 默认值:'butt'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:
- 'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。
- 'bevel':在线段相连处使用三角形为底填充, 每个部分矩形拐角独立。
- 'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。
- 默认值:'miter'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。
- 默认值:10。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [font](#font) | string | 设置文本绘制中的字体样式。
语法:ctx.font='font-size font-family'
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列。
语法:ctx.font='font-style font-weight font-size font-family'
- font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。
- font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal', 'bold', 'bolder', 'lighter', 100, 200, 300, 400, 500, 600, 700, 800, 900。
- font-size(可选),指定字号和行高,单位只支持px。
- font-family(可选),指定字体系列,支持如下几种类型:'sans-serif', 'serif', 'monospace'。
- 默认值:'normal normal 14px sans-serif'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:
- 'left':文本左对齐。
- 'right':文本右对齐。
- 'center':文本居中对齐。
- 'start':文本对齐界线开始的地方。
- 'end':文本对齐界线结束的地方。
> **说明:**
> ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。
- 默认值:'left'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:
- 'alphabetic':文本基线是标准的字母基线。
- 'top':文本基线在文本块的顶部。
- 'hanging':文本基线是悬挂基线。
- 'middle':文本基线在文本块的中间。
- 'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。
- 'bottom':文本基线在文本块的底部。 与ideographic基线的区别在于ideographic基线不需要考虑下行字母。
- 默认值:'alphabetic'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。 | -| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。
- 默认值:0.0。 | -| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。
- 默认值:'source-over'。 | -| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。
- 默认值:0.0。 | -| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。 | -| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 | -| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
- 默认值:true。 | +| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。
- 默认值:0.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。
- 默认值:'source-over'。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。
- 默认值:0.0。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
- 默认值:true。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | > **说明:** > fillStyle、shadowColor与 strokeStyle 中string类型格式为 'rgb(255, 255, 255)','rgba(255, 255, 255, 1.0)','\#FFFFFF'。 @@ -700,6 +702,8 @@ fillRect(x: number, y: number, w: number, h: number): void 填充一个矩形。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -747,6 +751,8 @@ strokeRect(x: number, y: number, w: number, h: number): void 绘制具有边框的矩形,矩形内部不填充。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -794,6 +800,8 @@ clearRect(x: number, y: number, w: number, h: number): void 删除指定区域内的绘制内容。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -843,6 +851,8 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void 绘制填充类文本。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -891,6 +901,8 @@ strokeText(text: string, x: number, y: number): void 绘制描边类文本。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -939,6 +951,8 @@ measureText(text: string): TextMetrics 该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -947,9 +961,9 @@ measureText(text: string): TextMetrics **返回值:** -| 类型 | 说明 | -| ----------- | ------- | -| TextMetrics | 文本的尺寸信息 | +| 类型 | 说明 | +| ----------- | ------------------------------------------------------------ | +| TextMetrics | 文本的尺寸信息
从API version 9开始,该接口支持在ArkTS卡片中使用。 | **TextMetrics类型描述:** @@ -1009,6 +1023,8 @@ stroke(path?: Path2D): void 进行边框绘制操作。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1058,6 +1074,8 @@ beginPath(): void 创建一个新的绘制路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -1101,6 +1119,8 @@ moveTo(x: number, y: number): void 路径从当前点移动到指定点。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -1149,6 +1169,8 @@ lineTo(x: number, y: number): void 从当前点到指定点进行路径连接。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1197,6 +1219,8 @@ closePath(): void 结束当前路径形成一个封闭路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -1240,12 +1264,14 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu 通过指定图像和重复方式创建图片填充的模板。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | | ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | null | 图源对象,具体参考ImageBitmap对象。 | -| repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'。 | +| repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、 'repeat-y'、'no-repeat'、'clamp'、'mirror'。 | **返回值:** @@ -1294,6 +1320,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, 创建三次贝赛尔曲线的路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1346,6 +1374,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void 创建二次贝赛尔曲线的路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1396,6 +1426,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, 绘制弧线路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1447,6 +1479,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void 依据圆弧经过的点和圆弧半径创建圆弧路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1497,6 +1531,8 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number 在规定的矩形区域绘制一个椭圆。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -1549,6 +1585,8 @@ rect(x: number, y: number, w: number, h: number): void 创建矩形路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1597,6 +1635,8 @@ fill(fillRule?: CanvasFillRule): void 对封闭路径进行填充。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1638,6 +1678,8 @@ fill(path: Path2D, fillRule?: CanvasFillRule): void 对封闭路径进行填充。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1695,6 +1737,8 @@ clip(fillRule?: CanvasFillRule): void 设置当前路径为剪切路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1741,6 +1785,8 @@ clip(path:Path2D, fillRule?: CanvasFillRule): void 设置封闭路径为剪切路径。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1797,6 +1843,8 @@ filter(filter: string): void 为Canvas图形设置各类滤镜效果。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 说明 | @@ -1810,6 +1858,8 @@ getTransform(): Matrix2D 获取当前被应用到上下文的转换矩阵。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### resetTransform @@ -1817,6 +1867,8 @@ resetTransform(): void 使用单位矩阵重新设置当前变形。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### direction @@ -1824,6 +1876,8 @@ direction(direction: CanvasDirection): void 绘制文本时,描述当前文本方向的属性。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + ### rotate @@ -1831,6 +1885,8 @@ rotate(angle: number): void 针对当前坐标轴进行顺时针旋转。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1876,6 +1932,8 @@ scale(x: number, y: number): void 设置canvas画布的缩放变换属性,后续的绘制操作将按照缩放比例进行缩放。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -1924,6 +1982,8 @@ transform(a: number, b: number, c: number, d: number, e: number, f: number): voi transform方法对应一个变换矩阵,想对一个图形进行变化的时候,只要设置此变换矩阵相应的参数,对图形的各个定点的坐标分别乘以这个矩阵,就能得到新的定点的坐标。矩阵变换效果可叠加。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + > **说明:** > 变换后的坐标计算方式(x和y为变换前坐标,x'和y'为变换后坐标): > @@ -1987,6 +2047,8 @@ setTransform(a: number, b: number, c: number, d: number, e: number, f: number): setTransform方法使用的参数和transform()方法相同,但setTransform()方法会重置现有的变换矩阵并创建新的变换矩阵。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2040,6 +2102,8 @@ translate(x: number, y: number): void 移动当前坐标系的原点。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2091,6 +2155,8 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: 进行图像绘制。 +从API version 9开始,该接口支持在ArkTS卡片中使用,卡片中不支持PixelMap对象。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2144,6 +2210,8 @@ createImageData(sw: number, sh: number): ImageData 根据宽高创建ImageData对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认 | 描述 | @@ -2156,6 +2224,8 @@ createImageData(imageData: ImageData): ImageData 根据已创建的ImageData对象创建新的ImageData对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认 | 描述 | @@ -2217,6 +2287,8 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData 以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagedata.md)对象。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2276,6 +2348,8 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: 使用[ImageData](ts-components-canvas-imagedata.md)数据填充新的矩形区域。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2331,6 +2405,8 @@ setLineDash(segments: number[]): void 设置画布的虚线样式。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 描述 | @@ -2375,6 +2451,8 @@ getLineDash(): number[] 获得当前画布的虚线样式。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **返回值:** | 类型 | 说明 | @@ -2481,6 +2559,8 @@ imageSmoothingQuality(quality: imageSmoothingQuality) 用于设置图像平滑度。该接口为空接口。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 描述 | @@ -2544,6 +2624,8 @@ restore(): void 对保存的绘图上下文进行恢复。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -2585,6 +2667,8 @@ save(): void 对当前的绘图上下文进行保存。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **示例:** ```ts @@ -2626,6 +2710,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void 创建一个线性渐变色。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2678,6 +2764,8 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, 创建一个径向渐变色。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | @@ -2725,7 +2813,59 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ![zh-cn_image_0000001238952407](figures/zh-cn_image_0000001238952407.png) +### createConicGradient10+ + +createConicGradient(startAngle: number, x: number, y: number): CanvasGradient + +创建一个圆锥渐变色。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ---------- | ------ | ---- | ------ | ------------------------------------------------------------ | +| startAngle | number | 是 | 0 | 开始渐变的角度,以弧度为单位。角度测量从中心右侧水平开始,顺时针移动。 | +| x | number | 是 | 0 | 圆锥渐变的中心x轴坐标。单位:vp | +| y | number | 是 | 0 | 圆锥渐变的中心y轴坐标。单位:vp | + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct OffscreenCanvasConicGradientPage { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffffff') + .onReady(() =>{ + var grad = this.offContext.createConicGradient(0, 50, 80) + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') + this.offContext.fillStyle = grad + this.offContext.fillRect(0, 30, 100, 100) + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + ![zh-cn_image_0000001239032419](figures/zh-cn_image_0000001239032420.png) ## CanvasPattern 一个Object对象, 通过[createPattern](#createpattern)方法创建。 + +从API version 9开始,该接口支持在ArkTS卡片中使用。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index b2ae6d899c62fc7d28c04d633f6f85905059f63c..d097a205da899a01cdeee8b1a914211c6dc42a7f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -752,6 +752,8 @@ abstract get(): T 读取从AppStorage/LocalStorage同步属性的数据。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **返回值:** | 类型 | 描述 | @@ -770,9 +772,10 @@ prop1.get(); // prop1.get()=47 abstract set(newValue: T): void - 设置AppStorage/LocalStorage同步属性的数据。 +从API version 9开始,该接口支持在ArkTS卡片中使用。 + **参数:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md index e01fba5ea85912d2e78a357edc0ee7d7ff3b6bbf..928f97b47419f53056537d8f24313112ba377a15 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md @@ -3,7 +3,7 @@ > **说明:** > - 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > -> - 仅当父组件是 Flex、Column、Row 时生效。 +> - 仅当父组件是 Flex、Column、Row 、GridRow时生效。 ## 属性 @@ -13,7 +13,7 @@ | flexBasis | number \| string | 设置组件在父容器主轴方向上的基准尺寸。
默认值:'auto'(表示组件在主轴方向上的基准尺寸为组件原本的大小)。
不支持百分比设置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | flexGrow | number | 设置父容器的剩余空间分配给此属性所在组件的比例。
默认值:0
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | flexShrink | number | 设置父容器压缩尺寸分配给此属性所在组件的比例。
父容器为Row、Column时,默认值:0
父容器为flex时,默认值:1
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | 子组件在父容器交叉轴的对齐格式,会覆盖Flex布局容器中的alignItems设置。
默认值:ItemAlign.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | 子组件在父容器交叉轴的对齐格式,会覆盖Flex、Column、Row、GridRow布局容器中的alignItems设置。
GridCol可以绑定alignsSelf属性来改变它自身在交叉轴方向上的布局。
默认值:ItemAlign.Auto
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index a2666355283735e6935d12b6faf42a3fba6d683b..11f0c61a7e44545b0374a82b260187074c633e07 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -14,7 +14,7 @@ | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | blur | number | - | 为当前组件添加内容模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。
取值范围:[0, +∞)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | backdropBlur | number | - | 为当前组件添加背景模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。
取值范围:[0, +∞)
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| shadow | [ShadowOptions](#shadowoptions对象说明) \| [ShadowStyle](#shadowstyle10枚举说明) | - | 为当前组件添加阴影效果。
入参类型为ShadowOptions时,可以指定模糊半径、阴影的颜色、X轴和Y轴的偏移量。
入参类型为ShadowStyle时,可指定不同阴影样式。
从API version 9开始,该接口支持在ArkTS卡片中使用。
**说明:**
ArkTS卡片上不支持参数为 [ShadowStyle](#shadowstyle10枚举说明)类型。 | +| shadow | [ShadowOptions](#shadowoptions对象说明) \| [ShadowStyle](#shadowstyle10枚举说明) | - | 为当前组件添加阴影效果。
入参类型为ShadowOptions时,可以指定模糊半径、阴影的颜色、X轴和Y轴的偏移量。
入参类型为ShadowStyle时,可指定不同阴影样式。
从API version 9开始,该接口支持在ArkTS卡片中使用,ArkTS卡片上不支持参数为 [ShadowStyle](#shadowstyle10枚举说明)类型。 | | grayscale | number | 0.0 | 为当前组件添加灰度效果。值定义为灰度转换的比例,入参1.0则完全转为灰度图像,入参则0.0图像无变化,入参在0.0和1.0之间时,效果呈线性变化。(百分比)
取值范围:[0, 1]
**说明:**
设置小于0的值时,按值为0处理,设置大于1的值时,按值为1处理。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | brightness | number | 1.0 | 为当前组件添加高光效果,入参为高光比例,值为1时没有效果,小于1时亮度变暗,0为全黑,大于1时亮度增加,数值越大亮度越大。
取值范围:[0, +∞)
**说明:**
设置小于0的值时,按值为0处理。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | saturate | number | 1.0 | 为当前组件添加饱和度效果,饱和度为颜色中的含色成分和消色成分(灰)的比例,入参为1时,显示原图像,大于1时含色成分越大,饱和度越大,小于1时消色成分越大,饱和度越小。(百分比)
取值范围:[0, +∞)
**说明:**
设置小于0的值时,按值为0处理。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md index e15fc1b17998ce850e2943cb213129e24f0153be..0368594df8a4a2c21c69d143b24dfbf28605d670 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md @@ -12,8 +12,8 @@ | 名称 | 参数类型 | 描述 | | ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| bindMenu | content: Array<[MenuItem](#menuitem)> \| [CustomBuilder](ts-types.md#custombuilder8),
options10+: [MenuOptions](#menuoptions10)10+ | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持图标+文本排列和自定义两种功能。
content: 必填,配置菜单项图标和文本的数组,或者自定义组件
options: 非必填,配置弹出菜单的参数 | -| bindContextMenu8+ | content: [CustomBuilder](ts-types.md#custombuilder8),
responseType: [ResponseType](ts-appendix-enums.md#responsetype8) | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。 | +| bindMenu | content: Array<[MenuItem](#menuitem)> \| [CustomBuilder](ts-types.md#custombuilder8),
options: [MenuOptions](#menuoptions10) | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持图标+文本排列和自定义两种功能。
content: 必填,配置菜单项图标和文本的数组,或者自定义组件。
options: 非必填,配置弹出菜单的参数。 | +| bindContextMenu8+ | content: [CustomBuilder](ts-types.md#custombuilder8),
responseType: [ResponseType](ts-appendix-enums.md#responsetype8)
options: [ContextMenuOptions](#contextmenuoptions10) | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。
responseType: 必填。菜单弹出条件,长按或者右键点击。
options: 非必填,配置弹出菜单的参数。 | ## MenuItem @@ -29,6 +29,18 @@ | ------ | -------------------------------- | ---- | ------------------------------------------------------ | | title | string | 否 | 菜单标题。 | | offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | +| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | +| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | +| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | + +## ContextMenuOptions10+ + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | +| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | +| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | +| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 2b9226798f870d35fb1d06072aab189e4d5a8a1f..78d5ef99f809051c57c17570600bc562bb5422fd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -10,45 +10,45 @@ ## 接口 -| 名称 | 参数类型 | 描述 | -| ---------- | ------------------------------------- | --------------------------------------- | -| bindPopup | show: boolean,
popup: [PopupOptions](#popupoptions类型说明) \| [CustomPopupOptions](#custompopupoptions8类型说明)8+ | 给组件绑定Popup弹窗,设置参数show为true弹出弹框。
show: 弹窗显示状态,默认值为false,隐藏弹窗。
popup: 配置当前弹窗提示的参数。 | +| 名称 | 参数类型 | 描述 | +| --------- | ---------------------------------------- | ---------------------------------------- | +| bindPopup | show: boolean,
popup: [PopupOptions](#popupoptions类型说明) \| [CustomPopupOptions](#custompopupoptions8类型说明)8+ | 给组件绑定Popup弹窗,设置参数show为true弹出弹框。
show: 弹窗显示状态,默认值为false,隐藏弹窗。
popup: 配置当前弹窗提示的参数。 | ## PopupOptions类型说明 -| 名称 | 类型 | 必填 | 描述 | -| -------------------------| ------------------------------------------------| -----| ----------------------------------------- | -| message | string | 是 | 弹窗信息内容。 | -| placementOnTop | boolean | 否 | 是否在组件上方显示,默认值为false。 | -| primaryButton | {
value: string,
action: () => void
} | 否 | 第一个按钮。
value: 弹窗里主按钮的文本。
action: 点击主按钮的回调函数。 | -| secondaryButton | {
value: string,
action: () => void
} | 否 | 第二个按钮。
value: 弹窗里辅助按钮的文本。
action: 点击辅助按钮的回调函数。 | -| onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数isVisible为弹窗当前的显示状态。 | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。如果显示在屏幕边缘,气泡会自动左右偏移,数值为0时箭头始终指向绑定组件。 | -| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | -| mask10+ | boolean \| [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置气泡是否有遮罩层及遮罩颜色。如果设置为false,则没有遮罩层;如果设置为true,则设置有遮罩层并且颜色为透明色;如果设置为Color,则为遮罩层的颜色。 | -| messageOptions10+ | [PopupMessageOptions](#popupmessageoptions10) | 否 | 设置弹窗信息文本参数。 | -| targetSpace10+ | [Length](ts-types.md#length) | 否 | 设置popup与目标的间隙。 | +| 名称 | 类型 | 必填 | 描述 | +| ---------------------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| message | string | 是 | 弹窗信息内容。 | +| placementOnTop | boolean | 否 | 是否在组件上方显示,默认值为false。 | +| primaryButton | {
value: string,
action: () => void
} | 否 | 第一个按钮。
value: 弹窗里主按钮的文本。
action: 点击主按钮的回调函数。 | +| secondaryButton | {
value: string,
action: () => void
} | 否 | 第二个按钮。
value: 弹窗里辅助按钮的文本。
action: 点击辅助按钮的回调函数。 | +| onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数isVisible为弹窗当前的显示状态。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。如果显示在屏幕边缘,气泡会自动左右偏移,数值为0时箭头始终指向绑定组件。 | +| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | +| mask10+ | boolean \| [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置气泡是否有遮罩层及遮罩颜色。如果设置为false,则没有遮罩层;如果设置为true,则设置有遮罩层并且颜色为透明色;如果设置为Color,则为遮罩层的颜色。 | +| messageOptions10+ | [PopupMessageOptions](#popupmessageoptions10) | 否 | 设置弹窗信息文本参数。 | +| targetSpace10+ | [Length](ts-types.md#length) | 否 | 设置popup与目标的间隙。 | ## PopupMessageOptions10+类型说明 -| 名称 | 类型 | 必填 | 描述 | -| --------- | ------------------------------------------ | ---- | ---------------------- | -| textColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置弹窗信息文本颜色。 | -| font | [Font](ts-types.md#Font) | 否 | 设置弹窗信息字体属性。 | +| 名称 | 类型 | 必填 | 描述 | +| --------- | ---------------------------------------- | ---- | ----------- | +| textColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置弹窗信息文本颜色。 | +| font | [Font](ts-types.md#Font) | 否 | 设置弹窗信息字体属性。 | ## CustomPopupOptions8+类型说明 -| 名称 | 类型 | 必填 | 描述 | -| -------------------------| ------------------------- | ---- | ---------------------------------------------------- | -| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。 | -| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | -| popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 | -| enableArrow | boolean | 否 | 是否显示箭头。
从API Version 9开始,如果箭头所在方位侧的气泡长度不足以显示下箭头,则会默认不显示箭头。比如:placement设置为Left,此时如果气泡高度小于箭头的宽度(32vp)与气泡圆角两倍(48vp)之和(80vp),则实际不会显示箭头。
默认值:true | -| autoCancel | boolean | 否 | 页面有操作时,是否自动关闭气泡。
默认值:true | -| onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。如果显示在屏幕边缘,气泡会自动左右偏移,数值为0时箭头始终指向绑定组件。 | -| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | -| mask10+ | boolean \| [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置气泡是否有遮罩层及遮罩颜色。如果设置为false,则没有遮罩层;如果设置为true,则设置有遮罩层并且颜色为透明色;如果设置为Color,则为遮罩层的颜色。 | -| targetSpace10+ | [Length](ts-types.md#length) | 否 | 设置popup与目标的间隙。 | +| 名称 | 类型 | 必填 | 描述 | +| ---------------------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。 | +| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | +| popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 | +| enableArrow | boolean | 否 | 是否显示箭头。
从API Version 9开始,如果箭头所在方位侧的气泡长度不足以显示下箭头,则会默认不显示箭头。比如:placement设置为Left,此时如果气泡高度小于箭头的宽度(32vp)与气泡圆角两倍(48vp)之和(80vp),则实际不会显示箭头。
默认值:true | +| autoCancel | boolean | 否 | 页面有操作时,是否自动关闭气泡。
默认值:true | +| onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。如果显示在屏幕边缘,气泡会自动左右偏移,数值为0时箭头始终指向绑定组件。 | +| showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | +| mask10+ | boolean \| [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置气泡是否有遮罩层及遮罩颜色。如果设置为false,则没有遮罩层;如果设置为true,则设置有遮罩层并且颜色为透明色;如果设置为Color,则为遮罩层的颜色。 | +| targetSpace10+ | [Length](ts-types.md#length) | 否 | 设置popup与目标的间隙。 | ## 示例 ```ts @@ -111,7 +111,7 @@ struct PopupExample { .bindPopup(this.customPopup, { builder: this.popupBuilder, placement: Placement.Top, - mask: {color: 0x33000000}, + maskColor: '0x33000000', popupColor: Color.Yellow, enableArrow: true, showInSubWindow: false, diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 5cb4dcb09c9d2b7ff7c23ede334363329d791044..3cd1617601ff2bd83cc79b17ccb78e05868ab016 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -13,13 +13,13 @@ | 名称 | 参数类型 | 描述 | | -----------| ---------------------------------------- | ------------------------------------ | -| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 设置字体颜色。 | -| fontSize | [Length](ts-types.md#length) | 设置字体大小,Length为number类型时,使用fp单位。字体默认大小16。不支持设置百分比字符串。 | -| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 设置字体样式。
默认值:FontStyle.Normal | -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | 设置文本的字体粗细,number类型取值[100, 900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。
默认值:FontWeight.Normal | -| fontFamily | string \| [Resource](ts-types.md#resource) | 设置字体列表。默认字体'HarmonyOS Sans',且当前只支持这种字体。| -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。 | -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
} | +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 设置字体颜色。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fontSize | [Length](ts-types.md#length) | 设置字体大小,Length为number类型时,使用fp单位。字体默认大小16。不支持设置百分比字符串。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 设置字体样式。
默认值:FontStyle.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | 设置文本的字体粗细,number类型取值[100, 900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。
默认值:FontWeight.Normal
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| fontFamily | string \| [Resource](ts-types.md#resource) | 设置字体列表。默认字体'HarmonyOS Sans',且当前只支持这种字体。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
}
从API version 9开始,该接口支持在ArkTS卡片中使用。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md index ef742a9b6e92db10ca0c52ca5183d30f8318776c..69cfb3c75aa80b389630c4905ac4f41167c683e8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md @@ -98,7 +98,7 @@ struct ScrollExample { .scrollable(ScrollDirection.Vertical) .scrollBar(BarState.On) .scrollBarColor(Color.Gray) - .scrollBarWidth(30) + .scrollBarWidth(10) .onScroll((xOffset: number, yOffset: number) => { console.info(xOffset + ' ' + yOffset) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index 39760592bf318d9c0f0166ab0fd4a75f9e7e251d..ae6cbbb52c75105f43dc6bc864026e0803b4d556 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -45,6 +45,113 @@ ## 示例 +### 示例1 + +```ts +@Observed +class ClassA { + public name: string + public bol: boolean + + constructor(name: string, bol: boolean) { + this.name = name + this.bol = bol + } +} + +@Extend(Text) function textStyle() { + .width('25%') + .height(35) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xAFEEEE) +} + +@Entry +@Component +struct DragExample { + @State arr: ClassA[] = [new ClassA('A', true), new ClassA('B', true), new ClassA('C', true)] + @State dragIndex: number = 0 + + changeIndex(index1: number, index2: number) { // 交换数组位置 + [this.arr[index1], this.arr[index2]] = [this.arr[index2], this.arr[index1]]; + } + + build() { + Column() { + Row({ space: 15 }) { + List({ space: 20 }) { + ForEach(this.arr, (item, index) => { + ListItem() { + Column() { + Child({ a: this.arr[index] }) + } + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Down) { + this.dragIndex = index // 获取当前拖拽子组件的索引 + console.info('onTouch' + this.dragIndex) + } + }) + } + }) + } + .listDirection(Axis.Horizontal) + .onDrop((event: DragEvent, extraParams: string) => { // 绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。 + let jsonString = JSON.parse(extraParams); + this.changeIndex(this.dragIndex, jsonString.insertIndex) + }) + }.padding({ top: 10, bottom: 10 }).margin(10) + + }.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 }) + } +} + +@Component +struct Child { + @ObjectLink a: ClassA + + @Builder pixelMapBuilder() { + Column() { + Text(this.a.name) + .width('50%') + .height(60) + .fontSize(16) + .borderRadius(10) + .textAlign(TextAlign.Center) + .backgroundColor(Color.Yellow) + } + } + + build() { + Column() { + Text(this.a.name) + .textStyle() + .visibility(this.a.bol ? Visibility.Visible : Visibility.None) + .onDragStart(() => { // 第一次拖拽此事件绑定的组件时,触发回调。 + this.a.bol = false // 控制显隐 + return this.pixelMapBuilder() // 设置拖拽过程中显示的图片。 + }) + .onTouch((event: TouchEvent) => { + if (event.type === TouchType.Up) { + this.a.bol = true + } + }) + Text('') + .width('25%') + .height(35) + .fontSize(16) + .textAlign(TextAlign.Center) + .border({ width: 5, color: 'red' }) + .visibility(!this.a.bol ? Visibility.Visible : Visibility.None) + } + } +} +``` + +![drag-drop](figures/drag-drop.gif) + +### 示例2 + ```ts // xxx.ets @Extend(Text) function textStyle () { diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-request.md b/zh-cn/application-dev/reference/errorcodes/errorcode-request.md index 12f9370e04454e4208eccdb01b53ce610f695044..3788520ef8d782e87703a9f664e0240e8b9df126 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-request.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-request.md @@ -30,11 +30,11 @@ Bad file path. **错误描述** -在调用uploadFile或downloadFile接口时,文件路径不合法。 +在调用uploadFile或downloadFile接口时,文件路径不合法或文件路径下文件已存在。 **可能原因** -该错误码表示文件路径异常,可能原因文件路径错误。 +该错误码表示文件路径异常,可能原因文件路径错误或文件路径下文件已存在。 **处理步骤** diff --git a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md index fcce8eaa40a6b08002d09bfdde617cd87d12b167..00e40e5e37abeee7c8e2c84c2d88bd9888bc6bf9 100644 --- a/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md +++ b/zh-cn/application-dev/reference/native-apis/_ohos_pixel_map_info.md @@ -21,10 +21,10 @@ | 成员变量名称 | 描述 | | -------- | -------- | -| [width](#width) | 图片的高,用pixels表示。 | -| [height](#height) | Pixel的格式。 | +| [width](#width) | 图片的宽,用pixels表示。 | +| [height](#height) | 图片的高,用pixels表示。 | | [rowSize](#rowsize) | 每行的bytes数。 | -| [pixelFormat](#pixelformat) | 图片的宽,用pixels表示。 | +| [pixelFormat](#pixelformat) | Pixel的格式。 | ## 结构体成员变量说明 diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index 1438f9408048c340482f1dc71ae676e838f31e93..5ace3c7b4684e3f357475b49c4c4c5a1161837b1 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -974,6 +974,26 @@ **ACL使能**:TRUE +## ohos.permission.ENTERPRISE_SET_NETWORK + +允许设备管理员设置网络信息。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + +## ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY + +允许设备管理员设置应用运行管理策略。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + ## ohos.permission.NFC_TAG 允许应用读取Tag卡片。 @@ -1628,6 +1648,26 @@ **ACL使能**:TRUE +## ohos.permission.CLOUDFILE_SYNC_MANAGER + +允许应用获取端云同步管理能力。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + +## ohos.permission.CLOUDFILE_SYNC + +允许应用使用端云同步能力。 + +**权限级别**:system_basic + +**授权方式**:system_grant + +**ACL使能**:TRUE + ## ohos.permission.FILE_ACCESS_MANAGER 允许文件管理类应用通过FAF框架访问公共数据文件。 @@ -1778,6 +1818,16 @@ **ACL使能**:FALSE +## ohos.permission.GET_INSTALLED_BUNDLE_LIST + +允许应用读取已安装应用列表。 + +**权限级别**:system_basic + +**授权方式**:user_grant + +**ACL使能**:TRUE + ## ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS 允许应用管理系统分布式帐号信息。 diff --git a/zh-cn/application-dev/task-management/workscheduler-extensionability.md b/zh-cn/application-dev/task-management/workscheduler-extensionability.md index 58bc77dcf57c45447de4413a708775b4d42ad84e..d331a39dad6f0f011468e96294005989835efae4 100644 --- a/zh-cn/application-dev/task-management/workscheduler-extensionability.md +++ b/zh-cn/application-dev/task-management/workscheduler-extensionability.md @@ -209,5 +209,5 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 针对WorkSchedulerExtensionAbility开发,有以下相关示例可供参考: -- [WorkScheduler的创建与使用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/WorkScheduler) +- [WorkScheduler的创建与使用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) diff --git a/zh-cn/application-dev/telephony/telephony-call.md b/zh-cn/application-dev/telephony/telephony-call.md index 0426b1df602827beb3e6b163ecd893241b475545..483a6ecc5dd590f5038d279c8a091f8417467a7a 100644 --- a/zh-cn/application-dev/telephony/telephony-call.md +++ b/zh-cn/application-dev/telephony/telephony-call.md @@ -113,4 +113,4 @@ ohos.permission.PLACE_CALL权限级别为system_basic,在申请权限前,请 拨打电话有以下相关实例可供参考: -- [拨打电话](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/Call) +- [拨打电话](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Telephony/Call) diff --git a/zh-cn/application-dev/telephony/telephony-sms.md b/zh-cn/application-dev/telephony/telephony-sms.md index 15050311040ed94a7a8d10cde184e8e512cd8498..ca4f78bcebbdf60d852f19795379df78b05acb24 100644 --- a/zh-cn/application-dev/telephony/telephony-sms.md +++ b/zh-cn/application-dev/telephony/telephony-sms.md @@ -115,4 +115,4 @@ ## 相关实例 针对短信的使用,有以下相关实例可供参考: -- [短信服务](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/Message) +- [短信服务](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Telephony/Message) diff --git a/zh-cn/application-dev/tools/aa-tool.md b/zh-cn/application-dev/tools/aa-tool.md index b29887aa695013591709fc309c8079a6886782d6..1be35ff10856c4fe4d40d5c8b55e1f3711e77699 100644 --- a/zh-cn/application-dev/tools/aa-tool.md +++ b/zh-cn/application-dev/tools/aa-tool.md @@ -72,7 +72,7 @@ Ability assistant(Ability助手,简称为aa),是实现应用及测试用 | -------- | -------- | -------- | | -h/--help | - | 帮助信息。 | | -a/--all | - | 打印所有mission内的应用组件信息。 | - | -l/--mission-list | type(缺省打印全部) | 服务侧为了方便管理任务链,内部维护了4种类型的任务链。
可取值:
- NORMAL: 正常启动的任务链(比如A拉起B拉起C, 则对应的任务链是A->B->C)
- DEFAULT_STANDARD: 已经被破坏的任务链中的任务, 启动模式为standard的任务被放到该任务链中, 这里面的任务之间没有关联关系
- DEFAULT_SINGLE: 已经被破坏的任务链中的任务, 启动模式为singleton的任务被放到该任务链中, 这里面的任务之间没有关联关系
- LAUNCHER: launcher的任务链 | + | -l/--mission-list | type(缺省打印全部) | 服务侧为了方便管理任务链,内部维护了4种类型的任务链。
可取值:
- NORMAL:正常启动的任务链(比如A拉起B拉起C, 则对应的任务链是A->B->C)
- DEFAULT_STANDARD:已经被破坏的任务链中的任务, 启动模式为`multiton`的任务被放到该任务链中, 这里面的任务之间没有关联关系
- DEFAULT_SINGLE:已经被破坏的任务链中的任务, 启动模式为`singleton`的任务被放到该任务链中, 这里面的任务之间没有关联关系
- LAUNCHER:launcher的任务链 | | -e/--extension | elementName | 打印扩展组件信息。 | | -u/--userId | UserId | 打印指定UserId的栈信息,需要和其他参数组合使用,例如aa dump -a -u 100、aa dump -d -u 100。 | | -d/--data | - | 打印DataAbility相关信息。 | diff --git a/zh-cn/application-dev/tools/lldb-tool.md b/zh-cn/application-dev/tools/lldb-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..1764dca6756c9520a1272189e4ade6afc08f2581 --- /dev/null +++ b/zh-cn/application-dev/tools/lldb-tool.md @@ -0,0 +1,101 @@ +# LLDB调试器使用指导 +## 概述 +LLDB(Low Lever Debugger)是新一代高性能调试器。 + +当前Openharmony中的LLDB工具是在[llvm15.0.4](https://github.com/llvm/llvm-project/releases/tag/llvmorg-15.0.4)基础上适配演进出来的工具,支持在桌面和Openharmony设备或模拟器上调试。 +## 工具获取 +通过OpenHarmony的SDK获取,从以下链接获取SDK:http://ci.openharmony.cn/dailys/dailybuilds + +lldb工具在SDK中的路径: +``` +\ohos-sdk\[system]\native\llvm +``` +其中system可选windows/linux/darwin。 + +以windows平台为例,解压SDK后,lldb.exe的存放路径为: +``` +\ohos-sdk\windows\native\llvm\bin +``` + +## 支持平台与架构 + +### 本地调试 +#### linux平台调试使用示例 +1.获取到与lldb同一版本的clang编译器生成的带有调试信息的可执行文件filename + +2.指定调试的文件名,终端窗口执行命令: +``` +./lldb filename +``` +3.在代码中main函数处打断点,lldb界面下执行命令: +``` +(lldb) b main +``` +4.运行程序,使程序停在断点处,lldb界面下执行命令: +``` +(lldb) run +``` +5.执行后续调试操作 +### 远程调试 + +> **说明:远程调试时需要lldb-server和lldb配合使用** +- windows平台ohos设备调试(arm架构调试) +- windows平台ohos设备调试(aarch64架构调试) +- windows平台模拟器调试 +- mac(M1)平台ohos设备调试(arm架构调试) +- mac(M1)平台ohos设备调试(aarch64架构调试) +- mac(M1)平台模拟器调试 +- mac(x86)平台ohos设备调试(arm架构调试) +- mac(x86)平台ohos设备调试(aarch64架构调试) +- mac(x86)平台模拟器调试 +- linux平台ohos设备调试(arm架构调试) +- linux平台ohos设备调试(aarch64架构调试) + +#### 远程调试使用示例 + +linux平台连接arm架构ohos设备远程调试 + +1.设备上运行带有调试信息的可执行文件: + +``` +./filename +``` +2.将lldb-server推送到设备,运行lldb-server。 + +命令行窗口1: + +``` +hdc file send lldb-server /data/local/tmp +hdc shell ./data/local/tmp/lldb-server p --server --listen "*:8080" +``` +> **说明:其中/data/local/tmp为设备上指定的目录,8080为监听端口,均可自定义** + +3.在另一窗口启动lldb,选择远端ohos并连接。 + +命令行窗口2: + +``` +./lldb +(lldb) platform select remote-ohos +(lldb) platform connect connect://localhost:8080 +``` +4.打断点,以及后续调试操作。 + +命令行窗口2: + +``` +(lldb) breakpoint set --file --line +(lldb) process attach --name process-name +``` +## lldb调试器提供功能列表 +- 将程序加载到lldb +- 设置断点 +- 设置观察点 +- 启动或attach到程序 +- 控制程序的执行 +- 检查线程状态 +- 检查栈帧状态 + +## 其他更多功能与具体命令请参考 +[LLDB工具使用指导](https://gitee.com/openharmony/third_party_llvm-project/blob/master/lldb/README_zh.md) + diff --git a/zh-cn/application-dev/ui/arkts-drawing-customization-on-canvas.md b/zh-cn/application-dev/ui/arkts-drawing-customization-on-canvas.md index ab01b4499f00cd60e282874ecf0005c62df7c736..bad333289f075b3a30510847345f14230a26ee03 100644 --- a/zh-cn/application-dev/ui/arkts-drawing-customization-on-canvas.md +++ b/zh-cn/application-dev/ui/arkts-drawing-customization-on-canvas.md @@ -89,7 +89,7 @@ Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRe import lottie from '@ohos/lottie' ``` - 具体接口参考[Lottie](../reference/arkui-ts/ts-components-canvas-lottie.md),相关实例请参考[Lottie实例](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Lottie)。 + 具体接口参考[Lottie](../reference/arkui-ts/ts-components-canvas-lottie.md),相关实例请参考[Lottie实例](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Lottie)。 >**说明:** > diff --git a/zh-cn/application-dev/ui/arkts-graphics-display.md b/zh-cn/application-dev/ui/arkts-graphics-display.md index 0f415eee201bf176ccf23741d554295206afcb43..196046e3ff0e846292fbdde4aad88f4d3aa78fbc 100644 --- a/zh-cn/application-dev/ui/arkts-graphics-display.md +++ b/zh-cn/application-dev/ui/arkts-graphics-display.md @@ -78,9 +78,9 @@ Image支持加载存档图、多媒体像素图两种类型。 @Entry @Component struct Index { - private imgDatas: string[] = []; + @State imgDatas: string[] = []; // 获取照片url集 - async getAllImg() { + getAllImg() { let photoPicker = new picker.PhotoViewPicker(); let result = new Array(); try { @@ -89,29 +89,31 @@ Image支持加载存档图、多媒体像素图两种类型。 PhotoSelectOptions.maxSelectNumber = 5; let photoPicker = new picker.PhotoViewPicker(); photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { - result = PhotoSelectResult.photoUris; + this.imgDatas = PhotoSelectResult.photoUris; + console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); }).catch((err) => { console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`); }); } catch (err) { console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`); } - return result; } // aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中 async aboutToAppear() { - this.imgDatas = await this.getAllImg(); + this.getAllImg(); } // 使用imgDatas的url加载图片。 build() { - Grid() { - ForEach(this.imgDatas, item => { - GridItem() { - Image(item) - .width(200) - } - }, item => JSON.stringify(item)) - } + Column() { + Grid() { + ForEach(this.imgDatas, item => { + GridItem() { + Image(item) + .width(200) + } + }, item => JSON.stringify(item)) + } + }.width('100%').height('100%') } } ``` diff --git a/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md b/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md index 0525dec32af01ab3ea0f2fa451c9f7585dc65a8e..1547b28a4a8a9695ff1d6235e2b09821d865ad24 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-create-grid.md @@ -336,4 +336,4 @@ Grid() { 如需详细了解网格布局的实现,请参考以下示例: -- [分布式计算器](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/EtsDistributedCalc) +- [分布式计算器](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/ArkTSDistributedCalc) diff --git a/zh-cn/application-dev/ui/arkts-layout-development-create-looping.md b/zh-cn/application-dev/ui/arkts-layout-development-create-looping.md index 41436324259f168c0ddf74f3c5ee137bb51a183a..714b7af86eaa66fffc8827b94a7aa7d5ddb43834 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-create-looping.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-create-looping.md @@ -280,7 +280,7 @@ Swiper(this.swiperController) { ## 每页显示多个子页面 -Swiper支持在一个页面内同时显示多个子组件,通过[displayCount](../reference/arkui-ts/ts-container-swiper.md#%E5%B1%9E%E6%80%A7)属性设置。 +Swiper支持在一个页面内同时显示多个子组件,通过[displayCount](../reference/arkui-ts/ts-container-swiper.md#属性)属性设置。 设置一个页面内显示两个子组件: diff --git a/zh-cn/application-dev/ui/arkts-layout-development-linear.md b/zh-cn/application-dev/ui/arkts-layout-development-linear.md index 9623a681192b05aa22eb310d3083422e8b112dc9..1dee7a3963c2ec6f14636b6f3fda5e5d94820f9a 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-linear.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-linear.md @@ -22,9 +22,9 @@ - 布局子元素:布局容器内部的元素。 -- 主轴:线性布局容器在布局方向上的轴线,子元素默认沿主轴排列。Row容器主轴为纵向,Column容器主轴为横向。 +- 主轴:线性布局容器在布局方向上的轴线,子元素默认沿主轴排列。Row容器主轴为横向,Column容器主轴为纵向。 -- 交叉轴:垂直于主轴方向的轴线。Row容器交叉轴为横向,Column容器交叉轴为纵向。 +- 交叉轴:垂直于主轴方向的轴线。Row容器交叉轴为纵向,Column容器交叉轴为横向。 - 间距:布局子元素的纵向间距。 diff --git a/zh-cn/application-dev/ui/arkts-layout-development-media-query.md b/zh-cn/application-dev/ui/arkts-layout-development-media-query.md index 5b102cdad3b3400310dd128bbe77abf126fd75e8..513f2b77efe02908cd6d40005847fd918a41e993 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-media-query.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-media-query.md @@ -260,4 +260,4 @@ struct MediaQueryExample { 基于媒体查询,可参考以下实例: -[媒体查询](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MediaQuery):使用媒体查询,完成在不同设备上显示不同的界面效果。 +[媒体查询](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/ArkTsComponentClollection/MediaQuery):使用媒体查询,完成在不同设备上显示不同的界面效果。 diff --git a/zh-cn/application-dev/ui/arkts-layout-update-animation.md b/zh-cn/application-dev/ui/arkts-layout-update-animation.md index bb0787e27dca59fce8bb5dd5d78ae89bece61bbf..afe25945bd95adb73e448adb55848626a6b9be65 100644 --- a/zh-cn/application-dev/ui/arkts-layout-update-animation.md +++ b/zh-cn/application-dev/ui/arkts-layout-update-animation.md @@ -1,13 +1,13 @@ # 布局更新动画 -[属性动画](../reference/arkui-ts/ts-animatorproperty.md)(animation)和[显式动画](../reference/arkui-ts/ts-explicit-animation.md)(animateTo)是ArkUI提供的最基础和常用的动画功能。在布局属性(如[尺寸属性](../reference/arkui-ts/ts-universal-attributes-size.md)、[位置属性](../reference/arkui-ts/ts-universal-attributes-location.md))发生变化时,可以通过属性动画或显式动画,按照动画参数过渡到新的布局参数状态。 +[显式动画](../reference/arkui-ts/ts-explicit-animation.md)(animateTo)和[属性动画](../reference/arkui-ts/ts-animatorproperty.md)(animation)是ArkUI提供的最基础和常用的动画功能。在布局属性(如[尺寸属性](../reference/arkui-ts/ts-universal-attributes-size.md)、[位置属性](../reference/arkui-ts/ts-universal-attributes-location.md))发生变化时,可以通过属性动画或显式动画,按照动画参数过渡到新的布局参数状态。 -| 动画类型 | 特点 | 适用场景 | -| ---- | ---------------------------------------- | -------- | -| 属性动画 | 动画设置简单,属性变化时自动触发动画。 | 较简单的动画场景 | +| 动画类型 | 特点 | +| ---- | ---------------------------------------- | | 显式动画 | 闭包内的变化均会触发动画,包括由数据变化引起的组件的增删、组件属性的变化等,可以做较为复杂的动画。 | 较复杂的动画场景 | +| 属性动画 | 动画设置简单,属性变化时自动触发动画。 | ## 使用显式动画产生布局更新动画 @@ -263,8 +263,8 @@ struct LayoutChange2 { >**说明:** > -> 1. 使用属性动画时,会按照指定的属性动画参数执行动画。每个组件可为自己的属性配置不同参数的属性动画。 +> 1. 使用属性动画时,会按照指定的属性动画参数执行动画。每个组件可为自己的属性配置不同参数的属性动画。 > -> 2. 显式动画会对动画闭包前后造成的所有界面差异执行动画,且使用同一动画参数,适用于统一执行的场景。此外,显式动画也可以用于一些非属性变量造成的动画,如if/else的条件,ForEach使用的数组元素的删减。 +> 2. 显式动画会对动画闭包前后造成的所有界面差异执行动画,且使用同一动画参数,适用于统一执行的场景。此外,显式动画也可以用于一些非属性变量造成的动画,如if/else的条件,ForEach使用的数组元素的删减。 > -> 3. 如果一个属性配置了属性动画,且在显式动画闭包中改变该属性值,属性动画优先生效,会使用属性动画的动画参数。 +> 3. 如果一个属性配置了属性动画,且在显式动画闭包中改变该属性值,属性动画优先生效,会使用属性动画的动画参数。 diff --git a/zh-cn/application-dev/ui/arkts-navigation-tabs.md b/zh-cn/application-dev/ui/arkts-navigation-tabs.md index ba97f9bb0ad707f7c0f38afc94d777fd367096f2..1d732ea01b80ec985723661fc828ee7a611435b8 100644 --- a/zh-cn/application-dev/ui/arkts-navigation-tabs.md +++ b/zh-cn/application-dev/ui/arkts-navigation-tabs.md @@ -373,6 +373,4 @@ Tabs({ barPosition: BarPosition.End, controller: this.tabsController }) { 如需详细了解Tabs的更多实现,请参考以下示例: -- [健康生活](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/Healthy_life) - - [常用组件与布局](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ArkTSComponents) diff --git a/zh-cn/application-dev/ui/arkts-page-transition-animation.md b/zh-cn/application-dev/ui/arkts-page-transition-animation.md index 0342e53704d69dde11856ba506d007a784503e1e..31b996ce9952b8fea4ebdfecf53320bdca18e9ba 100644 --- a/zh-cn/application-dev/ui/arkts-page-transition-animation.md +++ b/zh-cn/application-dev/ui/arkts-page-transition-animation.md @@ -60,7 +60,7 @@ pageTransition() { ``` -假设页面栈为标准实例模式,即页面栈中允许存在重复的页面。可能会有4种场景,对应的页面转场效果如下表。 +假设页面栈为多实例模式,即页面栈中允许存在重复的页面。可能会有4种场景,对应的页面转场效果如下表。 | 路由操作 | 页面A转场效果 | 页面B转场效果 | @@ -118,7 +118,7 @@ pageTransition() { ``` -以上代码则完整的定义了所有可能的页面转场样式。假设页面栈为标准实例模式,即页面栈中允许存在重复的页面。可能会有4种场景,对应的页面转场效果如下表。 +以上代码则完整的定义了所有可能的页面转场样式。假设页面跳转配置为多实例模式,即页面栈中允许存在重复的页面。可能会有4种场景,对应的页面转场效果如下表。 | 路由操作 | 页面A转场效果 | 页面B转场效果 | diff --git a/zh-cn/application-dev/ui/arkts-popup-and-menu-components-popup.md b/zh-cn/application-dev/ui/arkts-popup-and-menu-components-popup.md index a0b540d4149c90e794f765fc2242c0e556c5f54a..6c2712d95d2c8ccee73972d2aa6da6942e73adc1 100644 --- a/zh-cn/application-dev/ui/arkts-popup-and-menu-components-popup.md +++ b/zh-cn/application-dev/ui/arkts-popup-and-menu-components-popup.md @@ -4,7 +4,7 @@ Popup属性可绑定在组件上显示气泡弹窗提示,设置弹窗内容、交互逻辑和显示状态。主要用于屏幕录制、信息弹出提醒等显示状态。 -气泡分为两种类型,一种是系统提供的气泡[PopupOptions](../reference/arkui-ts/ts-universal-attributes-popup.md#popupoptions%E7%B1%BB%E5%9E%8B%E8%AF%B4%E6%98%8E),一种是开发者可以自定义的气泡[CustomPopupOptions](../reference/arkui-ts/ts-universal-attributes-popup.md#custompopupoptions8%E7%B1%BB%E5%9E%8B%E8%AF%B4%E6%98%8E)。其中PopupOptions为系统提供的气泡,通过配置primaryButton、secondaryButton来设置带按钮的气泡。CustomPopupOptions通过配置[builder](../quick-start/arkts-builder.md)参数来设置自定义的气泡。 +气泡分为两种类型,一种是系统提供的气泡[PopupOptions](../reference/arkui-ts/ts-universal-attributes-popup.md#popupoptions类型说明),一种是开发者可以自定义的气泡[CustomPopupOptions](../reference/arkui-ts/ts-universal-attributes-popup.md#custompopupoptions8类型说明)。其中PopupOptions为系统提供的气泡,通过配置primaryButton、secondaryButton来设置带按钮的气泡。CustomPopupOptions通过配置[builder](../quick-start/arkts-builder.md)参数来设置自定义的气泡。 ## 文本提示气泡 diff --git a/zh-cn/application-dev/ui/arkts-routing.md b/zh-cn/application-dev/ui/arkts-routing.md index cc585fc3975a17eb1a7628d0f1d0e521299bc360..9b429f754dc95927a022da333200c0ca09e7f6fd 100644 --- a/zh-cn/application-dev/ui/arkts-routing.md +++ b/zh-cn/application-dev/ui/arkts-routing.md @@ -11,11 +11,11 @@ **图1** 页面跳转 ![router-jump-to-detail](figures/router-jump-to-detail.gif) -Router模块提供了两种跳转模式,分别是[router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9)和[router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9)。这两种模式决定了目标页是否会替换当前页。 +Router模块提供了两种跳转模式,分别是[router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9)和[router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9)。这两种模式决定了目标页面是否会替换当前页。 -- router.pushUrl():目标页不会替换当前页,而是压入[页面栈](../application-models/page-mission-stack.md)。这样可以保留当前页的状态,并且可以通过返回键或者调用[router.back()](../reference/apis/js-apis-router.md#routerback)方法返回到当前页。 +- router.pushUrl():目标页面不会替换当前页,而是压入[页面栈](../application-models/page-mission-stack.md)。这样可以保留当前页的状态,并且可以通过返回键或者调用[router.back()](../reference/apis/js-apis-router.md#routerback)方法返回到当前页。 -- router.replaceUrl():目标页会替换当前页,并销毁当前页。这样可以释放当前页的资源,并且无法返回到当前页。 +- router.replaceUrl():目标页面会替换当前页,并销毁当前页。这样可以释放当前页的资源,并且无法返回到当前页。 >**说明:** > @@ -23,9 +23,9 @@ Router模块提供了两种跳转模式,分别是[router.pushUrl()](../referen 同时,Router模块提供了两种实例模式,分别是Standard和Single。这两种模式决定了目标url是否会对应多个实例。 -- Standard:标准实例模式,也是默认情况下的实例模式。每次调用该方法都会新建一个目标页,并压入栈顶。 +- Standard:多实例模式,也是默认情况下的跳转模式。目标页面会被添加到页面栈顶,无论栈中是否存在相同url的页面。 -- Single:单实例模式。即如果目标页的url在页面栈中已经存在同url页面,则离栈顶最近的同url页面会被移动到栈顶,并重新加载;如果目标页的url在页面栈中不存在同url页面,则按照标准模式跳转。 +- Single:单实例模式。如果目标页面的url已经存在于页面栈中,则会将离栈顶最近的同url页面移动到栈顶,该页面成为新建页。如果目标页面的url在页面栈中不存在同url页面,则按照默认的多实例模式进行跳转。 在使用页面路由Router相关功能之前,需要在代码中先导入Router模块。 @@ -54,7 +54,7 @@ import router from '@ohos.router'; >**说明:** > - >标准实例模式下,router.RouterMode.Standard参数可以省略。 + >多实例模式下,router.RouterMode.Standard参数可以省略。 - 场景二:有一个登录页(Login)和一个个人中心页(Profile),希望从登录页成功登录后,跳转到个人中心页。同时,销毁登录页,在返回时直接退出应用。这种场景下,可以使用replaceUrl()方法,并且使用Standard实例模式(或者省略)。 @@ -76,7 +76,7 @@ import router from '@ohos.router'; >**说明:** > - >标准实例模式下,router.RouterMode.Standard参数可以省略。 + >多实例模式下,router.RouterMode.Standard参数可以省略。 - 场景三:有一个设置页(Setting)和一个主题切换页(Theme),希望从设置页点击主题选项,跳转到主题切换页。同时,需要保证每次只有一个主题切换页存在于页面栈中,在返回时直接回到设置页。这种场景下,可以使用pushUrl()方法,并且使用Single实例模式。 @@ -115,7 +115,7 @@ import router from '@ohos.router'; 以上是不带参数传递的场景。 -如果需要在跳转时传递一些数据给目标页,则可以在调用Router模块的方法时,添加一个params属性,并指定一个对象作为参数。例如: +如果需要在跳转时传递一些数据给目标页面,则可以在调用Router模块的方法时,添加一个params属性,并指定一个对象作为参数。例如: ```ts @@ -150,7 +150,7 @@ function onJumpClick(): void { } ``` -在目标页中,可以通过调用Router模块的[getParams()](../reference/apis/js-apis-router.md#routergetparams)方法来获取传递过来的参数。例如: +在目标页面中,可以通过调用Router模块的[getParams()](../reference/apis/js-apis-router.md#routergetparams)方法来获取传递过来的参数。例如: ```ts @@ -162,7 +162,7 @@ const age = params['info'].age; // 获取age属性的值 ## 页面返回 -当用户在一个页面完成操作后,通常需要返回到上一个页面或者指定页面,这就需要用到页面返回功能。在返回的过程中,可能需要将数据传递给目标页,这就需要用到数据传递功能。 +当用户在一个页面完成操作后,通常需要返回到上一个页面或者指定页面,这就需要用到页面返回功能。在返回的过程中,可能需要将数据传递给目标页面,这就需要用到数据传递功能。 **图2** 页面返回   @@ -195,7 +195,7 @@ import router from '@ohos.router'; }); ``` - 这种方式可以返回到指定页面,需要指定目标页的路径。目标页必须存在于页面栈中才能够返回。 + 这种方式可以返回到指定页面,需要指定目标页面的路径。目标页面必须存在于页面栈中才能够返回。 - 方式三:返回到指定页面,并传递自定义参数信息。 @@ -209,9 +209,9 @@ import router from '@ohos.router'; }); ``` - 这种方式不仅可以返回到指定页面,还可以在返回的同时传递自定义参数信息。这些参数信息可以在目标页中通过调用router.getParams()方法进行获取和解析。 + 这种方式不仅可以返回到指定页面,还可以在返回的同时传递自定义参数信息。这些参数信息可以在目标页面中通过调用router.getParams()方法进行获取和解析。 -在目标页中,在需要获取参数的位置调用router.getParams()方法即可,例如在onPageShow()生命周期回调中: +在目标页面中,在需要获取参数的位置调用router.getParams()方法即可,例如在onPageShow()生命周期回调中: ```ts @@ -275,7 +275,7 @@ function onBackClick(): void { message:string类型,表示询问框的内容。 如果调用成功,则会在目标界面开启页面返回询问框;如果调用失败,则会抛出异常,并通过err.code和err.message获取错误码和错误信息。 -当用户点击“返回”按钮时,会弹出确认对话框,询问用户是否确认返回。选择“取消”将停留在当前页目标页;选择“确认”将触发router.back()方法,并根据参数决定如何执行跳转。 +当用户点击“返回”按钮时,会弹出确认对话框,询问用户是否确认返回。选择“取消”将停留在当前页目标页面;选择“确认”将触发router.back()方法,并根据参数决定如何执行跳转。 ### 自定义询问框 @@ -322,4 +322,4 @@ function onBackClick() { } ``` -当用户点击“返回”按钮时,会弹出自定义的询问框,询问用户是否确认返回。选择“取消”将停留在当前页目标页;选择“确认”将触发router.back()方法,并根据参数决定如何执行跳转。 +当用户点击“返回”按钮时,会弹出自定义的询问框,询问用户是否确认返回。选择“取消”将停留在当前页目标页面;选择“确认”将触发router.back()方法,并根据参数决定如何执行跳转。 diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001163531210.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001163531210.gif index 47730f745cfd341cd6f11c9a3d4ce71d4b2795fb..a645566ffd6152e073bda387a61468d05d0a93da 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001163531210.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001163531210.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001174756580.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001174756580.gif index 5a297661641d1714ebc95116592a97a693293e0a..d3ad5d5ccc9d68f3f822a20b7fde31b05d4b2892 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001174756580.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001174756580.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001175075286.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001175075286.gif deleted file mode 100644 index 90898288928277467db40c5eb11b4ff7ae082e6e..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001175075286.gif and /dev/null differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001178685854.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001178685854.gif index abec4486ad5f444b32aa20b88a3a6d1975254cd0..7f8c79eb23a72da310d2769746d0a8bde4519bcd 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001178685854.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001178685854.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181655292.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181655292.gif index 5813dfac315791a87d9bd9c70a9587e6b779614c..24dba7afc4830bb8da86f31fe7a2d25092bc4987 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181655292.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181655292.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181823160.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181823160.gif index 5d4ed8967a4f4d4d163c560536ee537feddef49a..cf8a2ba1b016283dc59117bc853d1348b5016bbe 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181823160.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001181823160.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189089950.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189089950.gif index 903db10d6d7916f42ae2100403e02da2b2cf0fa2..c91f56f31a49756556d6ff61cccda166b33c6371 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189089950.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189089950.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189249862.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189249862.gif index a1839308d0fdde50aefd4c818d30ea82c49b6ca6..f541dcffbfdc3712ccb6aaddaa5ab0b5a904f6d9 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189249862.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001189249862.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001218279600.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001218279600.gif index b5bce1b8e09e0c47231c11250c6d676806bcd53c..af0d82673874b844d27059447b73c5eeff622156 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001218279600.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001218279600.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220316305.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220316305.gif index 365dbc42e583335f32de863120fd80ae0e7d59e5..52486eead5a5d005c46e0eb445954bb41fbc186e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220316305.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220316305.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220396251.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220396251.gif index b7808565202cf12474f1282e67fde3a9c85d0e9c..e7d53872aa36d55697d3fa917ba9ab655c91984e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220396251.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220396251.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220554911.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220554911.gif index 3fe0cd60d60a0c5d29c2625ebade3d8b0bd0cdf8..f6c0806abfb1bdc742b69592300bc333c590407b 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220554911.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220554911.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif deleted file mode 100644 index 0be34d5b9598c7e03132b08e030fd71d977886b5..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif and /dev/null differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224086459.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224086459.gif index 8158121587531a6ab754316d6379c016be803128..0257ac0a97c7bb8af3431962f41c8d0a62a5351e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224086459.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224086459.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226815403.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226815403.gif index 28b2a163673a71e95a40284d2b045005594623e6..ca4ecc21fe0596f0a644dd619b2d889949d339d1 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226815403.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226815403.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226896657.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226896657.gif index ab6d5e3bde1e3218eaa1156137c7fd6ffc298882..5caa616a4867ff14b496363ed522739ed470f873 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226896657.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001226896657.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227135613.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227135613.gif index f7f05ac39da2bd2f04a7257e1c36eb87ad811783..25967987fbbada2f179f029578d8f28dfc523d8a 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227135613.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227135613.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227422709.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227422709.gif index 260966e4fe59e4e6f80b501251f478bbb7126dce..a89f97cdb43f6527836575768e306a594a76a221 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227422709.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227422709.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701031.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701031.gif index d6a46140a41a112790210c58502fbc3df6e65f20..74e527d7842dcd825a0baf93dbe49cdcc3933a97 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701031.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701031.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif index 0cbcaa3ff368a2a2ad63c8729acc0f66ae874437..fac38d519b9b817e2a7dfdc7f26c46b61a7bdb3e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234011019.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234011019.gif index ab13d6f819a666ded9ffffac99168beafacd97ae..f7defcdb55deec4749d8af503dd8314bf6b1521a 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234011019.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234011019.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234289455.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234289455.gif index 960772dc9536a9e103125503bbb7d4723a6f8c49..47df31181d867cc93ccbe8ee01a254f569ab50b3 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234289455.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001234289455.gif differ diff --git a/zh-cn/application-dev/ui/ui-js-animate-component.md b/zh-cn/application-dev/ui/ui-js-animate-component.md index 07cabbfc8758decdf6694748551014c58cd86921..e8c9b70d71569c9640ae2e92fc901feb5031549e 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-component.md +++ b/zh-cn/application-dev/ui/ui-js-animate-component.md @@ -219,248 +219,3 @@ export default { > alternate-reverse:动画反向交替循环播放,奇数次反向播放,偶数次正向播放。 -## 添加事件和调用方法 - -animation对象支持动画事件和动画方法。可以通过添加开始和取消事件,调用播放、暂停、倒放和结束方法实现预期动画。 - -```html - -
-
-
-
- - -
-
- - -
-
-``` - -```css -/* xxx.css */ -.container { - flex-direction: column; - align-items: center; - justify-content: center; - width: 100%; - height: 100%; -} -button{ - width: 200px; -} -.row{ - width: 65%; - height: 100px; - align-items: center; - justify-content: space-between; - margin-top: 40px; - position: fixed; - top: 65%; - left: 120px; -} -.row1{ - width: 65%; - height: 100px; - align-items: center; - justify-content: space-between; - margin-top: 30px; - position: fixed; - top: 75%; - left: 120px; -} -``` - -```js -// xxx.js -export default { - data: { - animation: '', - }, - onShow() { - var options = { - duration: 1500, - easing:'ease-in', - delay:5, - direction:'normal', - iterations:2 - }; - var frames = [ - { - transform: { - translate: '-150px -0px' - }, - opacity: 0.1, - offset: 0.0, - width: 200, - height: 200, - }, - { - transform: { - translate: '150px 0px' - }, - opacity: 1.0, - offset: 1.0, - width: 300, - height: 300, - } - ]; - this.animation = this.$element('content').animate(frames, options); - this.animation.onstart = function() { - console.info('animation start') - } // 添加开始事件 - this.animation.onrepeat = function() { - console.info('animation repeated') - } // 添加重播事件 - this.animation.oncancel = function() { - console.info('animation canceled') - } // 添加取消事件 - this.animation.onfinish = function() { - console.info('animation finish') - } // 添加完成事件 - }, - playAnimation() { - this.animation.play() // 调用播放开始的方法 - }, - pauseAnimation() { - this.animation.pause() // 调用播放暂停的方法 - }, - reverseAnimation() { - this.animation.reverse() // 调用播放倒放的方法 - }, - cancelAnimation() { - this.animation.cancel() // 调用播放取消的方法 - } -} -``` - -![zh-cn_image_0000001220635011](figures/zh-cn_image_0000001220635011.gif) - -通过改变playState的值实现动画状态的改变。 - -```html - -
-
-
-
- -
-
- -
-
-``` - -```css -/* xxx.css */ -.container { - flex-direction: column; - align-items: center; - justify-content: center; -} -button{ - width: 200px; -} -.row{ - width: 65%; - height: 100px; - align-items: center; - justify-content: space-between; - margin-top: 50px; - margin-left: 260px; - position: fixed; - top: 65%; -} -.row1{ - width: 65%; - height: 100px; - align-items: center; - justify-content: space-between; - margin-top: 50px; - margin-left: 260px; - position: fixed; - top: 75%; -} -``` - -```js -// xxx.js -import promptAction from '@ohos.promptAction'; -export default { - data: { - animation: '', - state:'play', - state1:'play' - }, - onInit() { - }, - onShow() { - var options = { - duration: 1500, - easing:'ease-in', - elay:5, - direction:'normal', - iterations:2, - }; - var frames = [ - { - transform: { - translate: '-150px -0px' - }, - opacity: 0.1, - offset: 0.0, - width: 200, - height: 200, - }, - { - transform: { - translate: '150px 0px' - }, - opacity: 1.0, - offset: 1.0, - width: 300, - height: 300, - } - ]; - this.animation = this.$element('content').animate(frames, options); - this.animation.onstart = function(){ - promptAction.showToast({ - message: "start" - }); - }; - this.animation.onrepeat = function(){ - promptAction.showToast({ - message: " repeated" - }); - }; - this.animation.onfinish = function(){ - promptAction.showToast({ - message: " finished" - }); - }; - }, - playStateClick(){ - if(this.animation.playState != 'running'){ - this.animation.playState = 'running';//设置playState为running,动画运行。 - this.state = 'pause' - }else{ - this.animation.playState = 'paused';//设置playState为paused,动画暂停。 - this.state = 'play' - } - }, - playStateClick1(){ - if(this.animation.playState != 'running'){ - this.animation.playState = 'running'; - this.state1 = 'finish' - }else{ - this.animation.playState = 'finished';//设置playState为finished,动画结束。 - this.state1 = 'play' - } - } -} -``` - -![zh-cn_image_0000001175075286](figures/zh-cn_image_0000001175075286.gif) diff --git a/zh-cn/application-dev/ui/ui-js-animate-transform.md b/zh-cn/application-dev/ui/ui-js-animate-transform.md index b8ca82ad3af4e0bf80706585433c3f791410c0a4..7ba400aa5f6d063d93380c4eeb5816be0f9cfe70 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-transform.md +++ b/zh-cn/application-dev/ui/ui-js-animate-transform.md @@ -38,8 +38,8 @@ height: 428px; background-color: #860303; transform: rotate(45deg); - margin-top: 290px; - margin-left: 145px; + margin-top: 284px; + margin-left: 148px; } .content{ margin-top: 500px; @@ -50,9 +50,9 @@ } .door{ width: 100px; - height: 150px; + height: 135px; background-color: #1033d9; - transform: translate(150px,-152px); + transform: translate(150px,-137px); } .window{ z-index: 1; @@ -85,7 +85,7 @@ height: 100px; border-radius: 15px; background-color: #9a7404; - transform: translate(200px,-700px) skewX(-5deg); + transform: translate(200px,-710px) skewX(-5deg); } ``` @@ -197,107 +197,107 @@ ```css /* xxx.css */ .container { - flex-direction: column; - background-color:#F1F3F5; - display: flex; - align-items: center; - justify-content: center; - width: 100%; - height: 100%; + flex-direction: column; + background-color:#F1F3F5; + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; } .rect { - width: 100px; - height: 100px; - animation: rotate 3s infinite; - margin-left: 100px; + width: 100px; + height: 100px; + animation: rotate 3s infinite; + margin-left: 30px; } .rect1 { - background-color: #f76160; + background-color: #f76160; } .rect2 { - background-color: #60f76f; - /* 改变原点位置*/ - transform-origin: 10% 10px; + background-color: #60f76f; +/* 改变原点位置*/ + transform-origin: 10% 10px; } .rect3 { - background-color: #6081f7; - /* 改变原点位置*/ - transform-origin: right bottom; + background-color: #6081f7; +/* 改变原点位置*/ + transform-origin: right bottom; } @keyframes rotate { - from { - transform: rotate(0deg) - } - to { - transform: rotate(360deg); - } + from { + transform: rotate(0deg) + } + to { + transform: rotate(360deg); + } } /* 3d示例样式 */ .rotate3d { - margin-top: 150px; - flex-direction: column; - background-color:#F1F3F5; - display: flex; - align-items: center; - width: 80%; - height: 600px; - border-radius: 300px; - border: 1px solid #ec0808; + margin-top: 150px; + flex-direction: column; + background-color:#F1F3F5; + display: flex; + align-items: center; + width: 80%; + height: 600px; + border-radius: 300px; + border: 1px solid #ec0808; } .content { - padding-top: 150px; - display: flex; - align-items: center; - justify-content: center; + padding-top: 150px; + display: flex; + align-items: center; + justify-content: center; } /* react4 react5 翻转形成眼睛 */ .rect4 { - width: 100px; - height: 100px; - animation: rotate3d1 1000ms infinite; - background: linear-gradient(#e6c4ec, #be15d9) + width: 100px; + height: 100px; + animation: rotate3d1 1000ms infinite; + background-color: darkmagenta; } .rect5 { - width: 100px; - height: 100px; - animation: rotate3d1 1000ms infinite; - margin-left: 100px; - background: linear-gradient(#e6c4ec, #be15d9) + width: 100px; + height: 100px; + animation: rotate3d1 1000ms infinite; + margin-left: 100px; + background-color: darkmagenta; } .mouse { - margin-top: 150px; - width: 200px; - height: 100px; - border-radius: 50px; - border: 1px solid #e70303; - animation: rotate3d2 1000ms infinite; + margin-top: 150px; + width: 200px; + height: 100px; + border-radius: 50px; + border: 1px solid #e70303; + animation: rotate3d2 1000ms infinite; } /* 眼睛的动效 */ @keyframes rotate3d1 { - 0% { - transform:rotate3d(0,0,0,0deg) - } - 50% { - transform:rotate3d(20,20,20,360deg); - } - 100% { - transform:rotate3d(0,0,0,0deg); - } + 0% { + transform:rotate3d(0,0,0,0deg) + } + 50% { + transform:rotate3d(20,20,20,360deg); + } + 100% { + transform:rotate3d(0,0,0,0deg); + } } /* 嘴的动效 */ @keyframes rotate3d2 { - 0% { - transform:rotate3d(0,0,0,0deg) - } - 33% { - transform:rotate3d(0,0,10,30deg); - } - 66% { - transform:rotate3d(0,0,10,-30deg); - } - 100% { - transform:rotate3d(0,0,0,0deg); - } + 0% { + transform:rotate3d(0,0,0,0deg) + } + 33% { + transform:rotate3d(0,0,10,30deg); + } + 66% { + transform:rotate3d(0,0,10,-30deg); + } + 100% { + transform:rotate3d(0,0,0,0deg); + } } ``` @@ -331,86 +331,85 @@ ```css /* xxx.css */ .container { - flex-direction: column; - background-color:#F1F3F5; - width: 100%; - position: relative; + flex-direction: column; + background-color:#F1F3F5; + width: 100%; + position: relative; } .circle{ - margin-top: 400px; - margin-left: 40%; - width: 100px; - height: 100px; - border-radius: 50px; - background:linear-gradient(#dcaec1, #d3a8e3); - z-index: 1; position: absolute; + margin-top: 400px; + margin-left: 40%; + width: 100px; + height: 100px; + border-radius: 50px; + background-color: mediumpurple; + z-index: 1; position: absolute; } .ripple{ - margin-top: 400px; - margin-left: 40%; - position: absolute; z-index: 0; - width: 100px; - height: 100px; - border-radius: 50px; - background:linear-gradient(#dcaec1,#d3a8e3); - animation: ripple 5s infinite; + margin-top: 400px; + margin-left: 40%; + position: absolute; z-index: 0; + width: 100px; + height: 100px; + border-radius: 50px; + background-color: blueviolet; + animation: ripple 5s infinite; } /* 设置不同的动画时间 */ .ripple2{ - animation-duration: 2.5s; + animation-duration: 2.5s; } @keyframes ripple{ - 0%{ - transform: scale(1); - opacity: 0.5; - } - 50%{ - transform: scale(3); - opacity: 0; - } - 100%{ - transform: scale(1); - opacity: 0.5; - } + 0%{ + transform: scale(1); + opacity: 0.5; + } + 50%{ + transform: scale(3); + opacity: 0; + } + 100%{ + transform: scale(1); + opacity: 0.5; + } } text{ - color: white; - text-align: center; - height: 100%; - width: 100%; + color: white; + text-align: center; + height: 100%; + width: 100%; } .content { - margin-top: 700px; - margin-left: 33%; - width: 200px; - height: 100px; - animation:rubberBand 1s infinite; - /* 设置渐变色 */ - background:linear-gradient(#e276aa,#ec0d66); - position: absolute; + margin-top: 700px; + margin-left: 33%; + width: 200px; + height: 100px; + animation:rubberBand 1s infinite; + background-color: darkmagenta; + position: absolute; } @keyframes rubberBand { - 0% { - transform: scale3d(1, 1, 1); - } - 30% { - transform: scale3d(1.25, 0.75, 1.1); - } - 40% { - transform: scale3d(0.75, 1.25, 1.2); - } - 50% { - transform: scale3d(1.15, 0.85, 1.3); - } - 65% { - transform: scale3d(.95, 1.05, 1.2); - } - 75% { - transform: scale3d(1.05, .95, 1.1); - } - 100%{ - transform: scale3d(1, 1, 1); - } + 0% { + transform: scale3d(1, 1, 1); + } + 30% { + transform: scale3d(1.25, 0.75, 1.1); + } + 40% { + transform: scale3d(0.75, 1.25, 1.2); + } + 50% { + transform: scale3d(1.15, 0.85, 1.3); + } + 65% { + transform: scale3d(.95, 1.05, 1.2); + } + 75% { + transform: scale3d(1.05, .95, 1.1); + } + 100%{ + transform: scale3d(1, 1, 1); + } } ``` @@ -483,92 +482,92 @@ transform可以设置多个值并且多个值可同时设置,下面案例中 ```css /* xxx.css */ .container{ - width: 100%; - height: 100%; - flex-direction:column; - background-color:#F1F3F5; - padding:50px; + width: 100%; + height: 100%; + flex-direction:column; + background-color:#F1F3F5; + padding:50px; } .rect1{ - width: 100px; - height: 100px; - background:linear-gradient(#e77070,#ee0202); - animation: change1 3s infinite forwards; + width: 100px; + height: 100px; + background-color: red; + animation: change1 3s infinite forwards; } .rect2{ - margin-top: 50px; - width: 100px; - height: 100px; - background:linear-gradient(#95a6e8, #2739de); - animation: change2 3s infinite forwards; + margin-top: 50px; + width: 100px; + height: 100px; + background-color: darkblue; + animation: change2 3s infinite forwards; } .rect3{ - margin-top: 50px; - width: 100px; - height: 100px; - background:linear-gradient(#142ee2, #8cb1e5); - animation: change3 3s infinite; + margin-top: 50px; + width: 100px; + height: 100px; + background-color: darkblue; + animation: change3 3s infinite; } .rect4{ - align-self: center; - margin-left: 50px; - margin-top: 200px; - width: 100px; - height: 100px; - background:linear-gradient(#e2a8df, #9c67d4,#8245d9,#e251c3); - animation: change4 3s infinite; + align-self: center; + margin-left: 50px; + margin-top: 200px; + width: 100px; + height: 100px; + background-color: darkmagenta; + animation: change4 3s infinite; } .rect5{ - margin-top: 300px; - width: 100px; - height: 100px; - background:linear-gradient(#e7ded7, #486ccd, #94b4d2); - animation: change5 3s infinite; + margin-top: 300px; + width: 100px; + height: 100px; + background-color: cadetblue; + animation: change5 3s infinite; } /* change1 change2 对比 */ @keyframes change1{ - 0%{ - transform: translate(0,0); transform: rotate(0deg) - } - 100%{ - transform: translate(0,500px); - transform: rotate(360deg) - } + 0%{ + transform: translate(0,0); transform: rotate(0deg) + } + 100%{ + transform: translate(0,500px); + transform: rotate(360deg) + } } /* change2 change3 对比属性顺序不同的动画效果 */ @keyframes change2{ - 0%{ - transform:translate(0,0) rotate(0deg) ; - } - 100%{ - transform: translate(300px,0) rotate(360deg); - } + 0%{ + transform:translate(0,0) rotate(0deg) ; + } + 100%{ + transform: translate(300px,0) rotate(360deg); + } } @keyframes change3{ - 0%{ - transform:rotate(0deg) translate(0,0); - } - 100%{ - transform:rotate(360deg) translate(300px,0); - } + 0%{ + transform:rotate(0deg) translate(0,0); + } + 100%{ + transform:rotate(360deg) translate(300px,0); + } } /* 属性值不对应的情况 */ @keyframes change4{ - 0%{ - transform: scale(0.5); - } - 100%{ - transform:scale(2) rotate(45deg); - } + 0%{ + transform: scale(0.5); + } + 100%{ + transform:scale(2) rotate(45deg); + } } /* 多属性的写法 */ @keyframes change5{ - 0%{ - transform:scale(0) translate(0,0) rotate(0); - } - 100%{ - transform: scale(1.5) rotate(360deg) translate(200px,0); - } + 0%{ + transform:scale(0) translate(0,0) rotate(0); + } + 100%{ + transform: scale(1.5) rotate(360deg) translate(200px,0); + } } ``` @@ -590,8 +589,6 @@ transform可以设置多个值并且多个值可同时设置,下面案例中 - [`JsClock`:时钟(JS)(API10)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/JsClock) -- [`JsAnimator`:动画(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsAnimation) - - [动画样式(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/JSUI/AnimationDemo) - [图片常见操作(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Media/ImageJsDemo) diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-component.md b/zh-cn/application-dev/ui/ui-js-building-ui-component.md index 253c9d0ebcc83f969753fe2d3a7585b22e863b20..2fe99304ed549e7916092ea6dac57fb9d339aaeb 100755 --- a/zh-cn/application-dev/ui/ui-js-building-ui-component.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-component.md @@ -27,12 +27,6 @@ - [`JsComponentCollection`:组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) -- [`JsPanel`:内容展示面板(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsPanel) - -- [`Popup`:气泡(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/Popup) - -- [`JsUserRegistration`:用户注册(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsUserRegistration) - - [`MediaCollections`:媒体管理合集(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) - [rating(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/JSUI/RatingApplication) diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-routes.md b/zh-cn/application-dev/ui/ui-js-building-ui-routes.md index 0c1f7da4095e6caaf12416a2aaac76aa03a7fbb8..206cd433560c9cf46dd19ee49d162061211cca3c 100644 --- a/zh-cn/application-dev/ui/ui-js-building-ui-routes.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-routes.md @@ -91,4 +91,4 @@ export default { 针对页面路由开发,有以下相关实例可供参考: -- [`JsRouter`:页面路由(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsRouter) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-component-tabs.md b/zh-cn/application-dev/ui/ui-js-component-tabs.md index 667645da64cda09a34f3464a5cce62b135512010..64e10a67772c10819d0cafbbaac93d85c41361c5 100644 --- a/zh-cn/application-dev/ui/ui-js-component-tabs.md +++ b/zh-cn/application-dev/ui/ui-js-component-tabs.md @@ -50,57 +50,6 @@ tabs是一种常见的界面导航结构。通过页签容器,用户可以快 ![zh-cn_image_0000001165191390](figures/zh-cn_image_0000001165191390.gif) -## 设置tabs方向 - -tabs默认展示索引为index的标签及内容。通过设置vertical属性使组件纵向展示。 - -```html - -
- - - item1 - item2 - - -
- -
-
- -
-
-
-
-``` - -![zh-cn_image_0000001208908643](figures/zh-cn_image_0000001208908643.gif) - -设置mode属性使tab-bar的子组件均分,设置scrollable属性使tab-content不可进行左右滑动切换内容。 - -```html - -
- - - item1 - item2 - - -
- -
-
- -
-
-
-
-``` - -![zh-cn_image_0000001209028575](figures/zh-cn_image_0000001209028575.gif) - - ## 设置样式 设置tabs背景色及边框和tab-content布局。 @@ -319,4 +268,4 @@ export default { 针对tabs开发,有以下相关实例可供参考: -- [`Tabs`:页签容器(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/Tabs) \ No newline at end of file +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-js-components-canvas.md b/zh-cn/application-dev/ui/ui-js-components-canvas.md index cda2e7854144a919dc8a3b687a07adc84b136e8b..e27cea75647cec20b0ccfcdf3658fc6c07431808 100644 --- a/zh-cn/application-dev/ui/ui-js-components-canvas.md +++ b/zh-cn/application-dev/ui/ui-js-components-canvas.md @@ -146,4 +146,4 @@ export default { 针对Canvas开发,有以下相关实例可供参考: -- [`JsCanvas`:画布组件(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsCanvas) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-chart.md b/zh-cn/application-dev/ui/ui-js-components-chart.md index c00ce4dfb6a9acac1f460df1bd6d8a5420a06425..c6096a78174b3caf5a204094b33b79f034875214 100644 --- a/zh-cn/application-dev/ui/ui-js-components-chart.md +++ b/zh-cn/application-dev/ui/ui-js-components-chart.md @@ -624,6 +624,4 @@ export default { 针对chart开发,有以下相关实例可供参考: -- [`chart`:图表组件(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/chart) - -- [chart(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/JSUI/SwitchApplication) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-grid.md b/zh-cn/application-dev/ui/ui-js-components-grid.md index 4786eb03b1f3f9b4b95c44a7249e2222dc04cd3c..a25c4465a7b9da69f88186a47667704f9b82c9d7 100644 --- a/zh-cn/application-dev/ui/ui-js-components-grid.md +++ b/zh-cn/application-dev/ui/ui-js-components-grid.md @@ -12,9 +12,9 @@ ```html
- + + 10%;"> @@ -27,8 +27,7 @@ .container{ flex-direction: column; background-color: #F1F3F5; - width: 100%; - height: 100%; + margin-top: 500px; justify-content: center; align-items: center; } @@ -48,14 +47,14 @@ grid-container点击组件调用getColumns、getColumnWidth、getGutterWidth方 ```html
- + 40%;"> + 25%;"> + 10%;">
@@ -67,8 +66,7 @@ grid-container点击组件调用getColumns、getColumnWidth、getGutterWidth方 .container{ flex-direction: column; background-color: #F1F3F5; - width: 100%; - height: 100%; + margin-top: 400px; justify-content: center; align-items: center; } @@ -163,7 +161,7 @@ export default { text{ color: white; font-size: 40px; - +} ``` ![zh-cn_image_0000001227135731](figures/zh-cn_image_0000001227135731.png) @@ -252,4 +250,4 @@ export default { 针对Grid开发,有以下相关实例可供参考: -- [`JsGrid`:栅格组件(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsGrid) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-list.md b/zh-cn/application-dev/ui/ui-js-components-list.md index eb4dfa73618046665a2a5314369b968d63c30928..bbb2d35c2c4ac53e081164e04e85a25c2f5de8a6 100644 --- a/zh-cn/application-dev/ui/ui-js-components-list.md +++ b/zh-cn/application-dev/ui/ui-js-components-list.md @@ -314,4 +314,4 @@ export default { 针对list开发,有以下相关实例可供参考: -- [`JsList`:商品列表(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsList) \ No newline at end of file +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-js-components-marquee.md b/zh-cn/application-dev/ui/ui-js-components-marquee.md index f755e9807c056a25788fb999e9826f9c80f8bf67..280fdb86c494efeece578119069ffaacef0b4803 100644 --- a/zh-cn/application-dev/ui/ui-js-components-marquee.md +++ b/zh-cn/application-dev/ui/ui-js-components-marquee.md @@ -12,7 +12,7 @@ marquee为跑马灯组件,用于展示一段单行滚动的文字。具体用 ```html
- This is a marquee. + It's a racing lamp.
``` diff --git a/zh-cn/application-dev/ui/ui-js-components-menu.md b/zh-cn/application-dev/ui/ui-js-components-menu.md index 710007a5d1edc6fcb2be0d55e420b74c71812865..b71b3d19a460d5a12667f49265ab02eb8af76aa0 100644 --- a/zh-cn/application-dev/ui/ui-js-components-menu.md +++ b/zh-cn/application-dev/ui/ui-js-components-menu.md @@ -179,15 +179,15 @@ export default { ```html
-
- {{item.name}} -
- width:{{width}},height:{{height}} -
- change size - - - +
+ {{item.name}} +
+ width:{{width}},height:{{height}} +
+ change size + + +
``` @@ -242,7 +242,6 @@ option{ ```js // xxx.js -import promptAction from '@ohos.promptAction'; export default { data:{ fresh: false, @@ -283,4 +282,4 @@ export default { 针对menu开发,有以下相关实例可供参考: -- [`JSMenu`:菜单(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JSMenu) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-picker.md b/zh-cn/application-dev/ui/ui-js-components-picker.md index f0f0818a3f4e2bc59334d87782cd3e69ed16b880..7a9af47249ea769bb4fea644a0de598f15229387 100644 --- a/zh-cn/application-dev/ui/ui-js-components-picker.md +++ b/zh-cn/application-dev/ui/ui-js-components-picker.md @@ -301,4 +301,4 @@ export default { 针对picker开发,有以下相关实例可供参考: -- [`Picker`:滑动选择器(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/Picker) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-stepper.md b/zh-cn/application-dev/ui/ui-js-components-stepper.md index d91733753be4d725b8df526df0bb9bf3fb8a821b..1720cd4cee88bd8c28f15abbca8f12e952d42707 100644 --- a/zh-cn/application-dev/ui/ui-js-components-stepper.md +++ b/zh-cn/application-dev/ui/ui-js-components-stepper.md @@ -410,4 +410,4 @@ export default { 针对stepper开发,有以下相关实例可供参考: -- [`StepNavigator`:步骤导航器(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/StepNavigator) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-svg-overview.md b/zh-cn/application-dev/ui/ui-js-components-svg-overview.md index f3ee0f5ce2ab3bd80222e8f8bc8bdc65dfa4e965..ae32dcf6a7120e85454cdbd81077d21d9c463bf9 100644 --- a/zh-cn/application-dev/ui/ui-js-components-svg-overview.md +++ b/zh-cn/application-dev/ui/ui-js-components-svg-overview.md @@ -87,4 +87,4 @@ svg{ 针对Svg开发,有以下相关实例可供参考: -- [`JsSvg`:可缩放矢量图形(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsSvg) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-js-components-swiper.md b/zh-cn/application-dev/ui/ui-js-components-swiper.md index 6941ec9b7e2f72963bac34f059df24a65b1f4b9f..3568e0be6c664d73cd8fc95d9842930c6caef204 100644 --- a/zh-cn/application-dev/ui/ui-js-components-swiper.md +++ b/zh-cn/application-dev/ui/ui-js-components-swiper.md @@ -131,17 +131,17 @@ text{ ```html
- -
- item1 -
-
- item2 -
-
- item3 -
-
+ +
+ item1 +
+
+ item2 +
+
+ item3 +
+
``` @@ -370,4 +370,4 @@ export default { 针对swiper开发,有以下相关实例可供参考: -- [`Swiper`:内容滑动容器(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/Swiper) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-text.md b/zh-cn/application-dev/ui/ui-js-components-text.md index 61686969aa4028ad97b40ac11545386e61a55494..29d9960107bb4ecb71244c4efe169a2b2a4a3859 100644 --- a/zh-cn/application-dev/ui/ui-js-components-text.md +++ b/zh-cn/application-dev/ui/ui-js-components-text.md @@ -276,4 +276,4 @@ export default { 针对text开发,有以下相关实例可供参考: -- [`JstextComponents`:基础组件(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsBasicComponents) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-components-toolbar.md b/zh-cn/application-dev/ui/ui-js-components-toolbar.md index 00503fa7277a1dba1559ac048d809bcd2a802669..bcad8ae027af6690c263714cdbb82fa14869b035 100644 --- a/zh-cn/application-dev/ui/ui-js-components-toolbar.md +++ b/zh-cn/application-dev/ui/ui-js-components-toolbar.md @@ -108,10 +108,6 @@ toolbar-item{ toolbar-item{ font-size: 35px; } -.toolbarActive{ - color: red; - background-color: #daebef; -} ``` @@ -186,9 +182,8 @@ export default {
- - + +
``` @@ -234,4 +229,4 @@ export default { 针对toolbar开发,有以下相关实例可供参考: -- [`Toolbar`:工具栏(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/Toolbar) +- [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) diff --git a/zh-cn/application-dev/ui/ui-js-overview.md b/zh-cn/application-dev/ui/ui-js-overview.md index af7b69cf513ac896ce2218c0e4553a3f213f7718..e422e642c5bf40d09d5f4dc8b224de479058834f 100755 --- a/zh-cn/application-dev/ui/ui-js-overview.md +++ b/zh-cn/application-dev/ui/ui-js-overview.md @@ -34,14 +34,6 @@ 兼容JS的类Web开发范式的方舟开发框架,有以下相关实例可供参考: -- [`AtomicLayout`:原子布局(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/AtomicLayout) - -- [`FaModel`:FA示例应用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/FaModel) - -- [`JsShopping`:购物示例应用(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/JsShopping) - -- [`Stack`:堆叠容器(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/UI/Stack) - - [`JsComponentCollection`:JS组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/JsComponentClollection/JsComponentCollection) - [购物应用(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/JSUI/ShoppingOpenHarmony) diff --git a/zh-cn/application-dev/web/web-open-in-new-window.md b/zh-cn/application-dev/web/web-open-in-new-window.md index 99a244544598060f16881ab6b020eb431e6f8ecf..b05a96ffeccbf763fb557dcb04f09ae60104de4e 100644 --- a/zh-cn/application-dev/web/web-open-in-new-window.md +++ b/zh-cn/application-dev/web/web-open-in-new-window.md @@ -6,9 +6,9 @@ Web组件提供了在新窗口打开页面的能力,开发者可以通过[mult > **说明:** > -> - [allowWindowOpenMethod()](../reference/arkui-ts/ts-basic-components-web.md#allowwindowopenmethod9)接口设置为true时,前端页面通过JavaScript函数调用的方式打开新窗口。 +> - [allowWindowOpenMethod()](../reference/arkui-ts/ts-basic-components-web.md#allowwindowopenmethod10)接口设置为true时,前端页面通过JavaScript函数调用的方式打开新窗口。 > -> - 如果开发者在[onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9)接口通知中不需要打开新窗口,需要将[ControllerHandler.setWebController()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9)接口返回值设置成null。 +> - 如果开发者在[onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9)接口通知中不需要打开新窗口,需要将[ControllerHandler.setWebController()](../reference/arkui-ts/ts-basic-components-web.md#setwebcontroller9)接口返回值设置成null。 如下面的本地示例,当用户点击“新窗口中打开网页”按钮时,应用侧会在[onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9)接口中收到Web组件新窗口事件。 diff --git a/zh-cn/application-dev/webgl/webgl-guidelines.md b/zh-cn/application-dev/webgl/webgl-guidelines.md index 644fe8b172683880599c370f49292b3e3afbc99a..fe2ecf6799008fe3d4fa0bca6048d54daf9d77cf 100644 --- a/zh-cn/application-dev/webgl/webgl-guidelines.md +++ b/zh-cn/application-dev/webgl/webgl-guidelines.md @@ -703,9 +703,3 @@ WebGL主要帮助开发者在前端开发中完成图形图像的相关处理, **图2** 点击按钮绘制彩色三角形的效果图 ![zh-cn_image_0000001192429306](figures/zh-cn_image_0000001192429306.gif) - -## 相关实例 - -针对WebGL开发,有以下相关实例可供参考: - -- [`JsWbgGL`:WebGL(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL) \ No newline at end of file diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index 65030d6f11fb6d1f5f5f96b105c9b27e341020ac..7a2a9d493ef65ac69a09f5b28613b6a11baf00ec 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -1465,3 +1465,4 @@ - [IDE使用常见问题](faqs/faqs-ide.md) - [hdc_std命令使用常见问题](faqs/faqs-hdc-std.md) - [开发板使用常见问题](faqs/faqs-development-board.md) + diff --git a/zh-cn/contribute/FAQ.md b/zh-cn/contribute/FAQ.md index 4c75f95e3a738c36a6287dc5faa7c3c649d65646..297545c0bddfa863f8e0e2102fc59724c43074b8 100755 --- a/zh-cn/contribute/FAQ.md +++ b/zh-cn/contribute/FAQ.md @@ -44,7 +44,7 @@ OS\(操作系统\)开发时,经常会遇到多个代码仓的修改具有编 **解决办法**: - 点击[这里](https://dco.openharmony.io/sign/Z2l0ZWUlMkZvcGVuX2hhcm1vbnk=)签署、查看签署状态。 + 点击[这里](https://dco.openharmony.cn/sign)签署、查看签署状态。 在PR的评论框输入`check dco`后,单击”评论”,系统将再次进行DCO校验。 diff --git a/zh-cn/contribute/OpenHarmony-security-test-guide.md b/zh-cn/contribute/OpenHarmony-security-test-guide.md index baea8ed9d108a6a673813a8260aa2d418f052a96..b019f6e0f1d1e2c595f8f51b2aa792478f56a130 100644 --- a/zh-cn/contribute/OpenHarmony-security-test-guide.md +++ b/zh-cn/contribute/OpenHarmony-security-test-guide.md @@ -8,7 +8,7 @@ 2、通过OpenHarmony代码门禁安全扫描工具测试,扫描告警结果清零。 -3、依据[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-buildsystem/编译规范.md),使用编译选项扫描工具检查二进制文件编译选项开启情况,二进制文件编译选项均需要符合规范要求。 +3、依据[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig_buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md),使用编译选项扫描工具检查二进制文件编译选项开启情况,二进制文件编译选项均需要符合规范要求。 4、针对接收并处理用户态参数模块,开发人员需依据[Fuzz测试框架](https://gitee.com/openharmony/test_developertest/tree/master/libs/fuzzlib)开发灰白盒Fuzz测试套,并完成灰白盒Fuzz测试验证。 diff --git a/zh-cn/contribute/Readme-CN.md b/zh-cn/contribute/Readme-CN.md index 80bb091bd1b7b305298629aaefdf3e41dcc4ff71..eecb0dc72b0c3cbd7db4cd5603eb2f3ad087a80b 100755 --- a/zh-cn/contribute/Readme-CN.md +++ b/zh-cn/contribute/Readme-CN.md @@ -6,7 +6,7 @@ - [贡献流程](贡献流程.md) - [自测试验证](../readme/测试子系统.md) - [贡献文档](贡献文档.md) -- [写作规范](写作规范.md) +- [文档风格](style-guide/Readme-CN.md) - [社区沟通与交流](社区沟通与交流.md) - [FAQ](FAQ.md) diff --git a/zh-cn/contribute/template/README-template.md b/zh-cn/contribute/template/README-template.md index ffb8814a0f56b1056d25e88412b25b23ddc8b36a..963058a78cdcdd3f4ca884727c35743c217f1fc6 100644 --- a/zh-cn/contribute/template/README-template.md +++ b/zh-cn/contribute/template/README-template.md @@ -146,7 +146,7 @@ 示例: -[内核子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%86%85%E6%A0%B8%E5%AD%90%E7%B3%BB%E7%BB%9F.md) +[内核子系统](../../readme/内核子系统.md) [drivers\_liteos](https://gitee.com/openharmony/drivers_liteos/blob/master/README_zh.md) diff --git a/zh-cn/contribute/template/guide-template.md b/zh-cn/contribute/template/guide-template.md index fefe1359814200857ff975c45e75bde193658251..077ce9af0c00758fbefb51d3eddb71ff1535948a 100644 --- a/zh-cn/contribute/template/guide-template.md +++ b/zh-cn/contribute/template/guide-template.md @@ -181,7 +181,7 @@ _已发布的Sample code、Codelabs、Demo工程包,请在此处提供链接 针对Ability开发,有以下相关实例可供参考: -- [Page内和Page间导航跳转](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility) +- [UIAbility内和UIAbility间页面的跳转(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/Ability/StageAbility ## 环境准备 diff --git a/zh-cn/contribute/template/xxboard-template.md b/zh-cn/contribute/template/xxboard-template.md index dbd31d13e225d47946acdfbc834aaf0e4157a788..a7bdd0db96b8877dd1dc495f6e3ee1e6831f06b8 100644 --- a/zh-cn/contribute/template/xxboard-template.md +++ b/zh-cn/contribute/template/xxboard-template.md @@ -15,7 +15,7 @@ **图片名称以开发板名称命名。* -*参考文档:https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-introduction-hi3861.md* +*参考文档:[Hi3861开发板介绍](../../device-dev/quick-start/quickstart-appendix-hi3861.md)* ******** ## 开发板规格 diff --git "a/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" "b/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" index 1d7524fc65ec1d3aa782a5c5eb49803effd680e7..aabb1c27b3f7db08261f54dbc3deee10d90d4bfa 100755 --- "a/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" +++ "b/zh-cn/contribute/\347\254\254\344\270\211\346\226\271\345\274\200\346\272\220\350\275\257\344\273\266\345\274\225\345\205\245\346\214\207\345\257\274.md" @@ -139,7 +139,7 @@ third_party_abcde/doc/ LICENSEFILE LICENSE Apache-2.0 #### 新增三方开源软件评审 -参考[SIG-Architecture](https://gitee.com/openharmony/community/blob/master/sig/sig-architecture/sig-architecture_cn.md),SIG-Architecture会统一安排建仓评审。 +参考[SIG-Architecture](https://gitee.com/openharmony/community/blob/master/sig/sig_architecture/sig_architecture_cn.md),SIG-Architecture会统一安排建仓评审。 ### 第三方开源软件许可证要求 diff --git "a/zh-cn/contribute/\350\256\270\345\217\257\350\257\201\344\270\216\347\211\271\346\256\212\350\256\270\345\217\257\350\257\201\350\257\204\345\256\241\346\214\207\345\257\274.md" "b/zh-cn/contribute/\350\256\270\345\217\257\350\257\201\344\270\216\347\211\271\346\256\212\350\256\270\345\217\257\350\257\201\350\257\204\345\256\241\346\214\207\345\257\274.md" index d37f6a6a8311efac5aa2e1319f6bf4b0540c6b23..7387ff8b62281f449ec91f4c9ebf4a59b096c164 100644 --- "a/zh-cn/contribute/\350\256\270\345\217\257\350\257\201\344\270\216\347\211\271\346\256\212\350\256\270\345\217\257\350\257\201\350\257\204\345\256\241\346\214\207\345\257\274.md" +++ "b/zh-cn/contribute/\350\256\270\345\217\257\350\257\201\344\270\216\347\211\271\346\256\212\350\256\270\345\217\257\350\257\201\350\257\204\345\256\241\346\214\207\345\257\274.md" @@ -26,9 +26,9 @@ OpenHarmony项目第三方依赖:OpenHarmony项目依赖的第三方开源代 OpenHarmony项目贡献代码许可证白名单包括: -- [Apache License 2.0 (Apache-2.0)](https://opensource.org/licenses/Apache-2.0)(适用于用户态代码) -- [3-clause BSD License (BSD-3-Clause)](https://opensource.org/licenses/BSD-3-Clause) (适用于LiteOS Kernel代码) -- [GNU General Public License version 2 (GPL-2.0)](https://opensource.org/licenses/GPL-2.0)(适用于Linux Kernel代码) +- Apache License 2.0 (Apache-2.0)(适用于用户态代码) +- 3-clause BSD License (BSD-3-Clause)(适用于LiteOS Kernel代码) +- GNU General Public License version 2 (GPL-2.0)(适用于Linux Kernel代码) ## OpenHarmony项目第三方依赖可接纳和不可接纳的许可证名单 @@ -38,43 +38,43 @@ OpenHarmony项目还可能引入或依赖不同的第三方开源软件,这些 与Apache-2.0许可证相兼容的许可证可以被接纳,OpenHarmony项目建议可优先接纳采用如下许可证的第三方依赖: -- [Academic Free License 3.0 (AFL-3.0)](https://opensource.org/licenses/AFL-3.0) +- Academic Free License 3.0 (AFL-3.0) -- [Apache License 2.0 (Apache-2.0)](https://opensource.org/licenses/Apache-2.0) +- Apache License 2.0 (Apache-2.0) -- [Apache Software License 1.1](https://www.apache.org/licenses/LICENSE-1.1). Including variants: +- Apache Software License 1.1. Including variants: - - [PHP License 3.01](http://www.php.net/license/3_01.txt) - - [MX4J License](http://mx4j.sourceforge.net/docs/ch01s06.html) + - PHP License 3.01 + - MX4J License -- [Boost Software License (BSL-1.0)](https://opensource.org/licenses/BSL-1.0) +- Boost Software License (BSL-1.0) - BSD License: - - [3-clause BSD License](https://opensource.org/licenses/BSD-3-Clause) - - [2-clause BSD License](https://opensource.org/licenses/BSD-2-Clause) + - 3-clause BSD License + - 2-clause BSD License - DOM4J License - - [PostgreSQL License](http://opensource.org/licenses/postgresql) + - PostgreSQL License -- [ISC](https://opensource.org/licenses/ISC) +- ISC - ICU -- [MIT License (MIT)](https://opensource.org/licenses/MIT) / X11 +- MIT License (MIT) / X11 -- [MIT No Attribution License (MIT-0)](https://opensource.org/licenses/MIT-0) +- MIT No Attribution License (MIT-0) -- [Mulan Permissive Software License v2 (MulanPSL-2.0)](https://opensource.org/licenses/MulanPSL-2.0) +- Mulan Permissive Software License v2 (MulanPSL-2.0) -- [The Unlicense](https://opensource.org/licenses/unlicense) +- The Unlicense -- [W3C License (W3C)](https://opensource.org/licenses/W3C) +- W3C License (W3C) -- [University of Illinois/NCSA](http://opensource.org/licenses/UoI-NCSA.php) +- University of Illinois/NCSA -- [X.Net](http://opensource.org/licenses/xnet.php) +- X.Net -- [zlib/libpng](http://opensource.org/licenses/zlib-license.php) +- zlib/libpng - FSF autoconf license @@ -82,57 +82,57 @@ OpenHarmony项目还可能引入或依赖不同的第三方开源软件,这些 - OOXML XSD ECMA License -- [Microsoft Public License (MsPL)](http://www.opensource.org/licenses/ms-pl.html) +- Microsoft Public License (MsPL) -- [Python Software Foundation License](http://www.opensource.org/licenses/PythonSoftFoundation.php) +- Python Software Foundation License -- [Python Imaging Library Software License](https://github.com/python-pillow/Pillow/blob/master/LICENSE) +- Python Imaging Library Software License -- [Adobe Postcript(R) AFM files](https://spdx.org/licenses/APAFML.html) +- Adobe Postcript(R) AFM files -- [Boost Software License Version 1.0](http://www.opensource.org/licenses/BSL-1.0) +- Boost Software License Version 1.0 -- [WTF Public License](http://www.wtfpl.net/) +- WTF Public License -- [The Romantic WTF public license](https://github.com/pygy/gosub/blob/master/LICENSE) +- The Romantic WTF public license -- [UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE](http://www.unicode.org/copyright.html#Exhibit1) +- UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE -- [Zope Public License 2.0](https://opensource.org/licenses/ZPL-2.0) +- Zope Public License 2.0 - ACE license -- [Oracle Universal Permissive License (UPL) Version 1.0](https://oss.oracle.com/licenses/upl/) +- Oracle Universal Permissive License (UPL) Version 1.0 -- [Open Grid Forum License](https://www.ogf.org/ogf/doku.php/about/copyright) +- Open Grid Forum License - Google "Additional IP Rights Grant (Patents)" file -- [Historical Permission Notice and Disclaimer](https://opensource.org/licenses/HPND) +- Historical Permission Notice and Disclaimer ### 不建议接纳的第三方依赖的许可证名单 原则上,不支持商用的许可证,以及其它包含不合理限制或义务的许可证不建议被接纳,OpenHarmony项目不建议接纳采用如下许可证的第三方依赖: - Intel Simplified Software License -- [JSR-275 License](https://github.com/unitsofmeasurement/jsr-275/blob/0.9.3/LICENSE.txt) -- [Microsoft Limited Public License](https://www.openhub.net/licenses/mslpl) -- [Amazon Software License (ASL)](https://aws.amazon.com/asl/) +- JSR-275 License +- Microsoft Limited Public License +- Amazon Software License (ASL) - Java SDK for Satori RTM license -- [Redis Source Available License (RSAL)](https://redislabs.com/community/licenses/) +- Redis Source Available License (RSAL) - Booz Allen Public License -- [Confluent Community License Version 1.0](https://www.confluent.io/confluent-community-license/) -- [Any license including the Commons Clause License Condition v1.0](https://commonsclause.com/) +- Confluent Community License Version 1.0 +- Any license including the Commons Clause License Condition v1.0 - Creative Commons Non-Commercial variants -- [Sun Community Source License 3.0](http://jcp.org/aboutJava/communityprocess/SCSL3.0.rtf) -- [GNU GPL 3](http://www.opensource.org/licenses/gpl-license.php) -- [GNU Affero GPL 3](http://www.opensource.org/licenses/agpl-v3.html) -- [BSD-4-Clause](https://spdx.org/licenses/BSD-4-Clause.html)/[BSD-4-Clause (University of California-Specific)](https://spdx.org/licenses/BSD-4-Clause-UC.html) +- Sun Community Source License 3.0 +- GNU GPL 3 +- GNU Affero GPL 3 +- BSD-4-Clause/BSD-4-Clause (University of California-Specific) - Facebook BSD+Patents license -- [NPL 1.0](https://spdx.org/licenses/NPL-1.0.html)/[NPL 1.1](https://spdx.org/licenses/NPL-1.1.html) +- NPL 1.0/NPL 1.1 - The Solipsistic Eclipse Public License -- [The "Don't Be A Dick" Public License](https://dbad-license.org/) -- [JSON License](http://www.json.org/license.html) +- The "Don't Be A Dick" Public License +- JSON License ## 引入特殊许可证的规则 diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" index 7c88515d1be29f7211403c4ead878da940d6755f..9c915ea4f67eb0ac3f127cad6c77743c6aed6a98 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" @@ -4,13 +4,13 @@ ### 设计规范 -[OpenHarmony架构设计原则](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99.md) +[OpenHarmony架构设计原则](https://gitee.com/openharmony/community/blob/master/sig/sig_qa/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99.md) [OpenHarmony API治理章程](../design/OpenHarmony-API-governance.md) [OpenHarmony安全设计规范](OpenHarmony-security-design-guide.md) -[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) +[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig_buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) ### 代码风格 @@ -38,11 +38,11 @@ 有关详细信息,请参考[贡献流程](贡献流程.md)。 -[代码门禁详细质量要求](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/%E4%BB%A3%E7%A0%81%E9%97%A8%E7%A6%81%E8%A6%81%E6%B1%82.md)。 +[代码门禁详细质量要求](https://gitee.com/openharmony/community/blob/master/sig/sig_qa/%E4%BB%A3%E7%A0%81%E9%97%A8%E7%A6%81%E8%A6%81%E6%B1%82.md)。 -[需求类Issue处理指导](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/issue%EF%BC%88%E9%9C%80%E6%B1%82%E7%B1%BB%EF%BC%89%E5%A4%84%E7%90%86%E6%8C%87%E5%AF%BC.md) +[需求类Issue处理指导](https://gitee.com/openharmony/community/blob/master/sig/sig_qa/issue%EF%BC%88%E9%9C%80%E6%B1%82%E7%B1%BB%EF%BC%89%E5%A4%84%E7%90%86%E6%8C%87%E5%AF%BC.md) -[缺陷类Issue处理指导](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/issue-%E7%BC%BA%E9%99%B7%E7%B1%BB-%E5%A4%84%E7%90%86%E6%8C%87%E5%AF%BC.md) +[缺陷类Issue处理指导](https://gitee.com/openharmony/community/blob/master/sig/sig_qa/issue_%E7%BC%BA%E9%99%B7%E7%B1%BB_%E5%A4%84%E7%90%86%E6%8C%87%E5%AF%BC.md) ## 社区安全问题披露
diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" "b/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" index 397ec70f4bef209c5bfe8dda393c160f5d440a2e..6743b12052f5ba6dcb4b4a05e60f01c0dbc39c71 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\346\226\207\346\241\243.md" @@ -2,10 +2,8 @@ 非常欢迎您贡献文档,我们鼓励开发者以各种方式参与文档反馈和贡献。您可以对现有文档进行评价、简单更改、反馈文档质量问题、贡献您的原创内容。 -卓越贡献者将会在开发者社区文档贡献专栏表彰公示。 - - [贡献方式](#贡献方式) -- [写作规范](写作规范.md) +- [文档风格](style-guide/Readme-CN.md) ## 内容版权 @@ -15,7 +13,7 @@ ## License -[Creative Commons License version 4.0](https://creativecommons.org/licenses/by/4.0/legalcode) +Creative Commons License version 4.0 ## 贡献方式 diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\346\265\201\347\250\213.md" "b/zh-cn/contribute/\350\264\241\347\214\256\346\265\201\347\250\213.md" index c874beef6347925bcbf81456add00264b4cb8c4f..9f0c341e9e61fa8cf3888795c75e488f57044ff0 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\346\265\201\347\250\213.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\346\265\201\347\250\213.md" @@ -225,7 +225,7 @@ repo push --br="20200903" --d="master" --content="#I1TVV4" 如果门禁通过,该Issue关联的所有PR均会自动标记“测试通过”。 -详细参考[代码门禁质量要求](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/%E4%BB%A3%E7%A0%81%E9%97%A8%E7%A6%81%E8%A6%81%E6%B1%82.md)。 +详细参考[代码门禁质量要求](https://gitee.com/openharmony/community/blob/master/sig/sig_qa/%E4%BB%A3%E7%A0%81%E9%97%A8%E7%A6%81%E8%A6%81%E6%B1%82.md)。 ## CI门户 diff --git a/zh-cn/design/hdi-design-specifications.md b/zh-cn/design/hdi-design-specifications.md index 5b20dd0799214d46a45197f8a4eb3b87b6628c3c..43833f5b29977d9bc94555cd2ba54a273fd6d5a3 100644 --- a/zh-cn/design/hdi-design-specifications.md +++ b/zh-cn/design/hdi-design-specifications.md @@ -3,7 +3,7 @@ ## 总览 硬件设备接口(以下简称为设备接口)作为连通驱动程序和系统服务进行数据流通的桥梁,直接影响着系统的高效性、稳定性、兼容性、可靠性以及数据的正确性、完整性。本文档的目的是规范OpenHarmony设备接口的设计和开发,保证接口的风格一致、功能完备,提升设备接口的设计质量。 -本章程由[Driver SIG](https://gitee.com/openharmony/community/blob/master/sig/sig-driver/sig_driver_cn.md)制定,经[PMC](https://gitee.com/link?target=https%3A%2F%2Fwww.openharmony.cn%2Fcommunity%2Fpmc%2F)批准发布;对本章程的修订必须经由Driver SIG评审后,由PMC批准发布。 +本章程由[Driver SIG](https://gitee.com/openharmony/community/blob/master/sig/sig_driver/sig_driver_cn.md)制定,经[PMC](https://gitee.com/link?target=https%3A%2F%2Fwww.openharmony.cn%2Fcommunity%2Fpmc%2F)批准发布;对本章程的修订必须经由Driver SIG评审后,由PMC批准发布。 **术语和定义:** diff --git a/zh-cn/device-dev/driver/driver-peripherals-camera-des.md b/zh-cn/device-dev/driver/driver-peripherals-camera-des.md index d817ef48a6a1796bdf5dd9e33743d23d84d2a6d6..bf3ac64033d3c3135dbf7fe4fca54faf03174060 100755 --- a/zh-cn/device-dev/driver/driver-peripherals-camera-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-camera-des.md @@ -633,7 +633,7 @@ Camera驱动的开发过程主要包含以下步骤: ### 开发实例 -在/drivers/peripheral/camera/hal/init目录下有一个关于Camera的demo,开机后会在/vendor/bin下生成可执行文件ohos_camera_demo,该demo可以完成Camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例,可参考[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/init)。 +在/drivers/peripheral/camera/hal/test/demo目录下有一个关于Camera的demo,开机后会在/vendor/bin下生成可执行文件ohos_camera_demo,该demo可以完成Camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例,可参考[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/test/demo)。 1. 在main函数中构造一个CameraDemo 对象,该对象中有对Camera初始化、启停流、释放等控制的方法。下面mainDemo->InitSensors()函数为初始化CameraHost,mainDemo->InitCameraDevice()函数为初始化CameraDevice。 diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index 6830f1c25d24f603a0a5d78a2123bca96ea98c9d..4334e426a66c53801fb1b9f044eaad0426f5a57c 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -62,6 +62,7 @@ - [动态加载与链接](kernel-small-bundles-linking.md) - [虚拟动态共享库](kernel-small-bundles-share.md) - [轻量级进程间通信](kernel-small-bundles-ipc.md) + - [容器隔离](kernel-small-bundles-container.md) - 文件系统 - [虚拟文件系统](kernel-small-bundles-fs-virtual.md) - [支持的文件系统](kernel-small-bundles-fs-support.md) diff --git a/zh-cn/device-dev/kernel/figures/container-001.png b/zh-cn/device-dev/kernel/figures/container-001.png new file mode 100644 index 0000000000000000000000000000000000000000..70fa4f4c421e863bdc6f1e897d46f5a22f28091a Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/container-001.png differ diff --git a/zh-cn/device-dev/kernel/figures/container-002.png b/zh-cn/device-dev/kernel/figures/container-002.png new file mode 100644 index 0000000000000000000000000000000000000000..fac8e06cb9498e5d08df9f11cf9da20f65848ff6 Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/container-002.png differ diff --git a/zh-cn/device-dev/kernel/figures/container-003.png b/zh-cn/device-dev/kernel/figures/container-003.png new file mode 100644 index 0000000000000000000000000000000000000000..41761baa328686aadf90ea31a62ea8ea8d455754 Binary files /dev/null and b/zh-cn/device-dev/kernel/figures/container-003.png differ diff --git a/zh-cn/device-dev/kernel/kernel-small-bundles-container.md b/zh-cn/device-dev/kernel/kernel-small-bundles-container.md new file mode 100644 index 0000000000000000000000000000000000000000..00d8733ec7050f78f25db4c1e80c65db816635dd --- /dev/null +++ b/zh-cn/device-dev/kernel/kernel-small-bundles-container.md @@ -0,0 +1,363 @@ +# 容器隔离 + +## 概述 + +容器(Container)提供了一种资源隔离的解决方案。系统中许多资源是全局管理的。例如进程PID、主机信息、用户信息等,容器机制是对这种全局资源的隔离,使得处于不同容器的进程拥有独立的全局系统资源,改变一个容器中的系统资源只会影响当前容器里的进程,对其他容器中的进程没有影响。 + +LiteOS-A内核容器隔离功能包含7个容器:UTS容器、PID容器、Mount容器、Network容器、TIME容器、IPC容器、User容器。通过所在进程ProcessCB的Container和Credentials保存。 + +隔离的容器如下表。 + +| 编号 | 名称 | 宏定义/flag | 隔离资源 | 数据结构定义位置 | +| :-------- | :------------- | :------------------- | :----------------------- | :----------------------- | +| 1 | UTS | CLONE_NEWUTS | 主机名,域名,版本信息 |struct Container | +| 2 | PID | CLONE_NEWPID | 进程ID |struct Container | +| 3 | Mount | CLONE_NEWNS | 文件系统挂载点 |struct Container | +| 4 | Network | CLONE_NEWNET | 网络系统资源 |struct Container | +| 5 | TIME | CLONE_NEWTIME | 时钟资源 |struct Container | +| 6 | IPC | CLONE_NEWIPC | 进程间通信资源 |struct Container | +| 7 | User | CLONE_NEWUSER | 用户和用户组 |struct Credentials | + +容器之间的资源隔离,细分为两种: + + - 全局隔离:属于平行关系(无继承关系)的容器,所有容器之间的容器类资源彼此不可见。 + + - 非全局隔离:属于有父子继承关系的容器,同一层的各容器之间资源不可见,但上层容器仍然可以访问下层容器资源。 + +PID容器通过 unshare/setns 切换时,切换子进程的容器,而本进程容器不变。 + +通过在子进程ProcessCB中添加对应容器集合Container和用户容器,完成对容器功能的支持,并通过编译开关控制特性的开启和关闭。 + + - 每个进程ProcessCB包含一个Container指针,该指针指向真正分配的Container结构。通过这种方式,进程可单独拥有一个Container结构,也可共享同一个Container结构。 进一步分解,在Container结构中,包含各容器指针,分别指向UTS容器、PID容器、Network容器、Mount容器、TIME容器、IPC容器。 + + - 每个进程ProcessCB对应一个Credentials结构,单独管理User容器,便于模块化、单独处理User容器的特有逻辑。 + + + +![总体设计-总体结构-1](figures/container-001.png) + +### 各容器简介 + +#### **UTS容器** + +UTS 容器用于对主机名和域名进行隔离。 + +每一个进程对应有一个自己的UTS Container,用来隔离容器的内核名称、版本等信息,不同容器查看到的都是属于自己的信息,相互间不能查看。 + +#### **Mount容器** + +用于隔离文件挂载点。在一个容器里挂载、卸载的动作不会影响到其他容器。 + +通过文件挂载容器,实现各进程间相互独立的使用文件挂载系统,子进程在独立的文件挂载容器里面进行挂载操作,可以建立自身的文件挂载结构: + +- 文件挂载容器的基础实现,创建进程时根据clone传入的参数flag在各自进程创建文件挂载容器,将挂载信息从全局更改为与文件挂载容器相关联。 + +- 创建容器后,修改获取当前挂载信息的实现,将从全局或者更改为当前文件挂载容器中获取,使进程挂载、卸载或者访问挂载文件操作不会对其他进程挂载信息产生影响或者访问到其他进程的文件挂载信息。 + +#### **PID容器** + +用于隔离进程号,不同容器的进程可以使用相同的虚拟进程号。 + + 进程容器主要用于进程的隔离,特点如下: + +- 容器间的进程ID相互独立。 +- 父容器可以看到子容器中的进程,且同一个进程在父容器中的进程ID和子容器中的进程ID相互独立。 +- 子容器无法看到父容器中的进程。 +- 在根容器下可以看到系统的所有进程。 + +#### **Network容器** + +用于隔离系统网络设备和网络栈。 + +Network容器对TCP/IP协议栈和网络设备资源进行隔离,以达到隔离目的。 + + - 传输层隔离:对端口号进行隔离,Network容器内的可用端口号范围是0~65535,进程绑定的是自己所属容器的端口号,所以不同Network容器的进程可以对同一个TCP/UDP端口号进行绑定,且互相之间没有影响。 + - IP层隔离:对IP资源进行隔离,每个容器都有属于自己的IP资源,在一个Network容器内修改IP对其他Network容器没有影响。 + - 网络设备隔离:对网卡进行隔离,每个容器都有属于自己的网卡,不同Network容器内的网卡设备之间相互隔离无法通信,用户可以通过配置veth-pair解决不同容器间的通信问题。 + +#### **User容器** + +用于隔离用户和用户组。 + +User Container是用来隔离和分割管理权限的,管理权限实质分为两部分uid/gid和Capability。 + +- UID/GID + + User Container是对资源的一种隔离,主要隔离uid/gid,处于不同的User Container具有不同的uid/gid,每个User container拥有独立的从0开始的uid/gid。这样容器中的进程可以拥有root权限,但是它的root权限会被限制在一小块范围之内。改变一个User Container中的值只会影响当前User Container,对其他User Container中的进程无影响。 + +- Capability + + User Container通过设置Capability来实现能力隔离。 + + 每个进程在进程初始化的时候调用OsInitCapability对权限进行初始化,对用户提供修改和获取(SysCapSet/SysCapGet)权限的系统调用,用于修改进程的权限。 + +Capabilities的类型如下表: + +| 名称 | 描述 | +| --------------------- | ---------------------------------------------- | +| CAP_CHOWN | 修改文件所有者的权限 | +| CAP_DAC_EXECUTE | 忽略文件执行的 DAC 访问限制 | +| CAP_DAC_WRITE | 忽略文件写的 DAC 访问限制 | +| CAP_DAC_READ_SEARCH | 忽略文件读及目录搜索的 DAC 访问限制 | +| CAP_FOWNER | 忽略文件属主 ID 必须和进程用户 ID 相匹配的限制 | +| CAP_KILL | 允许对不属于自己的进程发送信号 | +| CAP_SETGID | 允许改变进程的GID | +| CAP_SETUID | 允许改变进程的UID | +| CAP_NET_BIND_SERVICE | 允许绑定到小于 1024 的端口 | +| CAP_NET_BROADCAST | 允许网络广播和多播访问 | +| CAP_NET_ADMIN | 允许执行网络管理任务 | +| CAP_NET_RAW | 允许使用原始套接字 | +| CAP_FS_MOUNT | 允许使用 chroot() 系统调用 | +| CAP_FS_FORMAT | 允许使用文件格式 | +| CAP_SCHED_SETPRIORITY | 允许设置优先级 | +| CAP_SET_TIMEOFDAY | 允许设置系统时间 | +| CAP_CLOCK_SETTIME | 允许改变系统时钟 | +| CAP_CAPSET | 允许设置任意的 capabilities | +| CAP_REBOOT | 允许重新启动系统 | +| CAP_SHELL_EXEC | 允许执行shell | + +#### **TIME容器** + +用于隔离系统的时间维护信息。 + +每一个进程对应有一个自己的TIME Container,用来隔离`CLOCK_MONOTONIC`和`CLOCK_MONOTONIC_RAW`对应的时钟,不同容器中的进程在对`CLOCK_MONOTONIC`和`CLOCK_MONOTONIC_RAW`时钟进行对应的时间操作调用时,彼此之间时钟的数值相对独立,实现安全容器间系统时钟的隔离。 + +容器(当前进程的time_for_children容器)中时钟的偏移量记录在`/proc/PID/timens_offsets`文件中,通过修改该文件,可以对应修改TIME容器的偏移信息。这些偏移是相对于初始时间容器中的时钟值表示的。 + +当前,创建TIME Container的唯一方法是通过使用`CLONE_NEWTIME`标志调用`unshare`。该调用将创建一个新的TIME Container,但不会将调用过程放在新的容器中。而是调用进程的随后创建的子级将放置在新的容器中。 + +这允许时钟偏移,用于新的容器的第一进程被放置在容器之前进行设置`/proc/PID/timens_offsets`文件。 + +#### **IPC容器** + +用于隔离进程间通信对象(IPC对象),包括消息队列和共享内存。 + +每一个进程对应有一个自己的IPC Container,用来隔离如下全局资源:消息队列、共享内存。 + +不同容器中的进程在对消息队列、共享内存进行对应的时间操作调用时,彼此之间是独立的。 + +- 消息队列隔离:把用于消息队列的全局变量结构LosQueueCB修改为IPC Container中的局部变量保存,从而实现在各自进程中的容器内可见,达到相互隔离的效果。 + +- 共享内存隔离:把用于共享内存的全局变量shmInfo,sysvShmMux,shmSegs,shmUsedPageCount修改为IPC Container中的局部变量保存,从而实现在各自进程中的容器内可见,达到相互隔离的效果。 + +### 运作机制 + +#### 新建容器流程 + +在系统初始化时,需要为初始进程(0号、1号、2号进程)创建同一个根容器,根容器类型包括所有7种类型:UTS容器、PID容器、User容器、Network容器、Mount容器、TIME容器、IPC容器。 + +后续可通过clone等接口为子进程新建容器(指定容器FLAG),未指定容器FLAG的情况下clone的子进程复用父进程容器。 + +![容器节点公共定义部分ContainerBase](figures/container-002.png) + + + +#### 切换容器流程 + +通过 unshare接口,将当前进程脱离当前所属容器,并转移到一个新建的容器。以IPC容器为例。 + +容器节点公共定义部分ContainerBase + +## 开发指导 + +应用层可基于容器隔离功能,进行如下场景的使用,新建容器、切换容器、销毁容器。 + +### 新建容器 + +创建子进程时可以完成新建容器。接口如下: + +**clone接口** + +通过clone()创建新进程的同时创建容器,是新建容器的一种常见做法,函数原型: + +``` +int clone(int (*fn)(void *), void *stack, int flags, void *arg, ... + /* pid_t *parent_tid, void *tls, pid_t *child_tid */ ); +``` + + - clone时可以指定新建的子进程通过容器隔离资源,使得资源(如UTS信息)获取和修改只限于容器范围内,不影响其他容器。 + + - 若调用clone接口不指定容器相关FLAG,则会将子进程也放到父进程所在容器中,即复用/共享父进程的容器。 + +### 切换容器 + + 转移/切换容器是调整已有进程的容器。包括2种情况: + +- **unshare 接口** + + 通过 unshare接口,将当前进程脱离当前所属容器,并转移到一个新建的容器。函数原型: + ``` + int unshare(int flags); + ``` + + 参考其他内核的实现,PID容器特殊处理,PID容器通过 unshare/setns 切换时, 是切换子进程的容器,而本进程容器仍然保持不变。 + + 方法是,本进程将新建的容器记录下来,创建子进程时再根据记录信息进行容器归属。 + + 这一点上,与其他容器(如Network容器)有区别,其他容器的setns、unshare操作是直接对已有进程生效。 + + 可以一句话总结为: PID容器的setns和unshare操作,是针对后代进程的PID容器。 + +- **setns接口** + + 通过 setns接口,将当前进程脱离当前所属容器,并转移到一个已有的容器。便于灵活切换进程容器。 + + PID容器通过 setns 转移时, 是切换子进程的容器,而本进程容器仍然保持不变。同上文。函数原型: + + ``` + int setns(int fd, int nstype); + ``` + +### 销毁容器 + +进程终止时会退出所属容器,并对引用计数进行递减。引用计数减为0的对象,需要进行销毁。 + +通过kill接口,可向指定进程发送指定信号,通知进程执行关闭/退出动作。函数原型: + +``` +int kill(pid_t pid, int sig); +``` + +### 查询容器信息 + +容器隔离之后,系统用户可使用 ls 命令访问 /proc/[pid]/container/ 目录进行查看和确认。 + +``` +ls -l /proc/[pid]/container +``` + +| 属性 | 所属用户 | 所属用户组 | 文件名 | 说明 | +| :--------- | :------- | :--------- | :--------------------------------------- | :--------------------- | +| lr--r--r-- | u:0 | g:0 | net -> 'net:[4026531847]' | 链接对象为容器唯一编号 | +| lr--r--r-- | u:0 | g:0 | user -> 'user:[4026531841]' | 同上 | +| lr--r--r-- | u:0 | u:0 | time_for_children -> 'time:[4026531846]' | 同上 | +| lr--r--r-- | u:0 | g:0 | time -> 'time:[4026531846]' | 同上 | +| lr--r--r-- | u:0 | g:0 | ipc -> 'ipc:[4026531845]' | 同上 | +| lr--r--r-- | u:0 | g:0 | mnt -> 'mnt:[4026531844]' | 同上 | +| lr--r--r-- | u:0 | g:0 | uts -> 'uts:[4026531843]' | 同上 | +| lr--r--r-- | u:0 | g:0 | pid_for_children -> 'pid:[4026531842]' | 同上 | +| lr--r--r-- | u:0 | g:0 | pid -> 'pid:[4026531842]' | 同上 | + +### 容器配额 + +容器配额(plimits)的主要功能是限制进程组可以使用的资源,/proc/plimits 目录作为容器配额根目录。 + +- plimits文件系统为伪文件系统,需要实现文件与plimits控制变量的映射;通过文件操作,达到修改内核变量的目的。例如:memory限制器中,通过用户修改memory.limit文件内容,即可修改相应的内核变量值,进而限制内存分配。 +- plimits文件系统中,文件能够被读写,目录能够被增删。 +- plimits的目录,映射的是plimits的分组,所以需要在创建目录的时候,自动创建目录下的文件(这些文件映射为限制器的控制变量)。 +- 创建限制器的文件是以组为单位创建的,例如:创建memory限制器,在增加一个memory限制器的时候,会全量创建所需的文件,而不是单独创建单个文件。 + +采用编译宏“LOSCFG_PROCESS_LIMITS”进行开关控制,y打开,n关闭,默认关闭 + +打开编译开关,查看 /proc/plimits目录, 主要包含下列文件: + +| 权限 | 用户 | 用户组 | 文件名 | 描述 | 备注 | +| ---------- | ---- | ------ | ---------------- | --------------------------------- | ------------------------------------------------------------ | +| -r--r--r-- | u:0 | g:0 | sched.stat | 调度统计信息 | 输出格式:[PID runTime] | +| -r--r--r-- | u:0 | g:0 | sched.period | 调度周期配置 | 单位:us | +| -r--r--r-- | u:0 | g:0 | sched.quota | 调度配额配置 | 单位:us | +| -r--r--r-- | u:0 | g:0 | devices.list | 报告plimits中的进程访问的设备 | 输出格式:[type name access] | +| -r--r--r-- | u:0 | g:0 | devices.deny | 指定plimits中的进程可以访问的设备 | 写入格式:["type name access" >> device.deny] | +| -r--r--r-- | u:0 | g:0 | devices.allow | 报告plimits中的进程不能访问的设备 | 写入格式:["type name access" >> device.allow] | +| -r--r--r-- | u:0 | g:0 | ipc.stat | ipc对象申请统计信息 | 输出格式:[mq count: mq failed count:
shm size: shm failed count: ] | +| -r--r--r-- | u:0 | g:0 | ipc.shm_limit | 共享内存大小上限 | 单位:byte | +| -r--r--r-- | u:0 | g:0 | ipc.mq_limit | 消息个数上限 | 0~最大64位正整数 | +| -r--r--r-- | u:0 | g:0 | memory.stat | 内存统计信息 | 单位:byte | +| -r--r--r-- | u:0 | g:0 | memory.limit | 组内进程占用内存总量配额 | 单位:byte | +| -r--r--r-- | u:0 | g:0 | pids.max | 组内包括的最大进程个数 | / | +| -r--r--r-- | u:0 | g:0 | pids.priority | 组内包括的最高进程优先级 | / | +| -r--r--r-- | u:0 | g:0 | plimits.procs | 组内包含的所有进程的pid | / | +| -r--r--r-- | u:0 | g:0 | plimits.limiters | plimits组内包含的限制器 | / | + +其中devices参数说明: + +| type (设备类型) | name (设备名字) | access (相应的权限) | +| -------------------------------------------- | ----------------- | ---------------------------------- | +| a - 所有设备,可以是字符设备,也可以是块设备 | / | r - 允许进程读取指定设备 | +| b- 块设备 | / | w - 允许进程写入指定设备 | +| c - 字符设备 | / | m - 允许进程生成还不存在的设备文件 | + +## 参考 + +### 规格说明 + +#### 参数设定 + +内核支持每一种容器最大数默认为LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT。 + +内核初始化proc/sys/user目录,生成文件max_net_container,max_ipc_container,max_time_container,max_uts_container,max_user_container,max_pid_container,max_mnt_container并且将伪文件与内核参数绑定。用户配置伪文件即会修改对应的内核参数。当前容器数量如果小于上限,则可创建新的容器,否则返回NULL表示失败。 + +#### 容器唯一编号 + +各容器的全局唯一编号,统一基于一个固定值进行编号。 + +``` +#define CONTAINER_IDEX_BASE (0xF0000000) +inum = CONTAINER_IDEX_BASE + (unsigned int)i; +``` + +#### 规则设定 + +- PID容器和User容器,具有分层关系,最大支持3层;其他的UTS、Mount、Network容器无分层关系。 + +- 通过上述接口clone创建容器、setns切换容器、unshare切换容器时,需传入符合POSIX标准的FLAG,如下: + +| FLAG | clone | setns | unshare | +| ------------- | ---------------------------- | -------------------------------- | -------------------------------- | +| CLONE_NEWNS | 为子进程新建文件系统容器 | 将当前进程转移到指定文件系统容器 | 为本进程新建文件系统容器 | +| CLONE_NEWPID | 为子进程新建PID容器 | 将当前进程转移到指定PID容器 | 为本进程新建的子进程新建PID容器 | +| CLONE_NEWIPC | 为子进程新建IPC容器 | 将当前进程转移到指定IPC容器 | 为本进程新建IPC容器 | +| CLONE_NEWTIME | 为进程所属父进程新建TIME容器 | 暂不支持 | 为本进程新建的子进程新建TIME容器 | +| CLONE_NEWUSER | 为子进程新建User容器 | 将当前进程转移到指定User容器 | 为本进程新建User容器 | +| CLONE_NEWUTS | 为子进程新建UTSNAME容器 | 将当前进程转移到指定UTSNAME容器 | 为本进程新建UTSNAME容器 | +| CLONE_NEWNET | 为子进程新建Network容器 | 将当前进程转移到指定Network容器 | 为本进程新建Network容器 | + +- 容器功能采用编译宏、编译脚本中参数结合,完成特性的开关控制。 + + - 容器编译宏定义: + + ``` + // 容器功能总编译宏 + LOSCFG_CONTAINER + // 各容器编译宏 + LOSCFG_UTS_CONTAINER + LOSCFG_MNT_CONTAINER + LOSCFG_PID_CONTAINER + LOSCFG_NET_CONTAINER + LOSCFG_USER_CONTAINER + LOSCFG_TIME_CONTAINER + LOSCFG_IPC_CONTAINER + ``` + + - 测试用例编译宏定义: enable打开,disable关闭,默认关闭。 + ``` + LOSCFG_USER_TEST_MNT_CONTAINER + LOSCFG_USER_TEST_PID_CONTAINER + LOSCFG_USER_TEST_NET_CONTAINER + LOSCFG_USER_TEST_USER_CONTAINER + LOSCFG_USER_TEST_TIME_CONTAINER + LOSCFG_USER_TEST_IPC_CONTAINER + ``` + +### 开发实例 + +当前LiteOS-A冒烟用例中已包含对应接口的使用示例,请开发者自行编译验证,推荐用例路径如下: + +[创建UTS容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_uts_container_001.cpp) + +[Unshare 切换当前进程的UTS容器至一个新容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_uts_container_004.cpp) + +[setns切换,将当前进程的UTS容器切换至子进程的UTS容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_uts_container_005.cpp) + +[创建Network容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_net_container_001.cpp) + +[创建User容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_user_container_001.cpp) + +[创建PID容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_pid_container_023.cpp) + +[创建Mount容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_mnt_container_001.cpp) + +[创建IPC容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_ipc_container_001.cpp) + +[创建TIME容器](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_time_container_001.cpp) + diff --git a/zh-cn/device-dev/porting/Readme-CN.md b/zh-cn/device-dev/porting/Readme-CN.md index ce5b474e48144b84d7b14854c3920359c1141ea0..1eeb819b8b7688d8d2bfee1eceb446ca9ea73190 100644 --- a/zh-cn/device-dev/porting/Readme-CN.md +++ b/zh-cn/device-dev/porting/Readme-CN.md @@ -1,5 +1,5 @@ ## 概述 -目前OpenHarmony已经成立了SIG组[sig-devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)。该SIG组以支持更多第三方开发板为目标,提供开发板移植的支撑。 +目前OpenHarmony已经成立了SIG组[sig_devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)。该SIG组以支持更多第三方开发板为目标,提供开发板移植的支撑。 在了解开发板移植前,需要先了解一下OpenHarmony对设备的分类。不同设备类型的移植方法会有较大差异。 diff --git a/zh-cn/device-dev/porting/porting-minichip-prepare.md b/zh-cn/device-dev/porting/porting-minichip-prepare.md index 17b0298bf7957d83985bfc25a44454eae00c63c6..d5c216be37f456906cf52f05efa74c88ec4920a8 100644 --- a/zh-cn/device-dev/porting/porting-minichip-prepare.md +++ b/zh-cn/device-dev/porting/porting-minichip-prepare.md @@ -6,7 +6,7 @@ ## 搭建编译环境 -开展移植前请参考[开发环境准备](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md)完成环境搭建工作。 +开展移植前请参考[开发环境准备](../quick-start/quickstart-ide-env-win.md)完成环境搭建工作。 ## 获取源码 @@ -14,7 +14,7 @@ ### 获取操作 -请参考[获取源码](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md)完成源码下载并进行编译。 +请参考[获取源码](../get-code/sourcecode-acquire.md)完成源码下载并进行编译。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本文档仅适用于OpenHarmony LTS 3.0.1及之前版本,所以请获取对应版本的源码。 diff --git a/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md b/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md index d30d6c469b472703847e4bda2a8e0bd7f10f9795..5ba5c7ed9d3ccf8b8482cee0319a6037546cfa25 100644 --- a/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md +++ b/zh-cn/device-dev/porting/porting-smallchip-driver-plat.md @@ -1,7 +1,7 @@ # 平台驱动移植 -在这一步,我们会在源码目录//device/vendor_name/soc_name/drivers 目录下创建平台驱动,如果你要移植的SOC的厂商还没有创建仓库的话,请联系[sig-devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)创建。 +在这一步,我们会在源码目录//device/vendor_name/soc_name/drivers 目录下创建平台驱动,如果你要移植的SOC的厂商还没有创建仓库的话,请联系[sig_devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)创建。 建议的目录结构: diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index cef4fc63ae7bb134daabe3a6d01eadb7210a37d9..26f02d5000a01fa6623e9a308e8e103b84b63059 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -18,6 +18,10 @@ - [加快本地编译的一些参数](subsys-build-reference.md) - [查看NinjaTrace](subsys-build-reference.md) - [HAP编译构建指导](subsys-build-gn-hap-compilation-guide.md) + - Rust编译构建指导 + - [Rust模块配置规则和指导](subsys-build-rust-compilation.md) + - [交互工具使用指导](subsys-build-bindgen-cxx-guide.md) + - [Cargo2gn工具操作指导](subsys-build-cargo2gn-guide.md) - [ 常见问题](subsys-build-FAQ.md) - [ArkCompiler](subsys-arkcompiler-guide.md) - [分布式远程启动](subsys-remote-start.md) diff --git a/zh-cn/device-dev/subsystems/figures/bindgen_and_cxx_tools.png b/zh-cn/device-dev/subsystems/figures/bindgen_and_cxx_tools.png new file mode 100644 index 0000000000000000000000000000000000000000..637f6cfaaacb832f544a16c8be11c1b29642ac7d Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/bindgen_and_cxx_tools.png differ diff --git a/zh-cn/device-dev/subsystems/figures/bindgen_test.png b/zh-cn/device-dev/subsystems/figures/bindgen_test.png new file mode 100644 index 0000000000000000000000000000000000000000..4c4d01b567e35fd07ce7a8a90256281cd9fcc165 Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/bindgen_test.png differ diff --git a/zh-cn/device-dev/subsystems/figures/cpp_call_rust.png b/zh-cn/device-dev/subsystems/figures/cpp_call_rust.png new file mode 100644 index 0000000000000000000000000000000000000000..49503982f893fb6c24d1e41c24ae54aa9681e2c6 Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/cpp_call_rust.png differ diff --git a/zh-cn/device-dev/subsystems/figures/rust_call_cpp.png b/zh-cn/device-dev/subsystems/figures/rust_call_cpp.png new file mode 100644 index 0000000000000000000000000000000000000000..eba899d0b111c71420b43c36c21e519228a06d54 Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/rust_call_cpp.png differ diff --git a/zh-cn/device-dev/subsystems/figures/test_rlib_cargo_crate.png b/zh-cn/device-dev/subsystems/figures/test_rlib_cargo_crate.png new file mode 100644 index 0000000000000000000000000000000000000000..86ade8272f625e6aa4336c713d52ee537918531c Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/test_rlib_cargo_crate.png differ diff --git a/zh-cn/device-dev/subsystems/figures/test_rlib_crate.png b/zh-cn/device-dev/subsystems/figures/test_rlib_crate.png new file mode 100644 index 0000000000000000000000000000000000000000..3df5877b7a3f583513527de1adcdabb80755961a Binary files /dev/null and b/zh-cn/device-dev/subsystems/figures/test_rlib_crate.png differ diff --git a/zh-cn/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md b/zh-cn/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..21d8a83a6cf10af2162b5dcb637fcdf4eeb9486c --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md @@ -0,0 +1,421 @@ +# 交互工具使用指导 + +## 概述 + +Bindgen和CXX工具的主要功能是实现Rust和C/C++之间的交互。其中,Bindgen通过将C接口转换为Rust接口来实现Rust对C的调用,CXX可以通过建立C接口和Rust接口的映射关系来实现C++和Rust的相互调用。 + +![bindgen_and_cxx_tools](./figures/bindgen_and_cxx_tools.png) + +## Bindgen工具使用指导 + +### 操作步骤 +下面是一个使用bindgen实现Rust调用C的示例。 + +1. 在C代码侧,使用头文件lib.h定义两个接口,接口FuncAAddB用来实现两数求和,接口SayHello用来打印字符串。 + + ```c + #ifndef BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_ + #define BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_ + #include + #include "build/rust/tests/test_bindgen_test/test_for_hello_world/lib2.h" + + uint32_t FuncAAddB(uint32_t a, uint32_t b); + void SayHello(const char *message); + + #endif // BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_ + ``` + + +2. 在lib.c中添加对两个接口的对应实现。 + + ```c + #include "build/rust/tests/test_bindgen_test/test_for_hello_world/lib.h" + #include + #include + + void SayHello(const char *message) + { + printf("This is a test for bindgen hello world:\n"); + printf("%s\n", message); + } + + uint32_t FuncAAddB(uint32_t a, uint32_t b) + { + printf("This is a test for bindgen of a + b:\n"); + return a + b; + } + ``` + +3. 添加文件main.rs,就可以在Rust侧通过c_ffi实现对C侧的接口调用。注意Rust侧调用的不安全接口需要使用unsafe封装。 + + ```rust + //! bindgen test for hello world + #![allow(clippy::approx_constant)] + mod c_ffi { + #![allow(dead_code)] + #![allow(non_upper_case_globals)] + #![allow(non_camel_case_types)] + include!(env!("BINDGEN_RS_FILE")); + } + /// pub fn add_two_numbers_in_c + pub fn add_two_numbers_in_c(a: u32, b: u32) -> u32 { + unsafe { c_ffi::FuncAAddB(a, b) } + } + + use std::ffi::c_char; + use std::ffi::CString; + + /// fn main() + fn main() { + println!("{} + {} = {}", 3, 7, add_two_numbers_in_c(3, 7)); + let c_str = CString::new("This is a message from C").unwrap(); + let c_world: *const c_char = c_str.as_ptr() as *const c_char; + unsafe { + c_ffi::SayHello(c_world); + } + } + + ``` + +4. 添加构建文件BUILD.gn,建立Rust模块对C模块的依赖。 + + ```GN + import("//build/ohos.gni") + + ohos_shared_library("c_lib") { + sources = [ "lib.c" ] + defines = [ "COMPONENT_IMPLEMENTATION" ] + } + + rust_bindgen("c_lib_bindgen") { + header = "lib.h" + } + + ohos_rust_executable("bindgen_test") { + deps = [ ":c_lib" ] + deps += [ ":c_lib_bindgen" ] + sources = [ "main.rs" ] + bindgen_output = get_target_outputs(":c_lib_bindgen") + inputs = bindgen_output + rustenv = [ "BINDGEN_RS_FILE=" + rebase_path(bindgen_output[0]) ] + crate_root = "main.rs" + } + ``` + +**调测验证** + +![bindgen_test](./figures/bindgen_test.png) + + +## CXX工具使用指导 + +### C++调用Rust接口 + +1. 在Rust侧文件lib.rs里mod ffi写清楚需要调用的C++接口,并将接口包含在extern "Rust"里面,暴露给C++侧使用。 + + ```rust + //! #[cxx::bridge] + #[cxx::bridge] + mod ffi{ + #![allow(dead_code)] + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] + struct Shared { + z: usize, + } + extern "Rust"{ + fn print_message_in_rust(); + fn r_return_primitive() -> usize; + fn r_return_shared() -> Shared; + fn r_return_rust_string() -> String; + fn r_return_sum(_: usize, _: usize) -> usize; + } + } + + fn print_message_in_rust(){ + println!("Here is a test for cpp call Rust."); + } + fn r_return_shared() -> ffi::Shared { + println!("Here is a message from Rust,test for ffi::Shared:"); + ffi::Shared { z: 1996 } + } + fn r_return_primitive() -> usize { + println!("Here is a message from Rust,test for usize:"); + 1997 + } + fn r_return_rust_string() -> String { + println!("Here is a message from Rust,test for String"); + "Hello World!".to_owned() + } + fn r_return_sum(n1: usize, n2: usize) -> usize { + println!("Here is a message from Rust,test for {} + {} is:",n1 ,n2); + n1 + n2 + } + + ``` + +2. C++侧将cxx工具转换出来的lib.rs.h包含进来,就可以使用C++侧的接口。 + + ```c++ + #include + #include "build/rust/tests/test_cxx/src/lib.rs.h" + + int main(int argc, const char* argv[]) + { + int a = 2021; + int b = 4; + print_message_in_rust(); + std::cout << r_return_primitive() << std::endl; + std::cout << r_return_shared().z << std::endl; + std::cout << std::string(r_return_rust_string()) << std::endl; + std::cout << r_return_sum(a, b) << std::endl; + return 0; + } + ``` + +3. 添加构建文件BUILD.gn。rust_cxx底层调用CXX工具将lib.rs文件转换成lib.rs.h和lib.rs.cc文件,ohos_rust_static_ffi实现Rust侧源码的编译,ohos_executable实现C++侧代码的编译。 + + ``` + import("//build/ohos.gni") + import("//build/templates/rust/rust_cxx.gni") + + rust_cxx("test_cxx_exe_gen") { + sources = [ "src/lib.rs" ] + } + + ohos_rust_static_ffi("test_cxx_examp_rust") { + sources = [ "src/lib.rs" ] + deps = [ "//build/rust:cxx_rustdeps" ] + } + + ohos_executable("test_cxx_exe") { + sources = [ "main.cpp" ] + sources += get_target_outputs(":test_cxx_exe_gen") + + include_dirs = [ "${target_gen_dir}" ] + deps = [ + ":test_cxx_examp_rust", + ":test_cxx_exe_gen", + "//build/rust:cxx_cppdeps", + ] + } + ``` + +**调测验证** +![cpp_call_rust](./figures/cpp_call_rust.png) + + +### Rust调用C++ + +1. 添加头文件client_blobstore.h。 + + ```c++ + #ifndef BUILD_RUST_TESTS_CLIENT_BLOBSTORE_H + #define BUILD_RUST_TESTS_CLIENT_BLOBSTORE_H + #include + #include "third_party/rust/cxx/include/cxx.h" + + namespace nsp_org { + namespace nsp_blobstore { + struct MultiBufs; + struct Metadata_Blob; + + class client_blobstore { + public: + client_blobstore(); + uint64_t put_buf(MultiBufs &buf) const; + void add_tag(uint64_t blobid, rust::Str add_tag) const; + Metadata_Blob get_metadata(uint64_t blobid) const; + + private: + class impl; + std::shared_ptr impl; + }; + + std::unique_ptr blobstore_client_new(); + } // namespace nsp_blobstore + } // namespace nsp_org + #endif + ``` + +2. 添加cpp文件client_blobstore.cpp。 + + ```c++ + #include + #include + #include + #include + #include + #include "src/main.rs.h" + #include "build/rust/tests/test_cxx_rust/include/client_blobstore.h" + + namespace nsp_org { + namespace nsp_blobstore { + // Toy implementation of an in-memory nsp_blobstore. + // + // In reality the implementation of client_blobstore could be a large complex C++ + // library. + class client_blobstore::impl { + friend client_blobstore; + using Blob = struct { + std::string data; + std::set tags; + }; + std::unordered_map blobs; + }; + + client_blobstore::client_blobstore() : impl(new class client_blobstore::impl) {} + + // Upload a new blob and return a blobid that serves as a handle to the blob. + uint64_t client_blobstore::put_buf(MultiBufs &buf) const + { + std::string contents; + + // Traverse the caller's res_chunk iterator. + // + // In reality there might be sophisticated batching of chunks and/or parallel + // upload implemented by the nsp_blobstore's C++ client. + while (true) { + auto res_chunk = next_chunk(buf); + if (res_chunk.size() == 0) { + break; + } + contents.append(reinterpret_cast(res_chunk.data()), res_chunk.size()); + } + + // Insert into map and provide caller the handle. + auto res = std::hash {} (contents); + impl->blobs[res] = {std::move(contents), {}}; + return res; + } + + // Add add_tag to an existing blob. + void client_blobstore::add_tag(uint64_t blobid, rust::Str add_tag) const + { + impl->blobs[blobid].tags.emplace(add_tag); + } + + // Retrieve get_metadata about a blob. + Metadata_Blob client_blobstore::get_metadata(uint64_t blobid) const + { + Metadata_Blob get_metadata {}; + auto blob = impl->blobs.find(blobid); + if (blob != impl->blobs.end()) { + get_metadata.size = blob->second.data.size(); + std::for_each(blob->second.tags.cbegin(), blob->second.tags.cend(), + [&](auto &t) { get_metadata.tags.emplace_back(t); }); + } + return get_metadata; + } + + std::unique_ptr blobstore_client_new() + { + return std::make_unique(); + } + } // namespace nsp_blobstore + } // namespace nsp_org + + ``` + +3. main.rs文件,在main.rs文件的ffi里面,通过宏include!将头文件client_blobstore.h引入进来,从而在Rust的main函数里面就可以通过ffi的方式调用C++的接口。 + + ```rust + //! test_cxx_rust + #[cxx::bridge(namespace = "nsp_org::nsp_blobstore")] + mod ffi { + // Shared structs with fields visible to both languages. + struct Metadata_Blob { + size: usize, + tags: Vec, + } + + // Rust types and signatures exposed to C++. + extern "Rust" { + type MultiBufs; + + fn next_chunk(buf: &mut MultiBufs) -> &[u8]; + } + + // C++ types and signatures exposed to Rust. + unsafe extern "C++" { + include!("build/rust/tests/test_cxx_rust/include/client_blobstore.h"); + + type client_blobstore; + + fn blobstore_client_new() -> UniquePtr; + fn put_buf(&self, parts: &mut MultiBufs) -> u64; + fn add_tag(&self, blobid: u64, add_tag: &str); + fn get_metadata(&self, blobid: u64) -> Metadata_Blob; + } + } + + // An iterator over contiguous chunks of a discontiguous file object. + // + // Toy implementation uses a Vec> but in reality this might be iterating + // over some more complex Rust data structure like a rope, or maybe loading + // chunks lazily from somewhere. + /// pub struct MultiBufs + pub struct MultiBufs { + chunks: Vec>, + pos: usize, + } + /// pub fn next_chunk + pub fn next_chunk(buf: &mut MultiBufs) -> &[u8] { + let next = buf.chunks.get(buf.pos); + buf.pos += 1; + next.map_or(&[], Vec::as_slice) + } + + /// fn main() + fn main() { + let client = ffi::blobstore_client_new(); + + // Upload a blob. + let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()]; + let mut buf = MultiBufs { chunks, pos: 0 }; + let blobid = client.put_buf(&mut buf); + println!("This is a test for Rust call cpp:"); + println!("blobid = {}", blobid); + + // Add a add_tag. + client.add_tag(blobid, "rust"); + + // Read back the tags. + let get_metadata = client.get_metadata(blobid); + println!("tags = {:?}", get_metadata.tags); + } + ``` + +4. 添加构建文件BUILD.gn。使用CXX将main.rs转换成lib.rs.h和lib.rs.cc,同时将产物作为test_cxx_rust_staticlib的源码,编译Rust源码main.rs并将test_cxx_rust_staticlib依赖进来。 + + ``` + import("//build/ohos.gni") + + rust_cxx("test_cxx_rust_gen") { + sources = [ "src/main.rs" ] + } + + ohos_static_library("test_cxx_rust_staticlib") { + sources = [ "src/client_blobstore.cpp" ] + sources += get_target_outputs(":test_cxx_rust_gen") + include_dirs = [ + "${target_gen_dir}", + "//third_party/rust/cxx/v1/crate/include", + "include", + ] + deps = [ + ":test_cxx_rust_gen", + "//build/rust:cxx_cppdeps", + ] + } + + ohos_rust_executable("test_cxx_rust") { + sources = [ "src/main.rs" ] + deps = [ + ":test_cxx_rust_staticlib", + "//build/rust:cxx_rustdeps", + ] + } + ``` + +**调测验证** +![rust_call_cpp](./figures/rust_call_cpp.png) \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md b/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..1bd28164b41007f94187a2ab7459bfd79aeec40b --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-build-cargo2gn-guide.md @@ -0,0 +1,94 @@ +# Cargo2gn工具操作指导 +## 概述 + +rust三方库使用cargo编译,配置为Cargo.toml。集成到OpenHarmony上需要转换成BUILD.gn规则。为了满足这个需求,需要提供一个cargo2gn转换工具。当需要引入rust三方crate时使用cargo2gn转换工具来把三方库的Cargo.toml转换成BUILD.gn规则。cargo2gn可以单个库进行转换,也可以多个库进行批量转换。 + +## 单个库转换操作步骤 +1. 进入到需要转化的rust三方库的目录下,比如需要转化bindgen。 + + ``` + cd openharmony/third_party/rust/bindgen + ``` + +2. 创建配置文件cargo2gn.json,可以参考如下配置。 + + ``` + { + "copy-out": true, + "run": true, + "add-workspace": true, + "cargo-bin": "/mnt/xxx/openharmony/prebuilts/rustc/linux-x86_64/current/bin" + } + ``` + +3. 执行以下命令进行转换。 + + ``` + python /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json + ``` + + 转换结果 + + ``` + import("//build/templates/rust/ohos_cargo_crate.gni") + + ohos_cargo_crate("lib") { + crate_name = "bindgen" + crate_type = "rlib" + crate_root = "./lib.rs" + + sources = ["./lib.rs"] + edition = "2018" + cargo_pkg_version = "0.64.0" + cargo_pkg_authors = "Jyun-Yan You , Emilio Cobos Álvarez , Nick Fitzgerald , The Servo project developers" + cargo_pkg_name = "bindgen" + cargo_pkg_description = "Automatically generates Rust FFI bindings to C and C++ libraries." + deps = [ + "//third_party/rust/bitflags:lib", + "//third_party/rust/cexpr:lib", + "//third_party/rust/clang-sys:lib", + "//third_party/rust/lazy_static:lib", + "//third_party/rust/lazycell:lib", + "//third_party/rust/log:lib", + "//third_party/rust/peeking_take_while:lib", + "//third_party/rust/proc-macro2:lib", + "//third_party/rust/quote:lib", + "//third_party/rust/regex:lib", + "//third_party/rust/rustc-hash:lib", + "//third_party/rust/shlex:lib", + "//third_party/rust/syn:lib", + "//third_party/rust/which:lib", + ] + features = [ + "default", + "log", + "logging", + "static", + "which", + "which-rustfmt", + ] + build_root = "build.rs" + build_sources = ["build.rs"] + build_script_outputs = ["host-target.txt"] + } + ``` + + + +## 多个库批量转换操作步骤 +1. 进入到rust目录下。 + + ``` + cd openharmony/third_party/rust + ``` +2. 把所有需要转换的rust三方库添加到rust目录下的Cargo.toml的[workspace]里,如下所示。 + + ``` + [workspace] + members = [ + "aho-corasick", + "memchr", + ] + ``` +3. 执行单个库转换操作步骤的2和3。 + diff --git a/zh-cn/device-dev/subsystems/subsys-build-module.md b/zh-cn/device-dev/subsystems/subsys-build-module.md index 80a692a54f836cff2b0bbaaec9969a7e9bad06b9..b5e2555d32cea8a34f7dbf4e691aab6d79d85a2a 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-module.md +++ b/zh-cn/device-dev/subsystems/subsys-build-module.md @@ -23,6 +23,17 @@ ohos_app_scope ohos_js_assets ohos_resources +#rust模板 +ohos_rust_executable +ohos_rust_shared_library +ohos_rust_static_library +ohos_rust_proc_macro +ohos_rust_shared_ffi +ohos_rust_static_ffi +ohos_rust_cargo_crate +ohos_rust_systemtest +ohos_rust_unittest + #其他常用模板 #配置文件 ohos_prebuilt_etc @@ -315,9 +326,11 @@ ohos_prebuilt_static_library("helloworld") { ### Hap模板 -hap模板详见:[ HAP编译构建指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md) +hap模板详见:[ HAP编译构建指导](subsys-build-gn-hap-compilation-guide.md) +### Rust模板 +rust模板详见:[ Rust模块配置规则和指导](subsys-build-rust-compilation.md) ### 其他常用模板 diff --git a/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md b/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md new file mode 100644 index 0000000000000000000000000000000000000000..1fc2e56d6d6f306e3ce279b4e1fc460afd3ee577 --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-build-rust-compilation.md @@ -0,0 +1,360 @@ +# Rust模块配置规则和指导 + +## 概述 + +Rust是一门静态强类型语言,具有更安全的内存管理、更好的运行性能、原生支持多线程开发等优势。Rust官方也使用Cargo工具来专门为Rust代码创建工程和构建编译。 +OpenHarmony为了集成C/C++代码和提升编译速度,使用了GN + Ninja的编译构建系统。GN的构建语言简洁易读,Ninja的汇编级编译规则直接高效。 +为了在OpenHarmony中集成Rust代码,并最大程度发挥Rust和OpenHarmony中原有C/C++代码的交互性,采用GN作为统一构建工具,即通过GN构建Rust源码文件(xxx.rs),并增加与C/C++互操作、编译时lint、测试、IDL转换、三方库集成、IDE等功能。同时扩展gn框架,支持接口自动化转换,最大程度简化开发。 + +### 基本概念 + +| 术语 | 描述 | +| ----- | ------------------------------------------------------------ | +| Cargo | Cargo是Rust官方使用的构建工具,允许Rust项目声明其各种依赖项,并确保您始终获得可重复的构建。 | +| crate | crate是一个独立的可编译单元。 | +| lints | lints 是指出常见编程错误、错误、样式错误和可疑结构的工具。可以对程序进行更加广泛的错误分析。 | + + + +## 配置规则 +OpenHarmony提供了用于Rust代码编译构建的各类型GN模板,可以用于编译Rust可执行文件,动态库和静态库等。各类型模板说明如下: + +| GN模板 | 功能 | 输出 | +| ------------------------ | ----------------- | ----------------------------------------------- | +| ohos_rust_executable | rust可执行文件 | rust可执行文件,不带后缀 | +| ohos_rust_shared_library | rust动态库 | rust dylib动态库,默认后缀.dylib.so | +| ohos_rust_static_library | rust静态库 | rust rlib静态库,默认后缀.rlib | +| ohos_rust_proc_macro | rust proc_macro | rust proc_macro库, 默认后缀.so | +| ohos_rust_shared_ffi | rust FFI动态库 | rust cdylib动态库,给C/C++模块调用,默认后缀.so | +| ohos_rust_static_ffi | rust FFI静态库 | rust staticlib库,给C/C++模块调用,默认后缀.a | +| ohos_rust_cargo_crate | 三方包Cargo crate | rust三方crate,支持rlib、dylib、bin | +| ohos_rust_systemtest | rust系统测试用例 | rust可执行系统测试用例,不带后缀 | +| ohos_rust_unittest | rust单元测试用例 | rust可执行单元测试用例,不带后缀 | + + + +## 配置指导 +配置Rust模块与C/C++模块类似,参考[模块配置规则](subsys-build-module.md)。下面是使用不同模板的示例。 +### 配置Rust静态库示例 +该示例用于测试Rust可执行bin文件和静态库rlib文件的编译,以及可执行文件对静态库的依赖,使用模板ohos_rust_executable和ohos_rust_static_library。操作步骤如下: + +1. 创建build/rust/tests/test_rlib_crate/src/simple_printer.rs,如下所示: + + ```rust + //! simple_printer + + /// struct RustLogMessage + + pub struct RustLogMessage { + /// i32: id + pub id: i32, + /// String: msg + pub msg: String, + } + + /// function rust_log_rlib + pub fn rust_log_rlib(msg: RustLogMessage) { + println!("id:{} message:{:?}", msg.id, msg.msg) + } + ``` + +2. 创建build/rust/tests/test_rlib_crate/src/main.rs,如下所示: + + ```rust + //! rlib_crate example for Rust. + + extern crate simple_printer_rlib; + + use simple_printer_rlib::rust_log_rlib; + use simple_printer_rlib::RustLogMessage; + + fn main() { + let msg: RustLogMessage = RustLogMessage { + id: 0, + msg: "string in rlib crate".to_string(), + }; + rust_log_rlib(msg); + } + ``` + +3. 配置gn脚本build/rust/tests/test_rlib_crate/BUILD.gn,如下所示: + + ``` + import("//build/ohos.gni") + + ohos_rust_executable("test_rlib_crate") { + sources = [ "src/main.rs" ] + deps = [ ":simple_printer_rlib" ] + } + + ohos_rust_static_library("simple_printer_rlib") { + sources = [ "src/simple_printer.rs" ] + crate_name = "simple_printer_rlib" + crate_type = "rlib" + features = [ "std" ] + } + ``` + +4. 执行编译得到的可执行文件,运行结果如下: + + ![test_rlib_crate](./figures/test_rlib_crate.png) + +### 配置三方库示例 +该示例用于测试包含预编译文件build.rs的三方静态库rlib文件的编译,使用了模板ohos_rust_executable和ohos_rust_cargo_crate。操作步骤如下: + +1. 创建build/rust/tests/test_rlib_cargo_crate/crate/src/lib.rs,如下所示: + + ```rust + include!(concat!(env!("OUT_DIR"), "/generated/generated.rs")); + + pub fn say_hello_from_crate() { + assert_eq!(run_some_generated_code(), 45); + #[cfg(is_new_rustc)] + println!("Is new rustc"); + #[cfg(is_old_rustc)] + println!("Is old rustc"); + #[cfg(is_ohos)] + println!("Is ohos"); + #[cfg(is_mac)] + println!("Is darwin"); + #[cfg(has_feature_a)] + println!("Has feature_a"); + #[cfg(not(has_feature_a))] + panic!("Wasn't passed feature_a"); + #[cfg(not(has_feature_b))] + #[cfg(test_a_and_b)] + panic!("feature_b wasn't passed"); + #[cfg(has_feature_b)] + #[cfg(not(test_a_and_b))] + panic!("feature_b was passed"); + } + + #[cfg(test)] + mod tests { + /// Test features are passed through from BUILD.gn correctly. This test is the target configuration. + #[test] + #[cfg(test_a_and_b)] + fn test_features_passed_target1() { + #[cfg(not(has_feature_a))] + panic!("feature a was not passed"); + #[cfg(not(has_feature_b))] + panic!("feature b was not passed"); + } + + #[test] + fn test_generated_code_works() { + assert_eq!(crate::run_some_generated_code(), 45); + } + } + ``` + +2. 创建build/rust/tests/test_rlib_cargo_crate/crate/src/main.rs,如下所示: + + ```rust + pub fn main() { + test_rlib_crate::say_hello_from_crate(); + } + ``` + +3. 创建build/rust/tests/test_rlib_cargo_crate/crate/build.rs,如下所示: + + ```rust + use std::env; + use std::path::Path; + use std::io::Write; + use std::process::Command; + use std::str::{self, FromStr}; + + fn main() { + println!("cargo:rustc-cfg=build_script_ran"); + let my_minor = match rustc_minor_version() { + Some(my_minor) => my_minor, + None => return, + }; + + if my_minor >= 34 { + println!("cargo:rustc-cfg=is_new_rustc"); + } else { + println!("cargo:rustc-cfg=is_old_rustc"); + } + + let target = env::var("TARGET").unwrap(); + + if target.contains("ohos") { + println!("cargo:rustc-cfg=is_ohos"); + } + if target.contains("darwin") { + println!("cargo:rustc-cfg=is_mac"); + } + + let feature_a = env::var_os("CARGO_FEATURE_MY_FEATURE_A").is_some(); + if feature_a { + println!("cargo:rustc-cfg=has_feature_a"); + } + let feature_b = env::var_os("CARGO_FEATURE_MY_FEATURE_B").is_some(); + if feature_b { + println!("cargo:rustc-cfg=has_feature_b"); + } + + // Some tests as to whether we're properly emulating various cargo features. + assert!(Path::new("build.rs").exists()); + assert!(Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("build.rs").exists()); + assert!(Path::new(&env::var_os("OUT_DIR").unwrap()).exists()); + + // Confirm the following env var is set + env::var_os("CARGO_CFG_TARGET_ARCH").unwrap(); + + generate_some_code().unwrap(); + } + + fn generate_some_code() -> std::io::Result<()> { + let test_output_dir = Path::new(&env::var_os("OUT_DIR").unwrap()).join("generated"); + let _ = std::fs::create_dir_all(&test_output_dir); + // Test that environment variables from .gn files are passed to build scripts + let preferred_number = env::var("ENV_VAR_FOR_BUILD_SCRIPT").unwrap(); + let mut file = std::fs::File::create(test_output_dir.join("generated.rs"))?; + write!(file, "fn run_some_generated_code() -> u32 {{ {} }}", preferred_number)?; + Ok(()) + } + + fn rustc_minor_version() -> Option { + let rustc_bin = match env::var_os("RUSTC") { + Some(rustc_bin) => rustc_bin, + None => return None, + }; + + let output = match Command::new(rustc_bin).arg("--version").output() { + Ok(output) => output, + Err(_) => return None, + }; + + let rustc_version = match str::from_utf8(&output.stdout) { + Ok(rustc_version) => rustc_version, + Err(_) => return None, + }; + + let mut pieces = rustc_version.split('.'); + if pieces.next() != Some("rustc 1") { + return None; + } + + let next_var = match pieces.next() { + Some(next_var) => next_var, + None => return None, + }; + + u32::from_str(next_var).ok() + } + ``` + +4. 配置gn脚本build/rust/tests/test_rlib_cargo_crate/BUILD.gn,如下所示: + + ``` + import("//build/templates/rust/ohos_cargo_crate.gni") + + ohos_cargo_crate("target") { + crate_name = "test_rlib_crate" + crate_root = "crate/src/lib.rs" + sources = [ "crate/src/lib.rs" ] + + #To generate the build_script binary + build_root = "crate/build.rs" + build_sources = [ "crate/build.rs" ] + build_script_outputs = [ "generated/generated.rs" ] + + features = [ + "my-feature_a", + "my-feature_b", + "std", + ] + rustflags = [ + "--cfg", + "test_a_and_b", + ] + rustenv = [ "ENV_VAR_FOR_BUILD_SCRIPT=45" ] + } + + # Exists to test the case that a single crate has both a library and a binary + ohos_cargo_crate("test_rlib_crate_associated_bin") { + crate_root = "crate/src/main.rs" + crate_type = "bin" + sources = [ "crate/src/main.rs" ] + + #To generate the build_script binary + build_root = "crate/build.rs" + build_sources = [ "crate/build.rs" ] + features = [ + "my-feature_a", + "my-feature_b", + "std", + ] + rustenv = [ "ENV_VAR_FOR_BUILD_SCRIPT=45" ] + deps = [ ":target" ] + } + ``` + +5. 执行编译得到的可执行文件,运行结果如下: + + ![test_rlib_cargo_crate](./figures/test_rlib_cargo_crate.png) + +### 其他源码实例 +在build/rust/tests目录下有Rust各类型模块的配置实例可供参考: +| 用例目录 | 测试功能 | +| -------------------------------------------- | ------------------------------------------------------------ | +| build/rust/tests/test_bin_crate | 测试ohos_rust_executable的host和target编译链接及运行 | +| build/rust/tests/test_static_link | 测试ohos_rust_executable对libstd.rlib进行静态链接 | +| build/rust/tests/test_dylib_crate | 测试ohos_rust_executable对ohos_rust_shared_library的编译依赖和运行 | +| build/rust/tests/test_rlib_crate | 测试ohos_rust_executable对ohos_rust_static_library的编译依赖和运行 | +| build/rust/tests/test_proc_macro_crate | 测试ohos_rust_executable对ohos_rust_proc_macro的编译依赖和运行,对不同类型都有用例覆盖 | +| build/rust/tests/test_cdylib_crate | 测试ohos_rust_executable对ohos_rust_shared_ffi的编译依赖和运行 | +| build/rust/tests/test_staticlib_crate | 测试ohos_rust_executable对ohos_rust_static_ffi的编译依赖和运行 | +| build/rust/tests/test_rust_ut | 测试ohos_rust_unittest,用例代码与特性代码在同一个文件中 | +| build/rust/tests/test_rust_st | 测试ohos_rust_systemtest,用例代码在独立的test目录中 | +| build/rust/tests/test_bin_cargo_crate | 测试ohos_cargo_crate对拥有build.rs预编译的可执行文件编译链接和运行,适用于rust三方crate编译依赖 | +| build/rust/tests/test_rlib_cargo_crate | 测试ohos_cargo_crate对拥有build.rs预编译的静态库文件编译链接和运行,适用于rust三方crate编译依赖 | +| build/rust/tests/test_proc_macro_cargo_crate | 测试ohos_cargo_crate对拥有build.rs预编译的过程宏编译链接和运行,适用于rust三方crate编译依赖 | + +## 参考 + +### 特性点实例 + +#### Rust源码依赖调用C/C++库 +OpenHarmony上C/C++模块动态库默认用.z.so后缀,但是Rust的编译命令通过-l链接时,默认只会链接.so后缀的动态库。因此如果要依赖一个C/C++动态库编译模块,需要在该动态库的GN构建文件中添加output_externsion = "so"的声明,这样编译得到的动态库将会以".so"作为后缀,而不是".z.so"。 +在Rust源码中如果直接链接动态库,后缀也需要使用".so",这时使用动态库的中间名,不需要添加lib前缀。例如Rust源码中链接libhilog.so: +```rust +#[link(name = "hilog")] +``` +#### externs使用 +某个模块如果依赖二进制的rlib库,可以使用externs属性: +``` +executable("foo") { + sources = [ "main.rs" ] + externs = [{ # 编译时会转成`--extern bar=path/to/bar.rlib` + crate_name = "bar" + path = "path/to/bar.rlib" + }] +} +``` +### lints规则 +OpenHarmony框架支持rustc lints和clippy lints两种lints,每种lints划为三个等级的标准:"openharmony"、"vendor"和"none",严格程度按照"openharmony" -> "vendor" -> "none"逐级递减。 +配置Rust模块时可以通过rustc_lints和clippy_lints来指定使用lints的等级。 +模块中没有配置rustc_lints或者clippy_lints时会根据模块所在路径来匹配lints等级。不同路径下的Rust代码的语法规范会有不同程度地约束,因此用户在OpenHarmony配置Rust代码编译模块时还应关注模块所在路径。 +#### rustc lints和clippy lints的各等级标志 +| **lints类型** | **模块属性** | **lints等级** | **lints等级标志** | **lints内容** | +| ------------- | ------------ | ------------- | ----------------- | ------------------------------------------------------------ | +| rustc_lints | rustc_lints | openharmony | RustOhosLints | "-A deprecated", "-D missing-docs", "-D warnigngs" | +| rustc_lints | rustc_lints | vendor | RustcVendorLints | "-A deprecated", "-D warnigs" | +| rustc_lints | rustc_lints | none | allowAllLints | "-cap-lints allow" | +| clippy lints | clippy lints | openharmony | ClippyOhosLints | "-A clippy::type-complexity", "-A clippy::unnecessary-wraps", "-A clippy::unusual-byte-groupings", "-A clippy::upper-case-acronyms" | +| clippy lints | clippy lints | vendor | ClippyVendorLints | "-A clippy::complexity", "-A Clippy::perf", "-A clippy::style" | +| clippy lints | clippy lints | none | allowAllLints | "--cap-lints allow" | + +#### 代码路径与lints等级的对应关系 +| 路径 | Lints等级 | +| ---------- | ----------- | +| thirdparty | none | +| prebuilts | none | +| vendor | vendor | +| device | vendor | +| others | openharmony | + diff --git a/zh-cn/device-dev/subsystems/subsys-power-level-LED-color.md b/zh-cn/device-dev/subsystems/subsys-power-level-LED-color.md index 9ac5e5d617e9133ad84bb9f4496d77d83dc07f5a..b20548fbae050749788b8c54f97cd30623d049b2 100644 --- a/zh-cn/device-dev/subsystems/subsys-power-level-LED-color.md +++ b/zh-cn/device-dev/subsystems/subsys-power-level-LED-color.md @@ -58,13 +58,18 @@ Linux调测环境,相关要求和配置可参考《[快速入门](../quick-sta } ``` - **表1** 电量与LED灯颜色映射配置说明 + **表1** 电量等级说明 - | 节点名称 | 作用 | + | 电量等级 | 描述 | | -------- | -------- | | low | 低电量 | | normal | 正常电量 | | high | 高电量 | + + **表2** 电量区间与LED灯颜色映射配置说明 + + | 配置项 | 描述 | + | -------- | -------- | | soc | 电量区间 | | rgb | LED灯RGB组合 | diff --git a/zh-cn/device-dev/subsystems/subsys-power-stats-power-average-customization.md b/zh-cn/device-dev/subsystems/subsys-power-stats-power-average-customization.md index adab21840e613eb520dc9f1447b07bab3bea30a5..7669407897e490766665d41ca82e2fc08b708f80 100644 --- a/zh-cn/device-dev/subsystems/subsys-power-stats-power-average-customization.md +++ b/zh-cn/device-dev/subsystems/subsys-power-stats-power-average-customization.md @@ -191,7 +191,7 @@ Linux调测环境,相关要求和配置可参考《[快速入门](../quick-sta 6. 耗电统计配置文件定制成功后,耗电统计会根据定制的耗电基准进行计算。 -7. 通过batterystatistics模块提供的[JS API](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.batteryStatistics.d.ts)或[Inner API](https://gitee.com/openharmony/powermgr_battery_statistics/blob/master/interfaces/innerkits/include/battery_stats_client.h)可以获得详细的耗电信息,验证定制的耗电基准。 +7. 通过batterystatistics模块提供的[JS API](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.batteryStatistics.d.ts)或[Inner API](https://gitee.com/openharmony/powermgr_battery_statistics/blob/master/interfaces/inner_api/include/battery_stats_client.h)可以获得详细的耗电信息,验证定制的耗电基准。 ## 参考 diff --git a/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md b/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md index c01af8520e18340a0db72842ab7b328fda1f7f1d..1ac256d5d8db38e4a21a2b65ce57eb7b784ee416 100644 --- a/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md +++ b/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @@ -418,7 +418,7 @@ eyJ0eXAiOiAiRFNMIn0=.eyJ0eXBlIjogImRlYnVnIiwgIm1hbnVmYWN0dXJlIjogIm9ob3MiLCAiYnJ ### 工具使用介绍 -为方便开发者对于“凭据文件”的进一步理解,设备安全等级管理模块提供了[凭据工具](https://gitee.com/openharmony/security_device_security_level/blob/master/oem_property/ohos/dslm_cred_tool.py),该工具是一个python脚本,基于OPENSSL命令行的简单封装,可以便捷的提供凭据文件的签发和验证功能。 +为方便开发者对于“凭据文件”的进一步理解,设备安全等级管理模块提供了[凭据工具](https://gitee.com/openharmony/security_device_security_level/blob/master/oem_property/ohos/standard/dslm_cred_tool.py),该工具是一个python脚本,基于OPENSSL命令行的简单封装,可以便捷的提供凭据文件的签发和验证功能。 其使用方法如下: 1. 签名密钥初始化: diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index 8940a99b9405ce3b07d9203e35d7e70723e05c86..26cbf9bbe2345509f7e9f83c475174b92c5b779a 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -216,6 +216,7 @@ - [动态加载与链接](kernel/kernel-small-bundles-linking.md) - [虚拟动态共享库](kernel/kernel-small-bundles-share.md) - [轻量级进程间通信](kernel/kernel-small-bundles-ipc.md) + - [容器隔离](kernel/kernel-small-bundles-container.md) - 文件系统 - [虚拟文件系统](kernel/kernel-small-bundles-fs-virtual.md) - [支持的文件系统](kernel/kernel-small-bundles-fs-support.md) @@ -540,7 +541,7 @@ - [xdevice测试调度框架使用指导](device-test/xdevice.md) - 调测工具 - [bytrace使用指导](subsystems/subsys-toolchain-bytrace-guide.md) - - [hdc 使用指导](subsystems/subsys-toolchain-hdc-guide.md) + - [hdc使用指导](subsystems/subsys-toolchain-hdc-guide.md) - [hiperf 使用指南](subsystems/subsys-toolchain-hiperf.md) - [XTS认证](device-test/xts.md) - 工具 diff --git "a/zh-cn/readme/ArkUI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/ArkUI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" index dc1ff40e771617f3c30c7de963431eb4625064fa..df00ec731a169af21ee6bf8026dfa2844a7907ef 100644 --- "a/zh-cn/readme/ArkUI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/ArkUI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" @@ -6,7 +6,7 @@ ## 简介 -ArkUI框架是OpenHarmony UI开发框架,提供开发者进行应用UI开发时所必需的能力,包括UI组件、动画、绘制、交互事件、JS API扩展机制等。ArkUI框架提供了两种开发范式,分别是基于eTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。 +ArkUI框架是OpenHarmony UI开发框架,提供开发者进行应用UI开发时所必需的能力,包括UI组件、动画、绘制、交互事件、JS API扩展机制等。ArkUI框架提供了两种开发范式,分别是基于ArkTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。 **框架结构** diff --git "a/zh-cn/readme/\345\252\222\344\275\223\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\345\252\222\344\275\223\345\255\220\347\263\273\347\273\237.md" index 5ecc31d2e210e10e6f51d7e0cc2619bb854343ca..85e807f08555075188d6a3e23c84e64775648ca0 100755 --- "a/zh-cn/readme/\345\252\222\344\275\223\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\345\252\222\344\275\223\345\255\220\347\263\273\347\273\237.md" @@ -26,7 +26,7 @@ - **Media**: 为应用提供播放、录制等接口,通过跨进程调用或直接调用方式,调用媒体引擎Gstreamer、Histreamer或其它引擎。 - mini设备上,Media部件调用Histreamer支持音频播放等功能。 - - small设备上,Media部件调用recorder_lite支持音视频录制,默认调用player_lite支持音视频播放,通过设置系统属性变量debug.media_service.histreamer为1使用histreamer。详细设置方法参见[syspara系统属性组件使用说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-boot-syspara.md)或者参见[syspara模块代码](https://gitee.com/openharmony/startup_syspara_lite)。 + - small设备上,Media部件调用recorder_lite支持音视频录制,默认调用player_lite支持音视频播放,通过设置系统属性变量debug.media_service.histreamer为1使用histreamer。详细设置方法参见[syspara系统属性组件使用说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-boot-init-sysparam.md)或者参见[syspara模块代码](https://gitee.com/openharmony/startup_syspara_lite)。 - standard设备上,Media部件调用Gstreamer支持音视频播放、音视频录制。 - **Audio**: Audio部件支持音频输入输出、策略管理、音频焦点管理等功能。 - **Camera**: Camera部件提供相机操作接口,支持预览、拍照、录像。 @@ -91,7 +91,7 @@ 如架构图示意,媒体提供了三大类功能接口,开发者可以根据使用诉求,综合使用一类或多类接口: -- 应用开发者使用媒体接口实现录像、预览和播放音视频,使用可以参考[多媒体开发指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-multimedia.md)。 +- 应用开发者使用媒体接口实现录像、预览和播放音视频,使用可以参考[多媒体开发指南](../application-dev/media)。 - 当使用简单播放录制功能时,可以使用Player和Recorder快速完成播放和录制功能。 - 提供了一组控制相机的有效接口,可以让用户方便开发使用相机。 - 开发者先创建camerakit组件对象,注册各种事件回调,这些事件回调是用来响应多媒体模块中事件响应的,之后调用创建camera就可以创建一个操作camera资源的对象,使用这个对象可以启动预览、录像或抓拍取流,及设置取流的相关参数。 diff --git a/zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md b/zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md index 8965da787ff93a3cb63e59cde2c50368aeb83134..879fa99eb707bdcf1f870357c4568baec12f29d3 100644 --- a/zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md @@ -66,7 +66,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md b/zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md index 627b7c1ff3bd48f7e2902c613d9eb4a2e4f29316..1bf13687086eca5505c12a77cfdb86b1491d9b32 100644 --- a/zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md @@ -69,7 +69,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0-LTS.md index 3d02a0031e96527af22b5eea6485e2afd81c2f55..017f75dc57bb696fc531564560a42f511559cefe 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0-LTS.md @@ -132,7 +132,7 @@ API变更请参考:[JS API 差异报告](api-diff/v3.0-LTS/js-apidiff-v3.0-lts ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.1-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.1-LTS.md index 5a165d4d67a45933981e830498fd248dbdb8b904..02443e1d8f5ecd95f65f6a84461df9ffe8a52c33 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.1-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.1-LTS.md @@ -71,7 +71,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md index 6dd84fdfeac418e6c8fb957d68205dbe65d3cf55..fe4b8f89a79062568bf9a629bd5b21898eeafbb1 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.2-LTS.md @@ -72,7 +72,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md index abf23f7d3675fc90e1c0b70213ce773c4e1726ee..de6c92504636765986d09defb39c2ac12a171116 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md @@ -72,7 +72,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md index 8d577c913225e56646a90f16a8c4d9d12a1a6163..1df0ea339d055ae974a18c9c47ea613e9e2816e5 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md @@ -100,7 +100,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md index a2fa9bf54bb06e639c06b8b6ba31b1d5a64b1da9..e8f4653934e3fe6ee0e54785cdebad75dd35da26 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md @@ -91,7 +91,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复安全漏洞列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.7-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.7-LTS.md index e88c57ae3db39fb0e7f25eb69c4a73b7f8ff9950..b666952881b0d8501ae8180eb7633296857d1ce1 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.7-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.7-LTS.md @@ -91,7 +91,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复安全漏洞列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md index 3d3cf5c436387fa04e1bfc085d7bf52e7507095b..4b08e7efbc79a1365f70e75b9aaaa40cb7b66cb6 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md +++ b/zh-cn/release-notes/OpenHarmony-v3.0.8-LTS.md @@ -91,7 +91,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复安全漏洞列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1-beta.md b/zh-cn/release-notes/OpenHarmony-v3.1-beta.md index 8637f3003d785e70ac0c03fdfdb663368a3139be..b9c359af741f32e7d1997b10549a66058afe5be3 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1-beta.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1-beta.md @@ -139,7 +139,7 @@ _[Changelog](api-diff/v3.1-beta/changelog-v3.1-beta.md)_ ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples & Codelabs @@ -151,17 +151,17 @@ _[Changelog](api-diff/v3.1-beta/changelog-v3.1-beta.md)_ | 名称 | 简介 | 开发语言 | | -------- | -------- | -------- | -| [Ets公共事件](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent) | 本示例展示了在eTS中如何使用CommonEvent的接口完成创建订阅者、订阅公共事件、发布公共事件、取消订阅的功能。 | eTS | +| [Ets公共事件](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent) | 本示例展示了在ArkTS中如何使用CommonEvent的接口完成创建订阅者、订阅公共事件、发布公共事件、取消订阅的功能。 | ArkTS | | [空气质量](https://gitee.com/openharmony/app_samples/tree/master/common/AirQuality) | 本示例使用JS实现了一个简单空气质量应用,使用折行显示能力显示空气质量信息,使用柱形图展示历史记录。 | JS | | [分布式计算器](https://gitee.com/openharmony/app_samples/tree/master/common/DistributeCalc) | 本示例使用JS分布式能力实现了一个简单的计算器应用,可以进行简单的数值计算,支持远程拉起另一个计算器FA,两个FA进行协同计算。 | JS | -| [EtsNotification](https://gitee.com/openharmony/app_samples/tree/master/common/Notification) | 本示例展示了在eTS中如何创建和删除Slot通道,如何发布和取消通知。 | eTS | -| [Ets资源管理](https://gitee.com/openharmony/app_samples/tree/master/common/ResourceManager) | 本示例展示了在eTS中如何调用资源管理的API接口实现字符串和图片资源信息的获取。 | eTS | +| [EtsNotification](https://gitee.com/openharmony/app_samples/tree/master/common/Notification) | 本示例展示了在ArkTS中如何创建和删除Slot通道,如何发布和取消通知。 | ArkTS | +| [Ets资源管理](https://gitee.com/openharmony/app_samples/tree/master/common/ResourceManager) | 本示例展示了在ArkTS中如何调用资源管理的API接口实现字符串和图片资源信息的获取。 | ArkTS | | [kikainput](https://gitee.com/openharmony/app_samples/tree/master/CompleteApps/KikaInput) | kikainput是一个轻量级的输入法应用,支持在运行OpenHarmony OS的智能终端上。 | JS | -| [eTS分布式数据管理](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) | 本示例展示了在eTS中分布式数据管理的使用,包括KVManager对象实例的创建和KVStore数据流转的使用。 | eTS | -| [轻量级数据存储](https://gitee.com/openharmony/app_samples/tree/master/data/LiteStorage) | 轻量级数据存储主要提供轻量级Key-Value操作,支持本地应用存储少量数据。本示例通过对购物车商品的添加和删除并保存退出的操作,使得再次打开应用时依然可以保留退出前的购物车信息,体现了轻量级存储在保存轻量级数据时的作用。 | eTS | -| [Ets进程信息](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Process) | 本示例展示了在eTS中如何获取进程信息和启动一个子进程运行一段shell,包括当前系统运行时间、获取进程当前工作目录、更改进程当前工作目录、发送signal到指定的进程、启动一个子进程、关闭子进程、退出当前系统的功能。 | eTS | -| [Ets运行锁](https://gitee.com/openharmony/app_samples/tree/master/common/Runninglock) | 本示例展示了阻止系统休眠的运行锁功能,通过黑白色壁纸模拟息屏、亮屏状态,来展示系统的休眠状态,从而对运行锁的功能进行测试,使得该运行锁在打开后可以阻止系统休眠。 | eTS | -| [字符串编解码](https://gitee.com/openharmony/app_samples/tree/master/Util/UtilStringCodec) | 本示例对字符串进行了特定格式的输出,对错误码的内容进行了文本输出,对字符串的编码和解码做了演示结果。 | eTS | +| [ArkTS分布式数据管理](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) | 本示例展示了在ArkTS中分布式数据管理的使用,包括KVManager对象实例的创建和KVStore数据流转的使用。 | ArkTS | +| [轻量级数据存储](https://gitee.com/openharmony/app_samples/tree/master/data/LiteStorage) | 轻量级数据存储主要提供轻量级Key-Value操作,支持本地应用存储少量数据。本示例通过对购物车商品的添加和删除并保存退出的操作,使得再次打开应用时依然可以保留退出前的购物车信息,体现了轻量级存储在保存轻量级数据时的作用。 | ArkTS | +| [Ets进程信息](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Process) | 本示例展示了在ArkTS中如何获取进程信息和启动一个子进程运行一段shell,包括当前系统运行时间、获取进程当前工作目录、更改进程当前工作目录、发送signal到指定的进程、启动一个子进程、关闭子进程、退出当前系统的功能。 | ArkTS | +| [Ets运行锁](https://gitee.com/openharmony/app_samples/tree/master/common/Runninglock) | 本示例展示了阻止系统休眠的运行锁功能,通过黑白色壁纸模拟息屏、亮屏状态,来展示系统的休眠状态,从而对运行锁的功能进行测试,使得该运行锁在打开后可以阻止系统休眠。 | ArkTS | +| [字符串编解码](https://gitee.com/openharmony/app_samples/tree/master/Util/UtilStringCodec) | 本示例对字符串进行了特定格式的输出,对错误码的内容进行了文本输出,对字符串的编码和解码做了演示结果。 | ArkTS | | [Js音频播放和管理](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) | 本示例展示了JS音频播放的使用方法,以及音频的音量大小设置。 | JS | | [JsVideo](https://gitee.com/openharmony/app_samples/tree/master/media/JsVideo) | 本示例使用JS UI中的<video/>组件,实现视频播放。可以通过video自带的控制栏进行播放、暂停等操作。 | JS | | [测试打点](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest) | 本示例展示了测试打点功能,包括应用打点与性能打点两部分。 | JS | @@ -180,17 +180,16 @@ _[Changelog](api-diff/v3.1-beta/changelog-v3.1-beta.md)_ | 名称 | 简介 | 开发语言 | | -------- | -------- | -------- | -| [分布式手写板(eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) | 基于分布式能力,实现多设备同步书写互动。 | eTS | +| [分布式手写板(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) | 基于分布式能力,实现多设备同步书写互动。 | ArkTS | | [分布式数据库](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData) | 基于分布式数据接口,实现多种设备上一致的数据访问体验。 | JS | | [关系型数据库](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) | 基于关系型数据库和数据管理能力,实现数据库相关应用服务的快速开发。 | JS | -| [极简声明式UI范式(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) | 基于OpenHarmony eTS UI,实现一个图库应用。 | eTS | -| [一次开发多端部署(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/MultiDeploymentEts) | 基于OpenHarmony eTS UI,实现一次布局,多端部署。 | eTS | -| [购物应用(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) | 基于OpenHarmony eTS UI丰富的组件实现购物商城应用。 | eTS | -| [Page内和Page间导航跳转](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility) | 入门教程,学习如何完成Page内和Page间的页面导航跳转。 | eTS | -| [转场动画的使用(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimtaionEts) | 基于OpenHarmony eTS UI转场动画,实现了页面间转场、组件内转场以及共享元素转场。 | eTS | -| [基础组件Slider的使用(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderApplicationEts) | 基于OpenHarmony eTS UI,使用slider组件,实现可调节风车大小和转速的动画效果。 | eTS | -| [流式布局(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/FlowLayoutEts) | 基于OpenHarmony eTS UI,实现流式布局效果。 | eTS | -| [弹窗(eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) | 基于OpenHarmony eTS UI,实现警告弹窗和自定义弹窗。 | eTS | +| [极简声明式UI范式(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) | 基于OpenHarmony ArkUI,实现一个图库应用。 | ArkTS | +| [一次开发多端部署(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/Multi_device) | 基于OpenHarmony ArkUI,实现一次布局,多端部署。 | ArkTS | +| [购物应用(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) | 基于OpenHarmony ArkUI丰富的组件实现购物商城应用。 | ArkTS | +| [转场动画的使用(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimation) | 基于OpenHarmony ArkUI转场动画,实现了页面间转场、组件内转场以及共享元素转场。 | ArkTS | +| [基础组件Slider的使用(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderExample) | 基于OpenHarmony eTS UI,使用slider组件,实现可调节风车大小和转速的动画效果。 | ArkTS | +| [流式布局(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/FlowLayoutEts) | 基于OpenHarmony ArkUI,实现流式布局效果。 | ArkTS | +| [弹窗(ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) | 基于OpenHarmony ArkUI,实现警告弹窗和自定义弹窗。 | ArkTS | ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1-release.md b/zh-cn/release-notes/OpenHarmony-v3.1-release.md index 4be25e2a100c4aac21fa82a474fbf84fdda649d0..21732e03288469bccac9c5dfce8eafbf59216d33 100755 --- a/zh-cn/release-notes/OpenHarmony-v3.1-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1-release.md @@ -195,7 +195,7 @@ _[API差异报告](api-diff/v3.1-Release/Readme-CN.md)_ ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples & Codelabs @@ -205,23 +205,23 @@ _[API差异报告](api-diff/v3.1-Release/Readme-CN.md)_ | 子系统 | 名称 | 简介 | 开发语言 | | -------- | -------- | -------- | -------- | -| 电话服务 | [短信服务](https://gitee.com/openharmony/app_samples/tree/master/Telephony/Message) | 本示例展示了电话服务中发送短信的功能。 | eTS | -| 电话服务 | [网络搜索](https://gitee.com/openharmony/app_samples/tree/master/Telephony/RadioTech) | 本示例通过eTS来展示电话服务中网络搜索功能,包含无线接入技术、网络状态、选网模式、ISO国家码、信号强度信息列表及Radio是否打开。 | eTS | -| 设备管理 | [系统电源管理](https://gitee.com/openharmony/app_samples/tree/master/common/PowerManager) | 本示例展示了关机、重启以及检测亮灭屏状态的功能。 | eTS | -| 设备管理 | [传感器](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor) | 本示例采用了传感器接口中的方向传感器,实现了指南针的效果。 | eTS | -| 设备管理 | [设备管理](https://gitee.com/openharmony/app_samples/tree/master/device/DeviceManager) | 本示例展示了在eTS中DeviceManager接口的使用,包括获取授信设备列表,设备扫描,设备认证,设备状态订阅。 | eTS | -| 帐号管理 | [应用帐号管理](https://gitee.com/openharmony/app_samples/tree/master/Account/AppAccountManager) | 本示例选择应用进行注册/登录,并设置帐号相关信息,简要说明应用帐号管理相关功能。 | eTS | -| ArkUI | [web](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Web) | 本示例主要展示了web的功能页面。 | eTS | -| ArkUI | [拖拽](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag) | 本示例主要展示了拖拽操作的功能。 | eTS | -| ArkUI | [动画](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation) | 本示例通过点击按钮触发动画,向用户展示属性动画与显示动画的效果。 | eTS | -| 数据管理 | [分布式数据库-结果集和谓词查询](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery) | 本示例展示了分布式数据管理中,如何通过构建query对象, 查询kvstore中的数据,获取结果集。 | eTS | -| 数据管理 | [关系型数据库](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | 本示例展示了在eTS中关系型数据库的使用,包括增、删、改、查等操作。 | eTS | -| 事件 | [后台代理提醒](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) | 本示例通过模拟闹钟来展示后台代理提醒的使用方法。 | eTS | -| 事件 | [事件通知](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter) | 本示例主要展示进程内事件通知,用户通过选择对应商品并提交订单后在订单列表显示所选商品。 | eTS | -| 通信与连接 | [RPC通信](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC) | 本示例展示了同一设备中前后台的数据交互,用户前台选择相应的商品与数目,后台计算出结果,回传给前台展示。 | eTS | -| 通信与连接 | [WLAN](https://gitee.com/openharmony/app_samples/tree/master/Communication/Wlan) | 本示例展示了在eTS中WLAN的基本使用,包括禁用和启用WLAN、WLAN扫描和获取扫描结果、WLAN状态监听、WiFi连接状态监听、获取IP信息、获取国家码、判断设备是否支持WLAN相关特性。 | eTS | -| 媒体服务 | [录音机Demo](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) | 本示例展示媒体服务中音频录制和播放功能的使用。 | eTS | -| 媒体服务 | [多媒体Demo](https://gitee.com/openharmony/app_samples/tree/master/media/MultiMedia) | 本示例展示如何在eTS中调用相机拍照,以及如何使用媒体库接口进行媒体文件的增、删、改、查操作。 | eTS | +| 电话服务 | [短信服务](https://gitee.com/openharmony/app_samples/tree/master/Telephony/Message) | 本示例展示了电话服务中发送短信的功能。 | ArkTS | +| 电话服务 | [网络搜索](https://gitee.com/openharmony/app_samples/tree/master/Telephony/RadioTech) | 本示例通过ArkTS来展示电话服务中网络搜索功能,包含无线接入技术、网络状态、选网模式、ISO国家码、信号强度信息列表及Radio是否打开。 | ArkTS | +| 设备管理 | [系统电源管理](https://gitee.com/openharmony/app_samples/tree/master/common/PowerManager) | 本示例展示了关机、重启以及检测亮灭屏状态的功能。 | ArkTS | +| 设备管理 | [传感器](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor) | 本示例采用了传感器接口中的方向传感器,实现了指南针的效果。 | ArkTS | +| 设备管理 | [设备管理](https://gitee.com/openharmony/app_samples/tree/master/device/DeviceManager) | 本示例展示了在ArkTS中DeviceManager接口的使用,包括获取授信设备列表,设备扫描,设备认证,设备状态订阅。 | ArkTS | +| 帐号管理 | [应用帐号管理](https://gitee.com/openharmony/app_samples/tree/master/Account/AppAccountManager) | 本示例选择应用进行注册/登录,并设置帐号相关信息,简要说明应用帐号管理相关功能。 | ArkTS | +| ArkUI | [web](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Web) | 本示例主要展示了web的功能页面。 | ArkTS | +| ArkUI | [拖拽](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag) | 本示例主要展示了拖拽操作的功能。 | ArkTS | +| ArkUI | [动画](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation) | 本示例通过点击按钮触发动画,向用户展示属性动画与显示动画的效果。 | ArkTS | +| 数据管理 | [分布式数据库-结果集和谓词查询](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery) | 本示例展示了分布式数据管理中,如何通过构建query对象, 查询kvstore中的数据,获取结果集。 | ArkTS | +| 数据管理 | [关系型数据库](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | 本示例展示了在ArkTS中关系型数据库的使用,包括增、删、改、查等操作。 | ArkTS | +| 事件 | [后台代理提醒](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) | 本示例通过模拟闹钟来展示后台代理提醒的使用方法。 | ArkTS | +| 事件 | [事件通知](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter) | 本示例主要展示进程内事件通知,用户通过选择对应商品并提交订单后在订单列表显示所选商品。 | ArkTS | +| 通信与连接 | [RPC通信](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC) | 本示例展示了同一设备中前后台的数据交互,用户前台选择相应的商品与数目,后台计算出结果,回传给前台展示。 | ArkTS | +| 通信与连接 | [WLAN](https://gitee.com/openharmony/app_samples/tree/master/Communication/Wlan) | 本示例展示了在ArkTS中WLAN的基本使用,包括禁用和启用WLAN、WLAN扫描和获取扫描结果、WLAN状态监听、WiFi连接状态监听、获取IP信息、获取国家码、判断设备是否支持WLAN相关特性。 | ArkTS | +| 媒体服务 | [录音机Demo](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) | 本示例展示媒体服务中音频录制和播放功能的使用。 | ArkTS | +| 媒体服务 | [多媒体Demo](https://gitee.com/openharmony/app_samples/tree/master/media/MultiMedia) | 本示例展示如何在ArkTS中调用相机拍照,以及如何使用媒体库接口进行媒体文件的增、删、改、查操作。 | ArkTS | 请访问[Samples](https://gitee.com/openharmony/app_samples)仓了解更多信息。 @@ -232,13 +232,13 @@ _[API差异报告](api-diff/v3.1-Release/Readme-CN.md)_ | 项目名称 | 简介 | 开发语言 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -------- | | [分布式鉴权](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH) | 使用JS开发一个分布式游戏鉴权应用,介绍分布式拉起,设备管理器对象、显示设备属性接口能力的使用。 | JS | -| [分布式游戏手柄](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) | 使用eTS开发一个手柄游戏,利用分布式能力,一个开发板作为手柄,一个开发板作为游戏端。 | eTS | -| [分布式亲子教育](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) | 使用RPC实现跨设备通讯,以及CommonEvent实现ServiceAbility与FA之间通讯,完成分布式拼图游戏。 | eTS | -| [分布式遥控器](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) | 使用eTS开发一个分布式遥控器,利用分布式能力,一个开发板作为TV端,一个开发板作为遥控器端。 | eTS | -| [音频录制应用](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) | 使用媒体组件AudioRecorder收录当前音频、使用AudioPlayer播放录音的方法。 | eTS | -| [备忘录](https://gitee.com/openharmony/codelabs/tree/master/Data/NotePad_OH_ETS) | 使用eTS开发一个简易备忘录,支持新建、删除和收藏笔记功能,轻量级数据库持久化存储数据。 | eTS | -| [分布式邮件编辑](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) | 使用eTS开发分布式邮件,利用分布式的能力,在相同局域网及帐号下,拉起另一个设备,实现邮件在不同设备下的编辑流转。 | eTS | -| [三方库](https://gitee.com/openharmony/codelabs/tree/master/ThirdPartyComponents/VCardDemo) | 介绍openHarmony中三方库vcard库使用:一款写入和读取特定格式的联系人数据(后缀名为vcard的文件)的OpenHarmony组件。 | eTS | +| [分布式游戏手柄](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) | 使用ArkTS开发一个手柄游戏,利用分布式能力,一个开发板作为手柄,一个开发板作为游戏端。 | ArkTS | +| [分布式亲子教育](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) | 使用RPC实现跨设备通讯,以及CommonEvent实现ServiceAbility与FA之间通讯,完成分布式拼图游戏。 | ArkTS | +| [分布式遥控器](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) | 使用ArkTS开发一个分布式遥控器,利用分布式能力,一个开发板作为TV端,一个开发板作为遥控器端。 | ArkTS | +| [音频录制应用](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) | 使用媒体组件AudioRecorder收录当前音频、使用AudioPlayer播放录音的方法。 | ArkTS | +| [备忘录](https://gitee.com/openharmony/codelabs/tree/master/Data/NotePad_OH_ETS) | 使用ArkTS开发一个简易备忘录,支持新建、删除和收藏笔记功能,轻量级数据库持久化存储数据。 | ArkTS | +| [分布式邮件编辑](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) | 使用ArkTS开发分布式邮件,利用分布式的能力,在相同局域网及帐号下,拉起另一个设备,实现邮件在不同设备下的编辑流转。 | ArkTS | +| [三方库](https://gitee.com/openharmony/codelabs/tree/master/ThirdPartyComponents/VCardDemo) | 介绍openHarmony中三方库vcard库使用:一款写入和读取特定格式的联系人数据(后缀名为vcard的文件)的OpenHarmony组件。 | ArkTS | ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md index 695fb424302d0db3cae0c99475b6f71a7ce0db9b..f8103db7b38002e72de1771bb972a85a130bf18d 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md @@ -142,7 +142,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 @@ -151,7 +151,7 @@ repo forall -c 'git lfs pull' | ISSUE单 | 问题描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | | [I4UUFR](https://gitee.com/openharmony/third_party_e2fsprogs/issues/I4UUFR) | 本地编译构建Hi3516开发板版本镜像 | -| [I4WDD3](https://gitee.com/openharmony/multimedia_camera_standard/issues/I4WDD3) | 【RK3568】录像后无法查看视频 | +| I4WDD3 | 【RK3568】录像后无法查看视频 | | [I50EBB](https://gitee.com/openharmony/docs/issues/I50EBB) | 【Hi3516烧录】标准系统Hi3516镜像无法通过IDE烧录 | diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.2-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.2-release.md index 48e9fb91a17a869302a1004405e54209a9742a1c..10544eea754b7b6a6e54d64f2eb9d0b6cec39015 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.2-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.2-release.md @@ -117,7 +117,7 @@ API变更 ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md index 5eddc0ec5a2560960e797ce5f0abced24a440bf1..4bbe03317dd3da8339cc1102f7cd86f310c7b6ca 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md @@ -105,7 +105,7 @@ API变更 ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ## 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md index 19a944c269bda58dbd0495fe7c92d0cb4812d301..f56f8e1469f74728a1ce6a9a62e85d35879ac20e 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md @@ -104,7 +104,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md index 9bafd21ac6fb7ae6c2c408565476ece681a45c4d..a0a014e45f22a93fa462bc70512c13551af4d64b 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.5-release.md @@ -104,7 +104,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.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 index da1e6c71bbac5c508443b019c81efa6a8048c240..70dbf6794d2b9b5661afeae9d07e64c1e4d95c9b 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.6-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.6-release.md @@ -104,7 +104,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.7-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.7-release.md index fc672fff5a3c3ac050d73a70ede5997cd6b86edd..fbab3c400837ea3592304bdd1e6ff8828eb83ff0 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.7-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.7-release.md @@ -104,7 +104,7 @@ repo forall -c 'git lfs pull' ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### 修复缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md index 4f329dcae95cf542c92673b43dae00eb75c04274..10ad73f5301f0372aa240040a84d2b058c273cd6 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md @@ -177,7 +177,7 @@ _[API差异报告](api-diff/v3.2-beta1/Readme-CN.md)_ ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples @@ -186,14 +186,12 @@ _[API差异报告](api-diff/v3.2-beta1/Readme-CN.md)_ | 子系统 | 名称 | 简介 | 开发语言 | | -------- | -------- | -------- | -------- | -| ArkUI | [MouseEvent](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) | 本示例模拟了简单的扫雷游戏调用了鼠标事件的相关接口 | ArkTS | | ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator) | 本示例模拟倒计时场景,展示振动接口的使用方法。 | ArkTS | | DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DFX/FaultLogger) | 本示例展示了在ArkTS中如何获取应用故障相关信息。 | ArkTS | -| ArkUI | [Gallery](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) | 本Demo通过不同示例向用户介绍通用事件、通用属性、手势处理等不同组件的功能。 | ArkTS | -| 图形 | [JsWebGL](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL) | 本示例调用GPU资源绘制了五角星和矩形,展示WebGL相关接口的使用方法。 | JS | +| ArkUI | [ComponentCollection](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/ArkTsComponentClollection/ComponentCollection) | 本示例为ArkUI中组件、通用、动画、全局方法的集合 | ArkTS | | ArkUI | [ArkTSClock](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock) | 本示例使用ArkTS UI能力实现一个简单的时钟应用。 | ArkTS | | 网络管理 | [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) | 本示例仿postman输入API接口地址,获取相应数据,介绍数据请求接口的用法。 | ArkTS | -| 网络管理 | [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) | 本示例主要演示了Socket在网络通信方面的应用,展示了Socket在两端设备的连接验证、聊天通信方面的应用。 | ArkTS | +| 网络管理 | [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Socket) | 本示例主要演示了Socket在网络通信方面的应用,展示了Socket在两端设备的连接验证、聊天通信方面的应用。 | ArkTS | | 分布式数据管理 | [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) | 本示例展示了在ArkTS中分布式关系型数据库的使用,在增、删、改、查的基本操作外,还包括分布式数据库的数据同步能力。 | ArkTS | | 元能力 | [WorkScheduler](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) | 本示例模拟下载更新包 、保存更新包、发送通知 、安装更新包实现升级,将下载任务通过后台任务管理进行处理,实现退出应用后任务仍能够执行,直至任务结束。 | ArkTS | | 元能力 | [AbilityStartMode](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/AbilityStartMode) | 本示例展示了在一个Stage模型中,实现standard、singleton、specified多种模式场景。 | ArkTS | @@ -205,7 +203,6 @@ _[API差异报告](api-diff/v3.2-beta1/Readme-CN.md)_ | ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Game2048) | 2048是一款比较流行的数字游戏,此游戏demo是grid组件基础上进行开发完成的。 | ArkTS | | 一多设置典型页面 | [Settings](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Settings) | 本示例展示了设置应用的典型页面,其在小窗口和大窗口有不同的显示效果,体现一次开发、多端部署的能力。 | ArkTS | | 分布式数据管理 | [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DataManagement/Preferences) | 本示例主要展示了首选项在主题切换方面的功能。 | ArkTS | -| ArkUI | [NativeAPI](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) | 本示例展示了在ArkTS中如何调用C++的接口以及C++如何回调JS,完成了一个简单的五子棋游戏,在native层完成计算逻辑,ArkTS完成界面绘制和刷新。 | ArkTS/C++ | | 全球化 | [International](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International) | 本示例展示了i18n,intl,resourceManager在ArkTS中的使用,使用相关api实现系统语言和地区设置、时间和时区设置,展示了区域格式化示例。 | ArkTS | 请访问[Samples](https://gitee.com/openharmony/applications_app_samples)仓了解更多信息。 diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md index 0499b185f8884b8ab15519c383f579609da1c8b1..93ed6c57df706d1f03612bfba6e3403a5a6efd93 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md @@ -162,7 +162,7 @@ ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md index baf256f286cf0bae5da653354f11dc60f73c18d5..1cf5cace6f9b2aa29a6012aa382299608713cb63 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md @@ -181,7 +181,7 @@ API变更请参考: ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples @@ -193,7 +193,7 @@ API变更请参考: | ArkUI | [HealthyDiet:健康饮食](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/HealthyDiet) | 这是一个记录饮食和查看食物信息的应用,主要用于管理饮食健康。可以添加饮食信息,包括食物的种类、重量以及用餐时间,如早餐、 午餐、晚餐和夜宵,并能统计得到相应用餐时间的总热量值、总蛋白质、总脂肪和总碳水值,并且用柱状图的形式展示出来。 | ArkTS | | ArkUI | [MusicAlbum:一多音乐专辑主页](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/MusicAlbum) | 本示例展示了音乐专辑主页,使用一次开发多端部署中介绍的自适应布局能力和响应式布局能力进行多设备(或多窗口尺寸)适配,保证应用在不同设备或不同窗口尺寸下可以正常显示。 | ArkTS | | 元能力、文件管理 | [CustomShare:自定义分享](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/CustomShare) | 分享的主要工作是实现:发送方将文本,链接,图片文件三种类型分享给三方应用,同时能够在三方应用中分别呈现出来。 | ArkTS | -| 元能力 | [GalleryForm:图库卡片](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm) | 本示例是模拟图库卡片,实现对图库中的照片在卡片中显示,定时刷新卡片内容等功能。 | ArkTS | +| 元能力 | [FormExtAbility:Stage模型卡片](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/FormExtAbility) | 本示例展示了Stage模型卡片提供方的创建与使用。 | ArkTS | | ArkUI | [AppMarket:一多应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AppMarket) | 本示例展示了应用市场首页,页面中包括Tab栏、运营横幅、精品应用、精品游戏等。 | ArkTS | | ArkUI | [Weather:一多天气](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather) | 本示例展示一个天气应用界面,包括首页、城市管理、添加城市、更新时间弹窗,体现一次开发,多端部署的能力。 | ArkTS | | 媒体 | [MediaCollections:媒体管理合集](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) | 本示例展示了网络流播放能力、音视频播控能力、音量调节能力等。 | ArkTS | diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta4.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta4.md index f8c47fbcd6b580d6062ee46fa7582fdd15f3f923..51a4584ae45e3d58d26c28718f70744c1586224d 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta4.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta4.md @@ -193,7 +193,7 @@ API变更请参考: ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md index 18f965c713a45ffd4c6cb3b4adae4409e2947995..e156dad5e3cdca1dd967da9fbed7127f27d05e71 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md @@ -170,7 +170,7 @@ API变更清单请参考:[API差异报告](api-change/v3.2-beta5/Readme.md) ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples @@ -181,7 +181,7 @@ API变更清单请参考:[API差异报告](api-change/v3.2-beta5/Readme.md) | -------- | -------- | -------- | -------- | | 媒体子系统 | [二维码扫描](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/media/Scan) | 本示例展示二维码扫描,从文件中选择二维码图片进行解析和读取,识别二维码信息。 | ArkTs | | ArkUI | [一多应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/MultiDeviceAppDev/AppMarket) | 本示例展示了应用市场首页,其在小窗口和大窗口有不同的显示效果,体现一次开发、多端部署的能力。 | ArkTs | -| 文件管理 | [文件管理](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/FileManager/FileIo) | 本示例主要展示了文件管理相关的功能,使用[mediaLibrary](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md)、[userFileManager](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md)、[fileio](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-fileio.md)等接口,实现了媒体库文件、应用沙箱内文件的添加和访问等功能。 | ArkTs | +| 文件管理 | [文件管理](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/FileManager/FileIo) | 本示例主要展示了文件管理相关的功能,使用[mediaLibrary](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md)、[userFileManager](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md)、[fileio](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-fileio.md)等接口,实现了媒体库文件、应用沙箱内文件的添加和访问等功能。 | ArkTs | | 元能力 | [图库卡片](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/ability/GalleryForm) | 本示例是模拟图库卡片,实现对图库中的照片在卡片中显示,定时刷新卡片内容等功能。 | ArkTs | diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-release.md b/zh-cn/release-notes/OpenHarmony-v3.2-release.md index 435b7425723269f4a3673397a9035b03f34b57b8..0f6c9b02850e52100dc6243b10ec4288ebfa4be9 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-release.md @@ -21,7 +21,6 @@ OpenHarmony 3.2版本完整里程碑如下图所示,阅读本文档了解更 - 增加基础的ArkTS卡片开发能力:支持卡片交互、能动态更新内容;统一卡片和页面的开发范式,页面的布局可以直接复用到卡片布局中,提升卡片开发体验和开发效率。 - 系统默认支持纯文本、纯图片复制、粘贴、拖拽,无需开发者处理复制、粘贴、拖拽事件。 - 支持多级菜单和分组菜单。 -- 支持切换深色模式/浅色模式,仅系统应用支持。 **UI界面开发支持一次开发适配多屏幕规格** @@ -596,7 +595,7 @@ API变更请参考: ### 芯片及开发板适配 -芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard_cn.md)信息。 ### Samples diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index 1bfd660ebdc2263495d3f6d2d57aff7aa057a16f..283ec3179453f7d8f542c706628f9d02ecd9cea8 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -8,6 +8,7 @@ - [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) - [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) - [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) +- [OpenHarmony v3.1.7 Release (2023-03-22)](OpenHarmony-v3.1.7-release.md) - [OpenHarmony v3.1.6 Release (2023-01-30)](OpenHarmony-v3.1.6-release.md) - [OpenHarmony v3.1.5 Release (2022-12-30)](OpenHarmony-v3.1.5-release.md) - [OpenHarmony v3.1.4 Release (2022-11-02)](OpenHarmony-v3.1.4-release.md) diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-arkui.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-arkui.md index 13fa31a833204a222885c0d68481903bae13e33d..52c24e47eaedad02b86e5e90ef3e9df8acb3b28c 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-arkui.md @@ -116,24 +116,24 @@ 通过构造函数方法初始化成员变量,需要遵循如下规则: | **从父组件中的变量(右)到子组件中的变量(下)** | **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** | -|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------| -| **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 | -| **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | -| **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | -| **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | -| **@Provide** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | -| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | -| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | +| -------------------------- | ----------- | ---------- | --------- | --------- | ------------ | ------------ | --------------- | +| **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 | +| **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | +| **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **@Provide** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | +| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | | **从父组件中的变量(右)到子组件中的变量(下)** | **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** | -|------------------|------------------|------------------|-----------------------|------------------------| -| **regular** | 支持 | 不支持 | 不支持 | 不支持 | -| **@State** | 支持 | 支持 | 支持 | 支持 | -| **@Link** | 支持(1) | 支持(1) | 支持(1) | 支持(1) | -| **@Prop** | 支持 | 支持 | 支持 | 支持 | -| **@Provide** | 支持 | 支持 | 支持 | 支持 | -| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | -| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | +| -------------------------- | ---------------- | ---------------- | --------------------- | --------------------- | +| **regular** | 支持 | 不支持 | 不支持 | 不支持 | +| **@State** | 支持 | 支持 | 支持 | 支持 | +| **@Link** | 支持(1) | 支持(1) | 支持(1) | 支持(1) | +| **@Prop** | 支持 | 支持 | 支持 | 支持 | +| **@Provide** | 支持 | 支持 | 支持 | 支持 | +| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | +| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | > **说明** > @@ -211,5 +211,5 @@ **适配指导** 1. 构造子组件时,不对子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量进行。 -如果需要在父组件中修改子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量,则使用LocalStorage提供的API接口方法(比如set方法)赋值。 -2. @ObjectLink的使用指导请参考文档[@ObjectLink使用指导](../../../application-dev/quick-start/arkts-state-mgmt-page-level.md)。 + 如果需要在父组件中修改子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量,则使用LocalStorage提供的API接口方法(比如set方法)赋值。 +2. @ObjectLink的使用指导请参考文档[@ObjectLink使用指导](../../../application-dev/quick-start/arkts-observed-and-objectlink.md)。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md index 6d04fd1b5c9263d0e91ba8d83ccc3bc536acf640..50cb351de5032d8c5023804fb79314fc030f8157 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md @@ -143,3 +143,46 @@ import volumeManager from '@ohos.volumeManager'; ```js import volumeManager from '@ohos.file.volumeManager'; ``` + +## cl.filemanagement.8 fileio相关接口异常处理方式变更 + +file_api部件fileio接口返回值不包含错误码error.code,现进行错误码整改,废弃原有相关接口,新增相关接口。 + +**变更影响** + +基于此前版本开发的应用,需注意废弃接口的迭代更新。新接口在接口规格上进行了微调,需注意新接口使用方法。 + +**关键接口/组件变更** + +为适配统一的API异常处理方式,对fileio相关接口进行废弃,并新增对应接口,原接口位于@ohos.fileio,新接口位于@ohos.file.fs。新增接口支持统一的错误码异常处理规范,功能上与原接口保持一致,参数上有微调,以下为规格调整的接口列表。 + +| 模块名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------------------------------------------------ | -------- | +| @ohos.fileio | **function** access(path: string, mode?: number, callback?: AsyncCallback): void \| Promise | 废弃 | +| @ohos.fileio | **function** accessSync(path: string, mode?: number): void | 废弃 | +| @ohos.file.fs | **function** access(path: string, callback?: AsyncCallback): void \| Promise | 新增 | +| @ohos.file.fs | **function** accessSync(path: string): boolean | 新增 | +| @ohos.fileio | **function** close(fd: number, callback?: AsyncCallback): void \| Promise | 废弃 | +| @ohos.fileio | **function** closeSync(fd: number): void | 废弃 | +| @ohos.file.fs | **function** close(file: File \| number, callback?: AsyncCallback): void \| Promise | 新增 | +| @ohos.file.fs | **function** closeSync(file: File \| number): void | 新增 | +| @ohos.fileio | **function** mkdir(path: string, mode?: number, callback?: AsyncCallback): void \| Promise | 废弃 | +| @ohos.fileio | **function** mkdirSync(path: string, mode?: number): void | 废弃 | +| @ohos.file.fs | **function** mkdir(path: string, callback?: AsyncCallback): void \| Promise | 新增 | +| @ohos.file.fs | **function** mkdirSync(path: string): void | 新增 | +| @ohos.fileio | **function** readText(filePath: string, options?: { position?: number; length?: number; encoding?: string; }, callback?: AsyncCallback): void \| Promise | 废弃 | +| @ohos.fileio | **function** readTextSync(filePath: string, options?: { position?: number; length?: number; encoding?: string; }): string | 废弃 | +| @ohos.file.fs | **function** readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }, callback?: AsyncCallback): void \| Promise | 新增 | +| @ohos.file.fs | **function** readTextSync(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): string | 新增 | +| @ohos.fileio | **function** Stream.read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }, callback?: AsyncCallback): void \| Promise | 废弃 | +| @ohos.fileio | **function** Stream.readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }): number | 废弃 | +| @ohos.file.fs | **function** Stream.read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback?: AsyncCallback): void \| Promise | 新增 | +| @ohos.file.fs | **function** Stream.readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number | 新增 | +| @ohos.fileio | **function** Stream.write(buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }, callback?: AsyncCallback): void \| Promise | 废弃 | +| @ohos.fileio | **function** Stream.writeSync(buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): number | 废弃 | +| @ohos.file.fs | **function** Stream.write(buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; encoding?: string; }, callback?: AsyncCallback): void \| Promise | 新增 | +| @ohos.file.fs | **function** Stream.writeSync(buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; encoding?: string; }): number | 新增 | + +**适配指导** + +@ohos.file.fs新增统一的API异常处理方式,可参考错误码[适配指导](../../../application-dev/reference/errorcodes/errorcode-filemanagement.md#错误码适配指导)。 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 index a35a20b092e9c8095deaaf85fb73ec575fcf936a..15accb04095bb7f3fb478b01b702d4e58c6e46ad 100644 --- 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 @@ -232,8 +232,14 @@ module.json配置文件中的ability的[name](../../../application-dev/quick-sta **适配指导**
删除module.json中[distroFilter](../../../application-dev/quick-start/module-configuration-file.md)标签,使用distributionFilter替代 -## cl.bundlemanager.20 module.json配置文件中launchTypede标签standard模式修改为multiton +## cl.bundlemanager.20 module.json配置文件中launchType的标签standard模式修改为multiton 删除module.json中[launchType](../../../application-dev/quick-start/module-configuration-file.md)标签的standard模式修改为multiton **适配指导**
-删除module.json中[launchType](../../../application-dev/quick-start/module-configuration-file.md)标签的standard模式,使用multiton替代 \ No newline at end of file +删除module.json中[launchType](../../../application-dev/quick-start/module-configuration-file.md)标签的standard模式,使用multiton替代 + +## cl.bundlemanager.21 module.json配置文件中abilities的标签visible修改为exported +module.json中[abilities](../../../application-dev/quick-start/module-configuration-file.md)的标签visible修改为exported,表示当前ability是否支持导出,被其他的ability使用。 + +**适配指导**
+删除module.json中[abilities](../../../application-dev/quick-start/module-configuration-file.md)的visible标签,使用exported标签替代 \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-account_os_account.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-account_os_account.md index 845e56f08f38e4cdf38b9755442f88e870f42cc3..7aa6bffc9cf3c8423ba8b552ae9046fbd4aa7494 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-account_os_account.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-account_os_account.md @@ -6,7 +6,7 @@ - 新增统一的错误码定义: - [帐号公共错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-account.md) - - [应用帐号错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-app-account.md) + - [应用帐号错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-account.md) - 按以下方式返回错误码: - 异步接口:错误信息通过AsyncCallback或Promise的error对象返回。其中,参数类型和数量错误信息,通过抛出异常的方式返回。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md index ceea34cf904a6158f5aa98ac8b76ef44ee80f6d9..277221beff721cadf9e7e02d223a65d6afca87b0 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md @@ -21,7 +21,7 @@ | @ohos.bundle.innerBundleManager.d.ts | [@ohos.bundle.launcherBundleManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.launcherBundleManager.d.ts) | | @ohos.bundle.innerBundleManager.d.ts | [@ohos.bundle.bundleMonitor.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.bundleMonitor.d.ts) | | @ohos.bundle.defaultAppManager.d.ts | [@ohos.bundle.defaultAppManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.defaultAppManager.d.ts) | -| @ohos.distributedBundle.d.ts | [@ohos.bundle.distributedBundle.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.distributedBundle.d.ts) | +| @ohos.distributedBundle.d.ts | [@ohos.bundle.distributedBundleManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.distributedBundleManager.d.ts) | | 无 | [@ohos.bundle.appControl.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.appControl.d.ts) | | @system.package.d.ts | 无 | @@ -65,23 +65,22 @@ import distributedBundle form '@ohos.bundle.distributedBundle' 新增结构体对原有的API8及之前的结构体进行梳理,将原有API8及之前的结构体全部废弃,新增新的API9结构体,变更前后的对比如下表所示,部分结构体进行了合并,例如moduleInfo.d.ts替换为hapModuleInfo.d.ts,customizeData.d.ts替换为metadata.d.ts。结构体功能上与原结构体保持一致。部分功能有变更或者新增的结构体属性会单独列出。 | 原结构体(废弃) | 新结构体(新增) | | ------ | ------ | -| bundle/abilityInfo.d.ts | [bundleManager/abilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/abilityInfo.d.ts) | -| bundle/applicationInfo.d.ts | [bundleManager/applicationInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/applicationInfo.d.ts) | -| bundle/bundleInfo.d.ts | [bundleManager/bundleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/bundleInfo.d.ts) | -| bundle/bundleInstaller.d.ts | [@ohos.bundle.installer.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.installer.d.ts) | -| bundle/bundleStatusCallback.d.ts | [@ohos.bundle.bundleMonitor.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.bundleMonitor.d.ts) | -| bundle/customizeData.d.ts | [bundleManager/metadata.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/metadata.d.ts) | -| bundle/dispatchInfo.d.ts | [bundleManager/dispatchInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/dispatchInfo.d.ts) | -| bundle/elementName.d.ts | [bundleManager/elementName.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/elementName.d.ts) | -| bundle/extensionAbilityInfo.d.ts | [bundleManager/extensionAbilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/extensionAbilityInfo.d.ts) | -| bundle/hapModuleInfo.d.ts | [bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts) | -| bundle/launcherAbilityInfo.d.ts | [bundleManager/launcherAbilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/launcherAbilityInfo.d.ts) | -| bundle/metadata.d.ts | [bundleManager/metadata.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/metadata.d.ts) | -| bundle/moduleInfo.d.ts | [bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts) | -| bundle/packInfo.d.ts | [bundleManager/packInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/packInfo.d.ts) | -| bundle/PermissionDef.d.ts | [bundleManager/permissionDef.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/permissionDef.d.ts) | -| bundle/remoteAbilityInfo.d.ts | [bundleManager/remoteAbilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/remoteAbilityInfo.d.ts) | -| bundle/shortcutInfo.d.ts | [bundleManager/shortcutInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/shortcutInfo.d.ts) | +| bundle/abilityInfo.d.ts | [bundleManager/abilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/AbilityInfo.d.ts) | +| bundle/applicationInfo.d.ts | [bundleManager/applicationInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ApplicationInfo.d.ts) | +| bundle/bundleInfo.d.ts | [bundleManager/bundleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/BundleInfo.d.ts) | +| bundle/bundleInstaller.d.ts | [@ohos.bundle.installer.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.installer.d.ts) | +| bundle/bundleStatusCallback.d.ts | [@ohos.bundle.bundleMonitor.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.bundleMonitor.d.ts) | +| bundle/customizeData.d.ts | [bundleManager/metadata.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/Metadata.d.ts) | +| bundle/dispatchInfo.d.ts | [bundleManager/dispatchInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/DispatchInfo.d.ts) | +| bundle/elementName.d.ts | [bundleManager/elementName.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ElementName.d.ts) | +| bundle/extensionAbilityInfo.d.ts | [bundleManager/extensionAbilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ExtensionAbilityInfo.d.ts) | +| bundle/hapModuleInfo.d.ts | [bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts) | +| bundle/launcherAbilityInfo.d.ts | [bundleManager/launcherAbilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/LauncherAbilityInfo.d.ts) | +| bundle/metadata.d.ts | [bundleManager/metadata.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/Metadata.d.ts) | +| bundle/moduleInfo.d.ts | [bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts) | +| bundle/PermissionDef.d.ts | [bundleManager/permissionDef.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/PermissionDef.d.ts) | +| bundle/remoteAbilityInfo.d.ts | [bundleManager/remoteAbilityInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/RemoteAbilityInfo.d.ts) | +| bundle/shortcutInfo.d.ts | [bundleManager/shortcutInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ShortcutInfo.d.ts) | **适配指导**
1. 使用原有结构体的代码需要修改为新结构体。 @@ -168,7 +167,7 @@ import appControl form '@ohos.bundle.appControl' ## cl.bundlemanager.4 BundleInfo结构体变更,包管理原有bundle/bundleInfo.d.ts字段全部废弃变更为bundleManager/bundleInfo.d.ts,涉及字段属性变化。 -包管理原有bundle/bundleInfo.d.ts字段全部废弃。由老的[bundle/bundleInfo.d.ts]((https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundle/bundleInfo.d.ts))变更为[bundleManager/bundleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/bundleInfo.d.ts),涉及字段属性变化。 +包管理原有bundle/bundleInfo.d.ts字段全部废弃。由老的[bundle/bundleInfo.d.ts]((https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundle/bundleInfo.d.ts))变更为[bundleManager/bundleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/BundleInfo.d.ts),涉及字段属性变化。 **变更影响**
@@ -176,7 +175,7 @@ import appControl form '@ohos.bundle.appControl' **关键的接口/组件变更**
-BundleInfo结构体发生变化的字段内容如下表所示。其余字段在bundle/bundleInfo.d.ts中废弃后,在新的[bundleManager/bundleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/bundleInfo.d.ts)中均有对应值。没有对应字段,则表明该字段已经在API9上废弃。 +BundleInfo结构体发生变化的字段内容如下表所示。其余字段在bundle/bundleInfo.d.ts中废弃后,在新的[bundleManager/bundleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/BundleInfo.d.ts)中均有对应值。没有对应字段,则表明该字段已经在API9上废弃。 | 已废弃 | API9新增或变更 | 类型 | | --- | --- | --- | @@ -217,7 +216,7 @@ ApplicationInfo结构体变更,包管理原有bundle/applicationInfo.d.ts字 对原有使用API version 9之前的应用无影响,使用API version 9的应用需要适配新模块和新接口。使用二级模块导出ApplicationInfo时,需要导入@ohos.bundle.bundleManager模块。 **关键的接口/组件变更**
-ApplicationInfo结构体发生变化的字段内容如下表所示。其余字段在bundle/applicationInfo.d.ts中废弃后,在新的[bundleManager/applicationInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/applicationInfo.d.ts)中均有对应值。没有对应字段,则表明该字段已经在API9上废弃。 +ApplicationInfo结构体发生变化的字段内容如下表所示。其余字段在bundle/applicationInfo.d.ts中废弃后,在新的[bundleManager/applicationInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ApplicationInfo.d.ts)中均有对应值。没有对应字段,则表明该字段已经在API9上废弃。 | 废弃 | API9新增或变更 | 类型 | | --- | --- | --- | @@ -240,7 +239,7 @@ ApplicationInfo结构体发生变化的字段内容如下表所示。其余字 ## cl.bundlemanager.6 HapModuleInfo结构体字段变更,包管理原有bundle/hapModuleInfo.d.ts 和 moduleInfo.d.ts字段全部废弃,变更为bundleManager/hapModuleInfo.d.ts,涉及字段属性变化。 -HapModuleInfo结构体字段变更,包管理原有bundle/hapModuleInfo.d.ts 和 moduleInfo.d.ts字段全部废弃,变更为[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts),涉及字段属性变化。 +HapModuleInfo结构体字段变更,包管理原有bundle/hapModuleInfo.d.ts 和 moduleInfo.d.ts字段全部废弃,变更为[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts),涉及字段属性变化。 **变更影响**
对原有使用API version 9之前的应用无影响,使用API version 9的应用需要适配新模块和新接口。使用二级模块导出HapModuleInfo时,需要导入@ohos.bundle.bundleManager模块。 @@ -263,8 +262,8 @@ HapModuleInfo结构体发生变化的字段内容如下表所示。其余字段 ## cl.bundlemanager.7 ModuleInfo结构体废弃,使用bundleManager/hapModuleInfo.d.ts中的HapModuleInfo代替。 -包管理原有bundle/hapModuleInfo.d.ts 和 moduleInfo.d.ts字段全部废弃,变更为[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts),涉及字段属性变化。 -ModuleInfo结构体废弃,使用[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts)中的HapModuleInfo代替。 +包管理原有bundle/hapModuleInfo.d.ts 和 moduleInfo.d.ts字段全部废弃,变更为[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts),涉及字段属性变化。 +ModuleInfo结构体废弃,使用[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/HapModuleInfo.d.ts)中的HapModuleInfo代替。 **变更影响**
对原有使用API version 9之前的应用无影响,使用API version 9的应用需要适配新模块和新接口。ModuleInfo被废弃,使用HapModuleInfo代替。 @@ -394,7 +393,7 @@ import defaultApp form '@ohos.bundle.defaultAppManager' ``` ## cl.bundlemanager.11 分布式包管理模块变更,原@ohos.distributedBundle.d.ts接口全部废弃,变更为@ohos.bundle.distributedBundle.d.ts,涉及接口变更。 -API异常错误整改,分布式包管理模块变更,原@ohos.distributedBundle.d.ts接口全部废弃,变更为[@ohos.bundle.distributedBundle.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.distributedBundle.d.ts)。涉及接口getRemoteAbilityInfos,变更为getRemoteAbilityInfo。相关结构体RemoteAbilityInfo的二级模块导出功能也需要导入新模块才可以继续使用。 +API异常错误整改,分布式包管理模块变更,原@ohos.distributedBundle.d.ts接口全部废弃,变更为[@ohos.bundle.distributedBundleManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.distributedBundleManager.d.ts)。涉及接口getRemoteAbilityInfos,变更为getRemoteAbilityInfo。相关结构体RemoteAbilityInfo的二级模块导出功能也需要导入新模块才可以继续使用。 **变更影响**
对API version 9之前的应用无影响。分布式模块和getRemoteAbilityInfos名称变更,会导致原有API version 9应用使用新的sdk编译失败。 @@ -437,7 +436,7 @@ import freeInstall from '@ohos.bundle.freeInstall' ## cl.bundlemanager.13 免安装相关结构体DisPatchInfo、AbilityFormInfo、ModuleDistroInfo和ModuleConfigInfo发生字段变更 免安装相关结构体DisPatchInfo、AbilityFormInfo、ModuleDistroInfo和ModuleConfigInfo发生字段变更: -1. DispatchInfo中字段dispatchAPI名称修改为[dispatchAPIVersion](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/dispatchInfo.d.ts),属性不变,为string。表示免安装接口的版本信息,含义不变。 +1. DispatchInfo中字段dispatchAPI名称修改为[dispatchAPIVersion](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/DispatchInfo.d.ts),属性不变,为string。表示免安装接口的版本信息,含义不变。 2. AbilityFormInfo结构体字段属性变更,原有字段supportDimensions属性由Array\修改为Array\; 3. AbilityFormInfo结构体字段属性变更,原有字段defaultDimension属性由number修改为string。 4. ModuleDistroInfo结构体废弃mainAbility字段,移至ModuleConfigInfo结构体中。 @@ -498,7 +497,7 @@ import freeInstall from '@ohos.bundle.freeInstall' import bundle form '@ohos.bundle.bundleManager' ``` ## cl.bundlemanager.15 包管理ShortcutInfo结构体字段变更 -包管理ShortcutInfo结构体字段变更,原有bundle/shortcutInfo.d.ts字段全部废弃,变更为[bundleManager/shortcutInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/shortcutInfo.d.ts)。ShortcutInfo和ShortWant结构体全部为systemapi。 +包管理ShortcutInfo结构体字段变更,原有bundle/shortcutInfo.d.ts字段全部废弃,变更为[bundleManager/shortcutInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/ShortcutInfo.d.ts)。ShortcutInfo和ShortWant结构体全部为systemapi。 **变更影响**
对API version 9之前的应用无影响。结构体名称字段属性变更,会导致原有API9应用使用新的sdk编译失败。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md index 639d94dadba885f48137602e7925977eb10a171c..a491f5b1cdd1578c3616e80733f3e84be5553c30 100755 --- a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md @@ -25,4 +25,4 @@ USB系统API运行时鉴权,异步接口以Promise reject形式抛出错误码 **适配指导** -请参考各接口的[API参考](../../../application-dev/reference/errorcodes/errorcode-universal.md) \ No newline at end of file +请参考各接口的[API文档](../../../application-dev/reference/apis/js-apis-usbManager.md) diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-arkui.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-arkui.md index 27ad666dc2f9091b7dcb93341c7e7a88d92b9dce..b183f8f79f680d28e87866fb8916c36e3f2115b2 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.2.3/changelogs-arkui.md @@ -116,24 +116,24 @@ 通过构造函数方法初始化成员变量,需要遵循如下规则: | **从父组件中的变量(右)到子组件中的变量(下)** | **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** | -|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------| -| **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 | -| **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | -| **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | -| **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | -| **@Provide** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | -| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | -| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | +| -------------------------- | ----------- | ---------- | --------- | --------- | ------------ | ------------ | --------------- | +| **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 | +| **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | +| **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **@Provide** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | +| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | +| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | | **从父组件中的变量(右)到子组件中的变量(下)** | **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** | -|------------------|------------------|------------------|-----------------------|------------------------| -| **regular** | 支持 | 不支持 | 不支持 | 不支持 | -| **@State** | 支持 | 支持 | 支持 | 支持 | -| **@Link** | 支持(1) | 支持(1) | 支持(1) | 支持(1) | -| **@Prop** | 支持 | 支持 | 支持 | 支持 | -| **@Provide** | 支持 | 支持 | 支持 | 支持 | -| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | -| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | +| -------------------------- | ---------------- | ---------------- | --------------------- | --------------------- | +| **regular** | 支持 | 不支持 | 不支持 | 不支持 | +| **@State** | 支持 | 支持 | 支持 | 支持 | +| **@Link** | 支持(1) | 支持(1) | 支持(1) | 支持(1) | +| **@Prop** | 支持 | 支持 | 支持 | 支持 | +| **@Provide** | 支持 | 支持 | 支持 | 支持 | +| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | +| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | > **说明** > @@ -211,8 +211,8 @@ **适配指导** 1. 构造子组件时,不对子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量进行。 -如果需要在父组件中修改子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量,则使用LocalStorage提供的API接口方法(比如set方法)赋值。 -2. @ObjectLink的使用指导请参考文档[@ObjectLink使用指导](../../../application-dev/quick-start/arkts-state-mgmt-page-level.md)。 + 如果需要在父组件中修改子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量,则使用LocalStorage提供的API接口方法(比如set方法)赋值。 +2. @ObjectLink的使用指导请参考文档[@ObjectLink使用指导](../../../application-dev/quick-start/arkts-observed-and-objectlink.md)。 ## cl.arkui.3 List组件和Scroll组件onScrollBegin事件变更 @@ -224,13 +224,13 @@ onScrollBegin事件不能再使用,需要使用onScrollFrameBegin事件。 **关键接口/组件变更** -| 旧事件定义 | 新事件定义 | -|------------------ | ------------------- | +| 旧事件定义 | 新事件定义 | +| ---------------------------------------- | ---------------------------------------- | | onScrollBegin(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | onScrollFrameBegin(event: (offset: number, state: ScrollState) => { offsetRemain: number }) | onScrollFrameBegin事件说明参考API接口文档: -- [Scroll组件事件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md#%E4%BA%8B%E4%BB%B6) -- [List组件事件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-container-list.md#%E4%BA%8B%E4%BB%B6) +- [Scroll组件事件](../../../application-dev/reference/arkui-ts/ts-container-scroll.md#事件) +- [List组件事件](../../../application-dev/reference/arkui-ts/ts-container-list.md#事件) **适配指导** diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.6.1/changelogs-usb.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.6.1/changelogs-usb.md index 9eda299dc1cfb943f70ee828580107c78b52aa2b..3c0d57d8b3cd957505d66711214181788a6e22c0 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.6.1/changelogs-usb.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.6.1/changelogs-usb.md @@ -20,4 +20,4 @@ **适配指导** -请参考各接口的[API参考](../../../application-dev/reference/errorcodes/errorcode-universal.md) \ No newline at end of file +请参考各接口的[API文档](../../../application-dev/reference/apis/js-apis-usbManager.md) diff --git a/zh-cn/release-notes/changelogs/v3.2-beta2/application-sandbox-adaptation-guide.md b/zh-cn/release-notes/changelogs/v3.2-beta2/application-sandbox-adaptation-guide.md index 7489b54814dc46cb771abd0693a804397b397c86..f690a09096af95d4b9cc8982c21e81e1fc321a2f 100644 --- a/zh-cn/release-notes/changelogs/v3.2-beta2/application-sandbox-adaptation-guide.md +++ b/zh-cn/release-notes/changelogs/v3.2-beta2/application-sandbox-adaptation-guide.md @@ -15,8 +15,6 @@ 1. 定位出app异常的问题点之后,识别该问题是否是app源代码访问路径出错导致的,是否是访问有效文件可以通过下一章节的[沙箱文件访问规格清单](#沙箱文件访问规格清单)自查。 2. 如果是app源码访问无效路径,则可以通过调整访问路径的策略,将原来访问/data目录从绝对路径访问方式调整为使用context接口进行访问,具体请见context接口使用说明: https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/application-models/application-context-stage.md - https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-ability-context.md - https://gitee.com/OpenHarmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md 3. 如果是app调用三方模块,异常调用栈出现在三方模块中,而app源码没有使用绝对路径去访问文件,则适配过程如下: - 通知三方模块,让其访问文件路径通过context接口进行访问而非使用绝对路径的方式。 - 如果三方模块是个公共模块,除了给appspawn孵化的进程使用之外还给native进程使用,则可以将三方模块抽象成一个服务,应用通过ipc的方式去访问服务。