diff --git a/CODEOWNERS b/CODEOWNERS index b795faf3a92d05a3975f5150e8f0f7789560b04f..9a1d61d16ef420d826e30e51578f82be8db8db2f 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -132,7 +132,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen -zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @@ -244,7 +244,7 @@ zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/file-management/ @zengyawen zh-cn/application-dev/application-test/ @ningningW -zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen @@ -278,7 +278,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility. zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids -zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 @@ -331,7 +331,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 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 @@ -476,8 +476,8 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone -zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 @@ -537,10 +537,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen +zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 8484845fb47d82c6de79664c00d0d1c234b0e167..a627e1116a792c5d4fc885ae01aa6ccb172b7b1d 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -65,12 +65,13 @@ - [Internationalization](internationalization/Readme-EN.md) - [Application Test](application-test/Readme-EN.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - - [Using Native APIs in Application Projects](napi/Readme-EN.md) + - [Native APIs](napi/Readme-EN.md) - Tools - - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) + - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) + - [Debugging Tools](tools/Readme-EN.md) - Hands-On Tutorials - - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - - [Codelabs](https://gitee.com/openharmony/codelabs) + - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) + - [Codelabs](https://gitee.com/openharmony/codelabs) - API References - [SystemCapability](reference/syscap.md) - [SystemCapability List](reference/syscap-list.md) diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md index ab116c430cb7b248b947ccbee46cf5ac932f9fc9..f163b035c7b759fab03ee3fcd455e3dcb77b5515 100644 --- a/en/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -60,13 +60,7 @@ The **module.json5** of a browser application is as follows: } catch (error) { console.info(`explicit start ability failed with ${error.code}`) } - let context = getContext(this) as common.UIAbilityContext; - await context.startAbility(want) - console.info(`explicit start ability succeed`) - } catch (error) { - console.info(`explicit start ability failed with ${error.code}`) - } - } + } ``` The matching process is as follows: diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 56e63cd47e1267a1acb08b240162dd96396c2215..bb8785c26d8ba1f13d174da1c1fa3f8393ca6df4 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -20,13 +20,13 @@ The following table lists the USB APIs currently available. For details, see the | getDevices(): Array> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | -| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. | -| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\ | Performs bulk transfer. | +| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. | +| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\ | Performs bulk transfer. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | | getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | -| controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\ | Performs control transfer. | +| controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise<number> | Performs control transfer. | ## How to Develop @@ -51,7 +51,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat vendorId: 7531, productId: 2, clazz: 9, - subclass: 0, + subClass: 0, protocol: 1, devAddress: 1, busNum: 1, @@ -68,7 +68,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat id: 0, protocol: 0, clazz: 9, - subclass: 0, + subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ @@ -93,7 +93,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ``` -2. Obtain the device operation permissions. +2. Obtain the device operation permissions. ```js let deviceName = deviceList[0].name; @@ -105,11 +105,11 @@ You can set a USB device as the USB host to connect to other USB devices for dat }); ``` -3. Open the device. +3. Open the device. ```js // Open the device, and obtain the USB device pipe for data transfer. - let pipe = usb.connectDevice(deviceList[0]); + let interface1 = deviceList[0].configs[0].interfaces[0]; /* Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. @@ -117,14 +117,16 @@ You can set a USB device as the USB host to connect to other USB devices for dat usb.claimInterface(pipe, interface1, true); ``` -4. Perform data transfer. +4. Perform data transfer. ```js /* Read data. Select the corresponding RX endpoint from deviceList for data transfer. (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array. */ - + let inEndpoint = interface1.endpoints[2]; + let outEndpoint = interface1.endpoints[1]; + let dataUint8Array = new Uint8Array(1024); usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { if (dataLength >= 0) { console.info("usb readData result Length : " + dataLength); @@ -137,7 +139,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat console.info("usb readData error : " + JSON.stringify(error)); }); // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) - usb.bulkTransfer(pipe, endpoint, dataUint8Array, 15000).then(dataLength => { + usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => { if (dataLength >= 0) { console.info("usb writeData result write length : " + dataLength); } else { diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index b8a4496e09420b3a7557e5c8b8996deaf14ce1c9..4ed700a49b94ef0c296ec27eaf9c5cde96575234 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,8 +1,13 @@ # DFX -- [Development of Application Event Logging](hiappevent-guidelines.md) -- [Development of Performance Tracing](hitracemeter-guidelines.md) -- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) +- Application Event Logging + - [Development of Application Event Logging](hiappevent-guidelines.md) +- Distributed Call Chain Tracing + - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) +- HiLog + - [HiLog Development](hilog-guidelines.md) +- Performance Tracing + - [Development of Performance Tracing](hitracemeter-guidelines.md) - Error Management - [Development of Error Manager](errormanager-guidelines.md) - [Development of Application Recovery](apprecovery-guidelines.md) diff --git a/en/application-dev/dfx/hilog-guidelines.md b/en/application-dev/dfx/hilog-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..f2a2fc7debf9b924d1b8db8894316adc6a826876 --- /dev/null +++ b/en/application-dev/dfx/hilog-guidelines.md @@ -0,0 +1,37 @@ +# HiLog Development +## Introduction +HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status. +> **NOTE** +> This development guide is applicable only when you use Native APIs for application development. For details about the APIs, see [HiLog Native API Reference](https://gitee.com/openharmony-sig/interface_native_header/blob/master/en/native_sdk/dfx/log.h). + +## Available APIs +| API/Macro| Description| +| -------- | -------- | +| int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) | Outputs logs based on the specified log type, log level, service domain, log tag, and variable parameters determined by the format specifier and privacy identifier in the printf format.| +| #define OH_LOG_DEBUG(type, ...) ((void)OH_LOG_Print((type), LOG_DEBUG, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__))| Outputs DEBUG logs. This is a function-like macro.| +| #define OH_LOG_INFO(type, ...) ((void)OH_LOG_Print((type), LOG_INFO, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs INFO logs. This is a function-like macro.| +| #define OH_LOG_WARN(type, ...) ((void)OH_LOG_Print((type), LOG_WARN, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs WARN logs. This is a function-like macro.| +| #define OH_LOG_ERROR(type, ...) ((void)OH_LOG_Print((type), LOG_ERROR, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs ERROR logs. This is a function-like macro.| +| #define OH_LOG_FATAL(type, ...) ((void)OH_LOG_Print((type), LOG_FATAL, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs FATAL logs. This is a function-like macro.| +| bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) | Checks whether logs of the specified service domain, tag, and level can be printed.
Input arguments:
- **domain**: service domain.
- **tag**: log tag.
- **level**: log level.
Output arguments: none
Return value: Returns **true** if the specified logs can be printed; returns **false** otherwise.| + +## Development Examples +1. Include the **hilog** header file in the source file. +```c++ +#include "hilog/log.h" +``` +2. Define the **domain** and **tag** macros. +```c++ +#undef LOG_DOMAIN +#undef LOG_TAG +#define LOG_DOMAIN 0x3200 // Service domain. The value ranges from 0xD0000 to 0xDFFFF. +#define LOG_TAG "MY_TAG" +``` +3. Print logs. For example, to print INFO logs, use the following code: +```c++ +OH_LOG_INFO(LOG_APP, "Failed to visit %{private}s, reason:%{public}d.", url, errno); +``` +4. View the output log information. +``` +12-11 12:21:47.579 2695 2695 I A03200/MY_TAG: Failed to visit , reason:11. +``` diff --git a/en/application-dev/dfx/hitracechain-guidelines.md b/en/application-dev/dfx/hitracechain-guidelines.md index affd260b0503f3c4f4c4b748d5911d94f7fef9e3..37ca65ece66a124eb8a72f1fd865f30d26024627 100644 --- a/en/application-dev/dfx/hitracechain-guidelines.md +++ b/en/application-dev/dfx/hitracechain-guidelines.md @@ -2,9 +2,7 @@ ## Introduction -The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. - -hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process. +hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process. The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. ## Basic Concepts @@ -18,47 +16,106 @@ The APIs for distributed call chain tracing are provided by the **hiTraceChain** **APIs for distributed call chain tracing** -| API| Return Value| Description| -| ------------------------------------------------------------------------------------------------------------------- | -------------- | ------------ | -| hiTraceChain.begin(name: string, flags: number = HiTraceFlag.DEFAULT) | HiTraceId | Starts call chain tracing.| -| hiTraceChain.tracepoint(mode: HiTraceCommunicationMode, type: HiTraceTracepointType, id: HiTraceId, msg?: string) | void | Creates a trace point.| -| hiTraceChain.end(id: HiTraceId) | void | Stops call chain tracing.| +| API | Return Value | Description | +| ------------------------------------------------------------------------------------------------------------------- | -------------- | ------------ | +| hiTraceChain.begin(name: string, flags: number = HiTraceFlag.DEFAULT) | HiTraceId | Starts call chain tracing. | +| hiTraceChain.end(id: HiTraceId) | void | Stops call chain tracing. | ## How to Develop -In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed. - -1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement call chain tracing upon page loading. The sample code is as follows: - - ``` - import hiTraceChain from '@ohos.hiTraceChain' - - export default { - data: { - title: "" - }, - onInit() { - this.title = this.$t('strings.world'); - - // 1. Enable distributed call chain tracing. - let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC | hiTraceChain.HiTraceFlag.DONOT_CREATE_SPAN); - - // 2. Start the service process. - console.log(`business start`); - - // 3. Add a trace point. - hiTraceChain.tracepoint(hiTraceChain.HiTraceCommunicationMode.THREAD, hiTraceChain.HiTraceTracepointType.SS, asyncTraceId, "Just an example"); - - // 4. Keep the service process running. - console.log(`business running`); - - // 5. End the service process. - console.log(`business end`); - - // 6. Stop call chain tracing. - hiTraceChain.end(asyncTraceId); - } - } +The following example illustrates how to simulate one-time [system event logging](../reference/apis/js-apis-hisysevent.md) to implement cross-thread distributed call chain tracing in a single HAP service. + +1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add a button to trigger system event logging. + + ```ts + import hiTraceChain from '@ohos.hiTraceChain'; + import hiSysEvent from '@ohos.hiSysEvent'; + + @Entry + @Component + struct Index { + @State message: string = 'Start writing system event'; + + build() { + Row() { + Column() { + Button(this.message) + .fontSize(20) + .margin(5) + .width(350) + .height(60) + .fontWeight(FontWeight.Bold) + .onClick(() => { + try { + // Enable distributed call chain tracing before the service starts. + let traceId = hiTraceChain.begin("Write a new system event", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC); + // Implement one-time system event logging when the service starts. + hiSysEvent.write({ + domain: "RELIABILITY", + name: "STACK", + eventType: hiSysEvent.EventType.FAULT, + params: { + PID: 1, + UID: 1, + PACKAGE_NAME: "com.demo.hitracechain", + PROCESS_NAME: "hitracechaindemo", + MSG: "no msg." + } + }).then((val) => { + console.info(`write result is ${val}`); + // Disable distributed call chain tracing when the service ends. + hiTraceChain.end(traceId); + }).catch((err) => { + console.error(`error message is ${err.message}`); + }); + } catch (err) { + console.error(`error message is ${err.message}`); + } + }) + } + .width('100%') + } + .height('100%') + } + } + ``` + +2. Touch the run button on the IDE to run the project. Then, touch the **Start writing system event** button on the application UI to trigger system event logging. + +3. View the information printed in the **Log** window. You can use **.*: \[([0-9a-zA-Z]{15}),.*].*** to access distributed call chain tracing information specific to the HAP service. The process ID of the HAP service is **8801**. Two threads, whose IDs are **8801** and **8819**, are involved in the system event logging. Based on the chain ID **edcfa53017a88e3**, you can then effectively trace the log information of the two threads. + ```text + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain I C02d03/HiTraceC: [edcfa53017a88e3, 0, 0] HiTraceBegin name:Write a new system event flags:0x01. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: chainId is edcfa53017a88e3. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: spanId is 0. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: parentSpanId is 0. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: flags is 1. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] domain is RELIABILITY. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] name is STACK. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] eventType is 1. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=3, typeName=6. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=3, typeName=6. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=4, typeName=6. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=4, typeName=6. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=4, typeName=6. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] create napi value of string type, value is JSHiSysEventWrite. + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain I C03900/Ace: [edcfa53017a88e3, 0, 0] [flutter_ace_view.cpp(operator())-(0)] Mark 0 id Touch Event Processed + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02800/ClientMsgHandler: [edcfa53017a88e3, 0, 0] in OnDispatchEventProcessed, enter + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02800/ANRHandler: [edcfa53017a88e3, 0, 0] in SetLastProcessedEventId, enter + 07-05 19:50:47.690 8801-8819/com.demo.hitracechain D C02d08/HISYSEVENT: [edcfa53017a88e3, 0, 0] size=312, sysevent={"domain_":"RELIABILITY","name_":"STACK","type_":1,"time_":47591447690,"tz_":"+0000","pid_":8801,"tid_":8819,"uid_":20010045,"traceid_":"edcfa53017a88e3","spanid_":"0","pspanid_":"0","trace_flag_":1,"UID":1,"PID":1,"MSG":"no msg.","PROCESS_NAME":"hitracechaindemo","PACKAGE_NAME":"com.demo.hitracechain"} + 07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02800/ANRHandler: [edcfa53017a88e3, 0, 0] in SetLastProcessedEventId, Processed event type:0, id:831, actionTime:6694499314, currentTime:6694501330, timeoutTime:4997984 + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02800/ANRHandler: [edcfa53017a88e3, 0, 0] in SetLastProcessedEventId, leave + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02800/ClientMsgHandler: [edcfa53017a88e3, 0, 0] in OnDispatchEventProcessed, leave + 07-05 19:50:47.691 8801-8819/com.demo.hitracechain D C02d08/HISYSEVENT: [edcfa53017a88e3, 0, 0] reset send buffer size old=245760, new=524288 + 07-05 19:50:47.691 8801-8819/com.demo.hitracechain D C02d08/HISYSEVENT: [edcfa53017a88e3, 0, 0] HiSysEvent send data successful + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] create napi value of int32 type, value is 0. + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain E A0fefe/JsApp: [edcfa53017a88e3, 399db38, 0] write result is 0 + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: chainId is edcfa53017a88e3. + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: spanId is 0. + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: parentSpanId is 0. + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: flags is 1. + 07-05 19:50:47.691 8801-8801/com.demo.hitracechain I C02d03/HiTraceC: [edcfa53017a88e3, 399db38, 0] HiTraceEnd. ``` -2. Click the run button on the application page. Then, you'll obtain the log information for service analysis. +## About Cross-Process/Cross-Device Distributed Call Chain Tracing + +Cross-process/cross-device distributed call chain tracing depends on the NAPI implementation of the corresponding service APIs of each OpenHarmony module. For details, see the [HiTraceChain Development](../../device-dev/subsystems/subsys-dfx-hitracechain.md). diff --git a/en/application-dev/media/avsession-guidelines.md b/en/application-dev/media/avsession-guidelines.md index 6106509fbfe30a7b437ec574843f50cd7bf1aceb..3d1ac479f0f358c42778e60a0d4b47edafe0a0cd 100644 --- a/en/application-dev/media/avsession-guidelines.md +++ b/en/application-dev/media/avsession-guidelines.md @@ -1,5 +1,9 @@ # 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 @@ -28,7 +32,7 @@ Table 1 Common APIs for session access end development ```js import avSession from '@ohos.multimedia.avsession'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; import featureAbility from '@ohos.ability.featureAbility'; ``` @@ -50,7 +54,7 @@ avSession.createAVSession(context, "AudioAppSample", 'audio').then((session) => 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**. Generally, **WantAgent** is used to encapsulate want information. For more information, see [wantAgent](../reference/apis/js-apis-wantAgent.md). +- 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. @@ -83,7 +87,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + abilityName: "com.example.test.EntryAbility", } ], operationType: wantAgent.OperationType.START_ABILITIES, @@ -187,7 +191,7 @@ currentSession.on('playNext', () => { }); console.log ("Call AudioPlayer.play."); // Set the playback state information. - let time = (new Data()).getTime(); + 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) => { @@ -282,7 +286,7 @@ currentSession.off('outputDeviceChange'); // Deactivate the session and destroy the object. currentSession.deactivate().then(() => { - currentSession.destory(); + currentSession.destroy(); }); ``` @@ -365,7 +369,7 @@ Table 2 Common APIs for session control end development ```js import avSession from '@ohos.multimedia.avsession'; import {Action, KeyEvent} from '@ohos.multimodalInput.KeyEvent'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; import audio from '@ohos.multimedia.audio'; ``` diff --git a/en/application-dev/media/avsession-overview.md b/en/application-dev/media/avsession-overview.md index 761483bf5052ef48cd9313261ead681b295d6604..c46211765644330ac26c1154f181904c2db4c3d0 100644 --- a/en/application-dev/media/avsession-overview.md +++ b/en/application-dev/media/avsession-overview.md @@ -1,5 +1,9 @@ # AVSession Overview +> **NOTE** +> +> All APIs of the **AVSession** module are system APIs and can be called only by system applications. + ## Overview AVSession, short for audio and video session, is also known as media session. @@ -49,4 +53,4 @@ The **AVSession** module provides two classes: **AVSession** and **AVSessionCont - 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 third-party applications. Only third-party applications that have accessed AVSession can play audio in the background. Otherwise, the system forcibly pauses the playback when a third-party application switches to the background. +- 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. diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md index 1355a27dcf7fb5e54a283ccd5c39a4f1b19de381..a48a081a3e69ea8259727efd343264f80c6cc284 100644 --- a/en/application-dev/napi/drawing-guidelines.md +++ b/en/application-dev/napi/drawing-guidelines.md @@ -118,9 +118,9 @@ The following steps describe how to use the canvas and brush of the Native Drawi // Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush. OH_Drawing_CanvasDrawPath(cCanvas, cPath); // Destroy the created objects when they are no longer needed. - OH_Drawing_BrushDestory(cBrush); - OH_Drawing_PenDestory(cPen); - OH_Drawing_PathDestory(cPath); + OH_Drawing_BrushDestroy(cBrush); + OH_Drawing_PenDestroy(cPen); + OH_Drawing_PathDestroy(cPath); ``` 6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas. @@ -133,9 +133,9 @@ The following steps describe how to use the canvas and brush of the Native Drawi LOGI("memcpy_s failed"); } // Destroy the canvas object. - OH_Drawing_CanvasDestory(cCanvas); + OH_Drawing_CanvasDestroy(cCanvas); // Destroy the bitmap object. - OH_Drawing_BitmapDestory(cBitmap); + OH_Drawing_BitmapDestroy(cBitmap); ``` ## Development Procedure for Text Drawing diff --git a/en/application-dev/napi/native-window-guidelines.md b/en/application-dev/napi/native-window-guidelines.md index a71a261c8d2dc6cee74e79deff99d50814a00007..f5a5ead9c083217c77692b34384f969c4b44dc00 100644 --- a/en/application-dev/napi/native-window-guidelines.md +++ b/en/application-dev/napi/native-window-guidelines.md @@ -29,20 +29,72 @@ The following scenarios are common for native window development: | OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow \*window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t \*metaData) | Sets the HDR static metadata set of the native window.| | OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow \*window, const OHExtDataHandle \*handle) | Sets the tunnel handle to the native window.| - ## How to Develop The following describes how to use the NAPI provided by **NativeWindow** to request a graphics buffer, write the produced graphics content to the buffer, and flush the buffer to the graphics queue. -1. Obtain a **NativeWindow** instance. For example, use **Surface** to create a **NativeWindow** instance. - ```c++ - sptr cSurface = Surface::CreateSurfaceAsConsumer(); - sptr listener = new BufferConsumerListenerTest(); - cSurface->RegisterConsumerListener(listener); - sptr producer = cSurface->GetProducer(); - sptr pSurface = Surface::CreateSurfaceAsProducer(producer); - OHNativeWindow* nativeWindow = OH_NativeWindow_CreateNativeWindow(&pSurface); - ``` +1. Obtain a **NativeWindow** instance, which can be obtained by running the APIs provided by **OH_NativeXComponent_Callback**. + 1. Define **XComponent** in an .ets file. + ```ts + XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'nativerender'}) + .onLoad((context) => { + this.context = context; + }) + .onDestroy(() => { + }) + ``` + 2. Obtain **NativeXComponent** at the native C++ layer. + ```c++ + napi_value exportInstance = nullptr; + napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance); + + OH_NativeXComponent *nativeXComponent = nullptr; + napi_unwrap(env, exportInstance, reinterpret_cast(&nativeXComponent)); + + char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { }; + uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1; + OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize); + ``` + 3. Define **OH_NativeXComponent_Callback**. + ```c++ + // Define the callback. + void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window) + { + // Obtain a NativeWindow instance. + OHNativeWindow* nativeWindow = window; + // ... + } + void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window) + { + // Obtain a NativeWindow instance. + OHNativeWindow* nativeWindow = window; + // ... + } + void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) + { + // Obtain a NativeWindow instance. + OHNativeWindow* nativeWindow = window; + // ... + } + void DispatchTouchEventCB(OH_NativeXComponent* component, void* window) + { + // Obtain a NativeWindow instance. + OHNativeWindow* nativeWindow = window; + // ... + } + ``` + ```c++ + // Initialize OH_NativeXComponent_Callback. + OH_NativeXComponent_Callback callback_; + callback_->OnSurfaceCreated = OnSurfaceCreatedCB; + callback_->OnSurfaceChanged = OnSurfaceChangedCB; + callback_->OnSurfaceDestroyed = OnSurfaceDestroyedCB; + callback_->DispatchTouchEvent = DispatchTouchEventCB; + ``` + 4. Register **OH_NativeXComponent_Callback** with **NativeXComponent**. + ```c++ + OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback_); + ``` 2. Set the attributes of a native window buffer by using **OH_NativeWindow_NativeWindowHandleOpt**. ```c++ @@ -90,7 +142,6 @@ The following describes how to use the NAPI provided by **NativeWindow** to requ ``` 5. Flush the native window buffer to the graphics queue. - ```c++ // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the native window buffer are changed. Region region{nullptr, 0}; diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md index 3fff90e0682c4f79e63fa0ee8306a5f8aa7e9385..19e6d16258b06b5a2f613a01061fc6a683488ee2 100644 --- a/en/application-dev/quick-start/app-configuration-file.md +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -30,21 +30,21 @@ 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| | 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| -| description | Description of the application. 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 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| +| description | Description of the application. The value is a string with a maximum of 255 bytes or a resource index to the description.| String| Yes (initial value: left empty)| | vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | versionCode | Version number of the application. The value is a 32-bit non-negative integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number| No| | versionName | Version number of the application displayed to users.
The value consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:
Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.
The value contains a maximum of 127 bytes.| String| No| | minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario.| Number| Yes (initial value: value of **versionCode**)| -| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| -| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| +| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)| +| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.
- **Canary**: indicates a restricted release.
- **Beta**: indicates a publicly released beta version.
- **Release**: indicates a publicly released official version.
The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| | distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.
- **true**: Distributed notification is enabled.
- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)| | entityType | Type of the application. The options are as follows:
- game
- media
- communication
- news
- travel
- utility
- shopping
- education
- kids
- business
- photography
- unspecified| String| Yes (initial value: **"unspecified"**)| diff --git a/en/application-dev/quick-start/application-package-install-uninstall.md b/en/application-dev/quick-start/application-package-install-uninstall.md index 3ccafd9ad3da5f98b9fbd229ff7025863ca105d8..2fad037a9135912fc9a8ca2b48c56af9ffd8583c 100644 --- a/en/application-dev/quick-start/application-package-install-uninstall.md +++ b/en/application-dev/quick-start/application-package-install-uninstall.md @@ -1,8 +1,13 @@ # Application Installation and Uninstallation Process +## Developers +Developers can install and uninstall applications by running debug commands. For details, see [Multi-HAP Development, Debugging, Release, and Deployment Process](multi-hap-release-deployment.md#debugging). -The OpenHarmony bundle manager service module provides APIs for installing, updating, and uninstalling applications. You can call these APIs when needed. After you release your application to the application market, users can install and uninstall it on their device. +**Figure 1** Process of installing and uninstalling an application (applicable to developers) +![hap-intall-uninstall](figures/hap-install-uninstall-developer.png) +## Consumers +When an application has been released to the application market, consumers can install or uninstall the application on their device through the application market. - **Figure 1** Process of installing and uninstalling an application -![hap-intall-uninstall](figures/hap-intall-uninstall.png) +**Figure 2** Process of installing and uninstalling an application (applicable to consumers) +![hap-intall-uninstall](figures/hap-install-uninstall-user.png) \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-rendering-control.md b/en/application-dev/quick-start/arkts-rendering-control.md index d0ff5a8c183d8efba03b12f7343f001a3ba31fe5..0cb38c2c123171b7ebe05df263b7275445542986 100644 --- a/en/application-dev/quick-start/arkts-rendering-control.md +++ b/en/application-dev/quick-start/arkts-rendering-control.md @@ -263,11 +263,11 @@ struct MyComponent { > > - **LazyForEach** must be used in the container component. Currently, only the **\**, **\**, and **\** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time. > -> - **LazyForEach** must create and only one child component in each iteration. +> - **LazyForEach** must create one and only one child component in each iteration. > -> - The generated child components must be allowed in the parent container component of **LazyForEach**. +> - The generated child components must be the ones allowed in the parent container component of **LazyForEach**. > -> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement. +> - **LazyForEach** can be included in an **if/else** statement. > > - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**. > diff --git a/en/application-dev/quick-start/figures/hap-install-uninstall-developer.png b/en/application-dev/quick-start/figures/hap-install-uninstall-developer.png new file mode 100644 index 0000000000000000000000000000000000000000..71de207ab9c530c353064a3422c6855eafa7770e Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-install-uninstall-developer.png differ diff --git a/en/application-dev/quick-start/figures/hap-install-uninstall-user.png b/en/application-dev/quick-start/figures/hap-install-uninstall-user.png new file mode 100644 index 0000000000000000000000000000000000000000..2cd71657b6bb0af0a4d5094d09ebe028807518be Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-install-uninstall-user.png differ diff --git a/en/application-dev/quick-start/figures/hap-intall-uninstall.png b/en/application-dev/quick-start/figures/hap-intall-uninstall.png deleted file mode 100644 index de04aa18f5053de48dd0b595c8265c781e36fee5..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/hap-intall-uninstall.png and /dev/null differ diff --git a/en/application-dev/quick-start/multi-hap-release-deployment.md b/en/application-dev/quick-start/multi-hap-release-deployment.md index 785f476bf2fa508470d433477f4e1139e76589fd..ec688879ebb61ceb595feb974f2276d700479ef5 100644 --- a/en/application-dev/quick-start/multi-hap-release-deployment.md +++ b/en/application-dev/quick-start/multi-hap-release-deployment.md @@ -28,12 +28,12 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca uninstall bundle successfully. ``` -* Using Bundle Manager (bm) for debugging +* Using [Bundle Manager (bm)](../../application-dev/tools/bm-tool.md) for debugging When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows: ``` // Installation and update: Multiple file paths can be specified. - bm install -p /data/app/entry.hap /data/app/ feature.hap + bm install -p /data/app/entry.hap /data/app/feature.hap // The execution result is as follows: install bundle successfully. // Uninstall diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 3d225b8fd3e7c8941fddce20f678dd6797f6ae8b..5af0c2ec5f64bbb5c477af7d133c1c1f2379f9ed 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -4,71 +4,71 @@ - Ability Framework - Stage Model (Recommended) - - [@ohos.app.ability.Ability](js-apis-app-ability-ability.md) - - [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) - - [@ohos.app.ability.abilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) - - [@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md) - - [@ohos.app.ability.common](js-apis-app-ability-common.md) - - [@ohos.app.ability.contextConstant](js-apis-app-ability-contextConstant.md) - - [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) - - [@ohos.app.ability.ExtensionAbility](js-apis-app-ability-extensionAbility.md) - - [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) - - [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) - - [@ohos.app.ability.UIAbility](js-apis-app-ability-uiAbility.md) - - [@ohos.app.form.FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) - - [@ohos.application.DataShareExtensionAbility](js-apis-application-dataShareExtensionAbility.md) - - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) + - [@ohos.app.ability.Ability (Ability Base Class)](js-apis-app-ability-ability.md) + - [@ohos.app.ability.AbilityConstant (AbilityConstant)](js-apis-app-ability-abilityConstant.md) + - [@ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-app-ability-abilityLifecycleCallback.md) + - [@ohos.app.ability.AbilityStage (AbilityStage)](js-apis-app-ability-abilityStage.md) + - [@ohos.app.ability.common (Context)](js-apis-app-ability-common.md) + - [@ohos.app.ability.contextConstant (ContextConstant)](js-apis-app-ability-contextConstant.md) + - [@ohos.app.ability.EnvironmentCallback (EnvironmentCallback)](js-apis-app-ability-environmentCallback.md) + - [@ohos.app.ability.ExtensionAbility (ExtensionAbility Base Class)](js-apis-app-ability-extensionAbility.md) + - [@ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility)](js-apis-app-ability-serviceExtensionAbility.md) + - [@ohos.app.ability.StartOptions (StartOptions)](js-apis-app-ability-startOptions.md) + - [@ohos.app.ability.UIAbility (UIAbility)](js-apis-app-ability-uiAbility.md) + - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](js-apis-app-form-formExtensionAbility.md) + - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md) + - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md) - Stage Model (To Be Deprecated Soon) - - [@ohos.application.Ability](js-apis-application-ability.md) - - [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md) - - [@ohos.application.AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) - - [@ohos.application.AbilityStage](js-apis-application-abilityStage.md) - - [@ohos.application.context](js-apis-application-context.md) - - [@ohos.application.EnvironmentCallback](js-apis-application-environmentCallback.md) - - [@ohos.application.ExtensionAbility](js-apis-application-extensionAbility.md) - - [@ohos.application.FormExtension](js-apis-application-formExtension.md) - - [@ohos.application.ServiceExtensionAbility](js-apis-application-serviceExtensionAbility.md) - - [@ohos.application.StartOptions](js-apis-application-startOptions.md) + - [@ohos.application.Ability (Ability)](js-apis-application-ability.md) + - [@ohos.application.AbilityConstant (AbilityConstant)](js-apis-application-abilityConstant.md) + - [@ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-application-abilityLifecycleCallback.md) + - [@ohos.application.AbilityStage (AbilityStage)](js-apis-application-abilityStage.md) + - [@ohos.application.context (Context)](js-apis-application-context.md) + - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md) + - [@ohos.application.ExtensionAbility (ExtensionAbility)](js-apis-application-extensionAbility.md) + - [@ohos.application.FormExtension (FormExtension)](js-apis-application-formExtension.md) + - [@ohos.application.ServiceExtensionAbility (ServiceExtensionAbility)](js-apis-application-serviceExtensionAbility.md) + - [@ohos.application.StartOptions (StartOptions)](js-apis-application-startOptions.md) - FA Model - - [@ohos.ability.ability](js-apis-ability-ability.md) - - [@ohos.ability.featureAbility](js-apis-ability-featureAbility.md) - - [@ohos.ability.particleAbility](js-apis-ability-particleAbility.md) + - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) + - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) + - [@ohos.ability.particleAbility (ParticleAbility)](js-apis-ability-particleAbility.md) - Both Models (Recommended) - - [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) - - [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) - - [@ohos.app.ability.appManager](js-apis-app-ability-appManager.md) - - [@ohos.app.ability.appRecovery](js-apis-app-ability-appRecovery.md) - - [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) - - [@ohos.app.ability.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) - - [@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md) - - [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) - - [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) - - [@ohos.app.ability.quickFixManager](js-apis-app-ability-quickFixManager.md) - - [@ohos.app.ability.Want](js-apis-app-ability-want.md) - - [@ohos.app.ability.wantAgent](js-apis-app-ability-wantAgent.md) - - [@ohos.app.ability.wantConstant](js-apis-app-ability-wantConstant.md) - - [@ohos.app.form.formBindingData](js-apis-app-form-formBindingData.md) - - [@ohos.app.form.formHost](js-apis-app-form-formHost.md) - - [@ohos.app.form.formInfo](js-apis-app-form-formInfo.md) - - [@ohos.app.form.formProvider](js-apis-app-form-formProvider.md) + - [@ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry)](js-apis-app-ability-abilityDelegatorRegistry.md) + - [@ohos.app.ability.abilityManager (AbilityManager)](js-apis-app-ability-abilityManager.md) + - [@ohos.app.ability.appManager (appManager)](js-apis-app-ability-appManager.md) + - [@ohos.app.ability.appRecovery (appRecovery)](js-apis-app-ability-appRecovery.md) + - [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md) + - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md) + - [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md) + - [@ohos.app.ability.missionManager (missionManager)](js-apis-app-ability-missionManager.md) + - [@ohos.app.ability.quickFixManager (quickFixManager)](js-apis-app-ability-quickFixManager.md) + - [@ohos.app.ability.Want (Want)](js-apis-app-ability-want.md) + - [@ohos.app.ability.wantAgent (WantAgent)](js-apis-app-ability-wantAgent.md) + - [@ohos.app.ability.wantConstant (wantConstant)](js-apis-app-ability-wantConstant.md) + - [@ohos.app.form.formBindingData (formBindingData)](js-apis-app-form-formBindingData.md) + - [@ohos.app.form.formHost (FormHost)](js-apis-app-form-formHost.md) + - [@ohos.app.form.formInfo (FormInfo)](js-apis-app-form-formInfo.md) + - [@ohos.app.form.formProvider (FormProvider)](js-apis-app-form-formProvider.md) - Both Models (To Be Deprecated Soon) - - [@ohos.ability.dataUriUtils](js-apis-ability-dataUriUtils.md) - - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) - - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) - - [@ohos.application.abilityDelegatorRegistry](js-apis-application-abilityDelegatorRegistry.md) - - [@ohos.application.abilityManager](js-apis-application-abilityManager.md) - - [@ohos.application.appManager](js-apis-application-appManager.md) - - [@ohos.application.Configuration](js-apis-application-configuration.md) - - [@ohos.application.ConfigurationConstant](js-apis-application-configurationConstant.md) - - [@ohos.application.errorManager)](js-apis-application-errorManager.md) - - [@ohos.application.formBindingData](js-apis-application-formBindingData.md) - - [@ohos.application.formError](js-apis-application-formError.md) - - [@ohos.application.formHost](js-apis-application-formHost.md) - - [@ohos.application.formInfo](js-apis-application-formInfo.md) - - [@ohos.application.formProvider](js-apis-application-formProvider.md) - - [@ohos.application.missionManager](js-apis-application-missionManager.md) - - [@ohos.application.Want](js-apis-application-want.md) - - [@ohos.wantAgent](js-apis-wantAgent.md) + - [@ohos.ability.dataUriUtils (DataUriUtils)](js-apis-ability-dataUriUtils.md) + - [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md) + - [@ohos.ability.wantConstant (wantConstant)](js-apis-ability-wantConstant.md) + - [@ohos.application.abilityDelegatorRegistry (AbilityDelegatorRegistry)](js-apis-application-abilityDelegatorRegistry.md) + - [@ohos.application.abilityManager (AbilityManager)](js-apis-application-abilityManager.md) + - [@ohos.application.appManager (appManager)](js-apis-application-appManager.md) + - [@ohos.application.Configuration (Configuration)](js-apis-application-configuration.md) + - [@ohos.application.ConfigurationConstant (ConfigurationConstant)](js-apis-application-configurationConstant.md) + - [@ohos.application.errorManager (ErrorManager)](js-apis-application-errorManager.md) + - [@ohos.application.formBindingData (formBindingData)](js-apis-application-formBindingData.md) + - [@ohos.application.formError (FormError)](js-apis-application-formError.md) + - [@ohos.application.formHost (FormHost)](js-apis-application-formHost.md) + - [@ohos.application.formInfo (FormInfo)](js-apis-application-formInfo.md) + - [@ohos.application.formProvider (FormProvider)](js-apis-application-formProvider.md) + - [@ohos.application.missionManager (missionManager)](js-apis-application-missionManager.md) + - [@ohos.application.Want (Want)](js-apis-application-want.md) + - [@ohos.wantAgent (WantAgent)](js-apis-wantAgent.md) - Dependent Elements and Definitions - ability - [abilityResult](js-apis-inner-ability-abilityResult.md) @@ -108,7 +108,6 @@ - [MissionListener](js-apis-inner-application-missionListener.md) - [MissionParameter](js-apis-inner-application-missionParameter.md) - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) - - [PermissionRequestResult](js-apis-permissionrequestresult.md) - [ProcessData](js-apis-inner-application-processData.md) - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) - [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md) @@ -125,24 +124,24 @@ - [continuationResult](js-apis-continuation-continuationResult.md) - Common Event and Notification - - [@ohos.commonEventManager (Recommended)](js-apis-commonEventManager.md) - - [@ohos.events.emitter](js-apis-emitter.md) - - [@ohos.notificationManager (Recommended)](js-apis-notificationManager.md) - - [@ohos.notificationSubscribe (Recommended)](js-apis-notificationSubscribe.md) - - [@ohos.commonEvent (To Be Deprecated Soon)](js-apis-commonEvent.md) - - [@ohos.notification](js-apis-notification.md) + - [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md) + - [@ohos.events.emitter (Emitter)](js-apis-emitter.md) + - [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md) + - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md) + - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md) + - [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md) - application - [EventHub](js-apis-inner-application-eventHub.md) - Bundle Management - - [@ohos.bundle.appControl](js-apis-appControl.md) - - [@ohos.bundle.bundleManager](js-apis-bundleManager.md) - - [@ohos.bundle.bundleMonitor](js-apis-bundleMonitor.md) - - [@ohos.bundle.defaultAppManager](js-apis-defaultAppManager.md) + - [@ohos.bundle.appControl (appControl)](js-apis-appControl.md) + - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) + - [@ohos.bundle.bundleMonitor (bundleMonitor)](js-apis-bundleMonitor.md) + - [@ohos.bundle.defaultAppManager (Default Application Management)](js-apis-defaultAppManager.md) - [@ohos.bundle.distributedBundleManager (distributedBundleManager)](js-apis-distributedBundleManager.md) - - [@ohos.bundle.freeInstall](js-apis-freeInstall.md) - - [@ohos.bundle.installer](js-apis-installer.md) - - [@ohos.bundle.launcherBundleManager](js-apis-launcherBundleManager.md) - - [@ohos.zlib](js-apis-zlib.md) + - [@ohos.bundle.freeInstall (freeInstall)](js-apis-freeInstall.md) + - [@ohos.bundle.installer (installer)](js-apis-installer.md) + - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](js-apis-launcherBundleManager.md) + - [@ohos.zlib (Zip)](js-apis-zlib.md) - bundleManager - [abilityInfo](js-apis-bundleManager-abilityInfo.md) - [applicationInfo](js-apis-bundleManager-applicationInfo.md) @@ -158,41 +157,41 @@ - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - - [@ohos.animator](js-apis-animator.md) - - [@ohos.curves](js-apis-curve.md) - - [@ohos.matrix4](js-apis-matrix4.md) - - [@ohos.mediaquery](js-apis-mediaquery.md) - - [@ohos.promptAction](js-apis-promptAction.md) - - [@ohos.router](js-apis-router.md) + - [@ohos.animator (Animator)](js-apis-animator.md) + - [@ohos.curves (Interpolation Calculation)](js-apis-curve.md) + - [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md) + - [@ohos.mediaquery (Media Query)](js-apis-mediaquery.md) + - [@ohos.promptAction (Prompt)](js-apis-promptAction.md) + - [@ohos.router (Page Routing)](js-apis-router.md) - Graphics - - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - - [@ohos.application.WindowExtensionAbility](js-apis-application-windowExtensionAbility.md) - - [@ohos.display ](js-apis-display.md) - - [@ohos.effectKit](js-apis-effectKit.md) - - [@ohos.graphics.colorSpaceManager](js-apis-colorSpaceManager.md) - - [@ohos.screen](js-apis-screen.md) - - [@ohos.screenshot](js-apis-screenshot.md) - - [@ohos.window](js-apis-window.md) + - [@ohos.animation.windowAnimationManager (Window Animation Management)](js-apis-windowAnimationManager.md) + - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](js-apis-application-windowExtensionAbility.md) + - [@ohos.display (Display)](js-apis-display.md) + - [@ohos.effectKit (Image Effects)](js-apis-effectKit.md) + - [@ohos.graphics.colorSpaceManager (Color Space Management)](js-apis-colorSpaceManager.md) + - [@ohos.screen (Screen)](js-apis-screen.md) + - [@ohos.screenshot (Screenshot)](js-apis-screenshot.md) + - [@ohos.window (Window)](js-apis-window.md) - webgl - - [webgl](js-apis-webgl.md) - - [webgl2](js-apis-webgl2.md) + - [WebGL](js-apis-webgl.md) + - [WebGL2](js-apis-webgl2.md) - Media - - [@ohos.multimedia.audio](js-apis-audio.md) - - [@ohos.multimedia.avsession](js-apis-avsession.md) - - [@ohos.multimedia.camera](js-apis-camera.md) - - [@ohos.multimedia.image](js-apis-image.md) - - [@ohos.multimedia.media](js-apis-media.md) + - [@ohos.multimedia.audio (Audio Management)](js-apis-audio.md) + - [@ohos.multimedia.avsession (AVSession Management)](js-apis-avsession.md) + - [@ohos.multimedia.camera (Camera Management)](js-apis-camera.md) + - [@ohos.multimedia.image (Image Processing)](js-apis-image.md) + - [@ohos.multimedia.media (Media)](js-apis-media.md) - Resource Management - - [@ohos.i18n](js-apis-i18n.md) - - [@ohos.intl](js-apis-intl.md) - - [@ohos.resourceManager](js-apis-resource-manager.md) + - [@ohos.i18n (Internationalization)](js-apis-i18n.md) + - [@ohos.intl (Internationalization)](js-apis-intl.md) + - [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md) - Resource Scheduling - - [@ohos.distributedMissionManager](js-apis-distributedMissionManager.md) - - [@ohos.reminderAgentManager](js-apis-reminderAgentManager.md) - - [@ohos.resourceschedule.backgroundTaskManager](js-apis-resourceschedule-backgroundTaskManager.md) - - [@ohos.resourceschedule.workScheduler](js-apis-resourceschedule-workScheduler.md) - - [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md) - - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) + - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) + - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) + - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) + - [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) + - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) + - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - Security - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) @@ -202,6 +201,9 @@ - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) + - security + - [PermissionRequestResult](js-apis-permissionrequestresult.md) + - Data Management - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) @@ -218,29 +220,26 @@ - [@ohos.environment](js-apis-environment.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) - - [@ohos.fileio (File Management)](js-apis-fileio.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - - [@ohos.securityLabel (Data Label)](js-apis-securityLabel.md) - - [@ohos.statfs (statfs)](js-apis-statfs.md) - [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md) - [@ohos.volumeManager (Volume Management)](js-apis-volumemanager.md) - Telephony Service - - [@ohos.contact](js-apis-contact.md) - - [@ohos.telephony.call](js-apis-call.md) - - [@ohos.telephony.data](js-apis-telephony-data.md) - - [@ohos.telephony.observer](js-apis-observer.md) - - [@ohos.telephony.radio](js-apis-radio.md) - - [@ohos.telephony.sim](js-apis-sim.md) - - [@ohos.telephony.sms](js-apis-sms.md) + - [@ohos.contact (Contacts)](js-apis-contact.md) + - [@ohos.telephony.call (Call)](js-apis-call.md) + - [@ohos.telephony.data (Cellular Data)](js-apis-telephony-data.md) + - [@ohos.telephony.observer (Observer)](js-apis-observer.md) + - [@ohos.telephony.radio (Network Search)](js-apis-radio.md) + - [@ohos.telephony.sim (SIM Management)](js-apis-sim.md) + - [@ohos.telephony.sms (SMS)](js-apis-sms.md) - Network Management - - [@ohos.net.connection](js-apis-net-connection.md) - - [@ohos.net.ethernet](js-apis-net-ethernet.md) - - [@ohos.net.http](js-apis-http.md) - - [@ohos.net.sharing](js-apis-net-sharing.md) - - [@ohos.net.socket](js-apis-socket.md) - - [@ohos.net.webSocket](js-apis-webSocket.md) - - [@ohos.request](js-apis-request.md) + - [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md) + - [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.md) + - [@ohos.net.http (Data Request)](js-apis-http.md) + - [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md) + - [@ohos.net.socket (Socket Connection)](js-apis-socket.md) + - [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md) + - [@ohos.request (Upload and Download)](js-apis-request.md) - Connectivity - [@ohos.bluetooth (Bluetooth)](js-apis-bluetooth.md) - [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md) @@ -256,136 +255,139 @@ - [nfctech (Standard NFC Technologies)](js-apis-nfctech.md) - [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md) - Basic Features - - [@ohos.accessibility](js-apis-accessibility.md) - - [@ohos.accessibility.config](js-apis-accessibility-config.md) - - [@ohos.accessibility.GesturePat](js-apis-accessibility-GesturePath.md) - - [@ohos.accessibility.GesturePoint](js-apis-accessibility-GesturePoint.md) - - [@ohos.application.AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md) - - [@ohos.faultLogger](js-apis-faultLogger.md) - - [@ohos.hichecker](js-apis-hichecker.md) - - [@ohos.hidebug](js-apis-hidebug.md) - - [@ohos.hilog](js-apis-hilog.md) - - [@ohos.hiSysEvent](js-apis-hisysevent.md) - - [@ohos.hiTraceChain](js-apis-hitracechain.md) - - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - - [@ohos.hiviewdfx.hiAppEvent](js-apis-hiviewdfx-hiappevent.md) - - [@ohos.inputmethod](js-apis-inputmethod.md) - - [@ohos.inputmethodengine](js-apis-inputmethodengine.md) - - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) - - [@ohos.inputmethodsubtype](js-apis-inputmethod-subtype.md) - - [@ohos.pasteboard](js-apis-pasteboard.md) - - [@ohos.screenLock](js-apis-screen-lock.md) - - [@ohos.systemTime](js-apis-system-time.md) - - [@ohos.systemTimer](js-apis-system-timer.md) - - [@ohos.wallpaper](js-apis-wallpaper.md) - - [@ohos.web.webview](js-apis-webview.md) - - [console](js-apis-logs.md) + - [@ohos.accessibility (Accessibility)](js-apis-accessibility.md) + - [@ohos.accessibility.config (System Accessibility Configuration)](js-apis-accessibility-config.md) + - [@ohos.accessibility.GesturePath (Gesture Path)](js-apis-accessibility-GesturePath.md) + - [@ohos.accessibility.GesturePoint (Gesture Point)](js-apis-accessibility-GesturePoint.md) + - [@ohos.application.AccessibilityExtensionAbility (AccessibilityExtensionAbility)](js-apis-application-accessibilityExtensionAbility.md) + - [@ohos.faultLogger (FaultLogger)](js-apis-faultLogger.md) + - [@ohos.hichecker (HiChecker)](js-apis-hichecker.md) + - [@ohos.hidebug (HiDebug)](js-apis-hidebug.md) + - [@ohos.hilog (HiLog)](js-apis-hilog.md) + - [@ohos.hiSysEvent (System Event Logging)](js-apis-hisysevent.md) + - [@ohos.hiTraceChain (Distributed Call Chain Tracing)](js-apis-hitracechain.md) + - [@ohos.hiTraceMeter (Performance Tracing)](js-apis-hitracemeter.md) + - [@ohos.hiviewdfx.hiAppEvent (Application Event Logging)](js-apis-hiviewdfx-hiappevent.md) + - [@ohos.inputMethod (Input Method Framework)](js-apis-inputmethod.md) + - [@ohos.inputMethodEngine (Input Method Service)](js-apis-inputmethodengine.md) + - [@ohos.InputMethodExtensionAbility (InputMethodExtensionAbility)](js-apis-inputmethod-extension-ability.md) + - [@ohos.InputMethodExtensionContext (InputMethodExtensionContext)](js-apis-inputmethod-extension-context.md) + - [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md) + - [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md) + - [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md) + - [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md) + - [@ohos.systemTimer (System Timer)](js-apis-system-timer.md) + - [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md) + - [@ohos.web.webview (Webview)](js-apis-webview.md) + - [console (Log)](js-apis-logs.md) - [Timer](js-apis-timer.md) - application - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) - Device Management - - [@ohos.batteryInfo ](js-apis-battery-info.md) - - [@ohos.batteryStatistics](js-apis-batteryStatistics.md) - - [@ohos.brightness](js-apis-brightness.md) - - [@ohos.deviceInfo](js-apis-device-info.md) - - [@ohos.distributedHardware.deviceManager](js-apis-device-manager.md) - - [@ohos.geoLocationManager](js-apis-geoLocationManager.md) - - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) - - [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md) - - [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md) - - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) - - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) - - [@ohos.multimodalInput.keyCode](js-apis-keycode.md) - - [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md) - - [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md) - - [@ohos.multimodalInput.pointer](js-apis-pointer.md) - - [@ohos.multimodalInput.touchEvent](js-apis-touchevent.md) - - [@ohos.power](js-apis-power.md) - - [@ohos.runningLock](js-apis-runninglock.md) - - [@ohos.sensor](js-apis-sensor.md) - - [@ohos.settings](js-apis-settings.md) - - [@ohos.stationary](js-apis-stationary.md) + - [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md) + - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) + - [@ohos.brightness (Screen Brightness)](js-apis-brightness.md) + - [@ohos.deviceInfo (Device Information)](js-apis-device-info.md) + - [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md) + - [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md) + - [@ohos.multimodalInput.inputConsumer (Input Consumer)](js-apis-inputconsumer.md) + - [@ohos.multimodalInput.inputDevice (Input Device)](js-apis-inputdevice.md) + - [@ohos.multimodalInput.inputDeviceCooperate (Screen Hopping)](js-apis-cooperate.md) + - [@ohos.multimodalInput.inputEvent (Input Event)](js-apis-inputevent.md) + - [@ohos.multimodalInput.inputEventClient (Key Event Injection)](js-apis-inputeventclient.md) + - [@ohos.multimodalInput.inputMonitor (Input Monitor)](js-apis-inputmonitor.md) + - [@ohos.multimodalInput.keyCode (Key Code)](js-apis-keycode.md) + - [@ohos.multimodalInput.keyEvent (Key Event)](js-apis-keyevent.md) + - [@ohos.multimodalInput.mouseEvent (Mouse Event)](js-apis-mouseevent.md) + - [@ohos.multimodalInput.pointer (Mouse Pointer)](js-apis-pointer.md) + - [@ohos.multimodalInput.touchEvent (Touch Event)](js-apis-touchevent.md) + - [@ohos.power (System Power Management)](js-apis-power.md) + - [@ohos.runningLock (Runninglock)](js-apis-runninglock.md) + - [@ohos.sensor (Sensor)](js-apis-sensor.md) + - [@ohos.settings (Data Item Settings)](js-apis-settings.md) + - [@ohos.stationary (Device Status Awareness Framework)](js-apis-stationary.md) - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - - [@ohos.thermal](js-apis-thermal.md) - - [@ohos.update](js-apis-update.md) - - [@ohos.usb](js-apis-usb.md) - - [@ohos.vibrator](js-apis-vibrator.md) + - [@ohos.systemParameterV9 (System Parameter)](js-apis-system-parameterV9.md) + - [@ohos.thermal (Thermal Management)](js-apis-thermal.md) + - [@ohos.update (Update)](js-apis-update.md) + - [@ohos.usbV9 (USB Management)](js-apis-usb.md) + - [@ohos.vibrator (Vibrator)](js-apis-vibrator.md) - Account Management - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - Custom Management - - [@ohos.configPolicy](js-apis-configPolicy.md) - - [@ohos.enterprise.deviceInfo](js-apis-enterprise-deviceInfo.md) - - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - - [@ohos.enterprise.adminManager](js-apis-enterprise-adminManager.md) - - [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md) + - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) + - [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md) + - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) + - [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md) - Language Base Class Library - [@ohos.buffer (Buffer)](js-apis-buffer.md) - - [@ohos.convertxml](js-apis-convertxml.md) - - [@ohos.process](js-apis-process.md) - - [@ohos.uri](js-apis-uri.md) - - [@ohos.url](js-apis-url.md) - - [@ohos.util](js-apis-util.md) - - [@ohos.util.ArrayList](js-apis-arraylist.md) - - [@ohos.util.Deque](js-apis-deque.md) - - [@ohos.util.HashMap](js-apis-hashmap.md) - - [@ohos.util.HashSet](js-apis-hashset.md) - - [@ohos.util.LightWeightMap](js-apis-lightweightmap.md) - - [@ohos.util.LightWeightSet](js-apis-lightweightset.md) - - [@ohos.util.LinkedList](js-apis-linkedlist.md) - - [@ohos.util.List](js-apis-list.md) - - [@ohos.util.PlainArray](js-apis-plainarray.md) - - [@ohos.util.Queue](js-apis-queue.md) - - [@ohos.util.Stack](js-apis-stack.md) - - [@ohos.util.TreeMap](js-apis-treemap.md) - - [@ohos.util.TreeSet](js-apis-treeset.md) - - [@ohos.util.Vector](js-apis-vector.md) - - [@ohos.worker](js-apis-worker.md) - - [@ohos.xml](js-apis-xml.md) + - [@ohos.convertxml (XML-to-JavaScript Conversion)](js-apis-convertxml.md) + - [@ohos.process (Obtaining Process Information)](js-apis-process.md) + - [@ohos.taskpool (Using the Task Pool)](js-apis-taskpool.md) + - [@ohos.uri (URI String Parsing)](js-apis-uri.md) + - [@ohos.url (URL String Parsing)](js-apis-url.md) + - [@ohos.util (util)](js-apis-util.md) + - [@ohos.util.ArrayList (Linear Container ArrayList)](js-apis-arraylist.md) + - [@ohos.util.Deque (Linear Container Deque)](js-apis-deque.md) + - [@ohos.util.HashMap (Nonlinear Container HashMap)](js-apis-hashmap.md) + - [@ohos.util.HashSet (Nonlinear Container HashSet)](js-apis-hashset.md) + - [@ohos.util.LightWeightMap (Nonlinear Container LightWeightMap)](js-apis-lightweightmap.md) + - [@ohos.util.LightWeightSet (Nonlinear Container LightWeightSet)](js-apis-lightweightset.md) + - [@ohos.util.LinkedList (Linear Container LinkedList)](js-apis-linkedlist.md) + - [@ohos.util.List (Linear Container List)](js-apis-list.md) + - [@ohos.util.PlainArray (Nonlinear Container PlainArray)](js-apis-plainarray.md) + - [@ohos.util.Queue (Linear Container Queue)](js-apis-queue.md) + - [@ohos.util.Stack (Linear Container Stack)](js-apis-stack.md) + - [@ohos.util.TreeMap (Nonlinear Container TreeMap)](js-apis-treemap.md) + - [@ohos.util.TreeSet (Nonlinear Container TreeSet)](js-apis-treeset.md) + - [@ohos.util.Vector (Linear Container Vector)](js-apis-vector.md) + - [@ohos.worker (Worker Startup)](js-apis-worker.md) + - [@ohos.xml (XML Parsing and Generation)](js-apis-xml.md) - Test - - [@ohos.application.testRunner](js-apis-application-testRunner.md) - - [@ohos.uitest](js-apis-uitest.md) + - [@ohos.application.testRunner (TestRunner)](js-apis-application-testRunner.md) + - [@ohos.uitest (UiTest)](js-apis-uitest.md) - APIs No Longer Maintained - - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - - [@ohos.bundle](js-apis-Bundle.md) - - [@ohos.bundle.innerBundleManager](js-apis-Bundle-InnerBundleManager.md) - - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - - [@ohos.bytrace](js-apis-bytrace.md) + - [@ohos.backgroundTaskManager (Background Task Management)](js-apis-backgroundTaskManager.md) + - [@ohos.bundle (Bundle)](js-apis-Bundle.md) + - [@ohos.bundle.innerBundleManager (innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) + - [@ohos.bundleState (Device Usage Statistics)](js-apis-deviceUsageStatistics.md) + - [@ohos.bytrace (Performance Tracing)](js-apis-bytrace.md) - [@ohos.data.distributedData (Distributed Data Management)](js-apis-distributed-data.md) - [@ohos.data.storage (Lightweight Data Storage)](js-apis-data-storage.md) - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md) - - [@ohos.distributedBundle](js-apis-Bundle-distributedBundle.md) + - [@ohos.distributedBundle (Distributed Bundle Management)](js-apis-Bundle-distributedBundle.md) - [@ohos.document (File Operation)](js-apis-document.md) - - [@ohos.geolocation](js-apis-geolocation.md) - - [@ohos.hiAppEvent](js-apis-hiappevent.md) - - [@ohos.prompt](js-apis-prompt.md) - - [@ohos.reminderAgent](js-apis-reminderAgent.md) - - [@ohos.systemParameter](js-apis-system-parameter.md) - - [@ohos.usb](js-apis-usb-deprecated.md) - - [@system.app](js-apis-system-app.md) - - [@system.battery](js-apis-system-battery.md) - - [@system.bluetooth](js-apis-system-bluetooth.md) - - [@system.brightness](js-apis-system-brightness.md) - - [@system.configuration](js-apis-system-configuration.md) - - [@system.device](js-apis-system-device.md) - - [@system.fetch](js-apis-system-fetch.md) - - [@system.file](js-apis-system-file.md) - - [@system.geolocation](js-apis-system-location.md) - - [@system.mediaquery](js-apis-system-mediaquery.md) - - [@system.network](js-apis-system-network.md) - - [@system.notification](js-apis-system-notification.md) - - [@system.package](js-apis-system-package.md) - - [@system.prompt](js-apis-system-prompt.md) - - [@system.request](js-apis-system-request.md) - - [@system.router](js-apis-system-router.md) - - [@system.sensor](js-apis-system-sensor.md) - - [@system.storage](js-apis-system-storage.md) - - [@system.vibrator](js-apis-system-vibrate.md) + - [@ohos.fileio (File Management)](js-apis-fileio.md) + - [@ohos.geolocation (Geolocation)](js-apis-geolocation.md) + - [@ohos.hiAppEvent (Application Event Logging)](js-apis-hiappevent.md) + - [@ohos.prompt (Prompt)](js-apis-prompt.md) + - [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md) + - [@ohos.statfs (statfs)](js-apis-statfs.md) + - [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md) + - [@ohos.usb (USB Management)](js-apis-usb-deprecated.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) + - [@system.brightness (Screen Brightness)](js-apis-system-brightness.md) + - [@system.configuration (Application Configuration)](js-apis-system-configuration.md) + - [@system.device (Device Information)](js-apis-system-device.md) + - [@system.fetch (Data Request)](js-apis-system-fetch.md) + - [@system.file (File Storage)](js-apis-system-file.md) + - [@system.geolocation (Geographic Location)](js-apis-system-location.md) + - [@system.mediaquery (Media Query)](js-apis-system-mediaquery.md) + - [@system.network (Network State)](js-apis-system-network.md) + - [@system.notification (Notification)](js-apis-system-notification.md) + - [@system.package (Bundle Management)](js-apis-system-package.md) + - [@system.prompt (Prompt)](js-apis-system-prompt.md) + - [@system.request (Upload and Download)](js-apis-system-request.md) + - [@system.router (Page Routing)](js-apis-system-router.md) + - [@system.sensor (Sensor)](js-apis-system-sensor.md) + - [@system.storage (Data Storage)](js-apis-system-storage.md) + - [@system.vibrator (Vibrator)](js-apis-system-vibrate.md) - bundle - [abilityInfo](js-apis-bundle-AbilityInfo.md) - [applicationInfo](js-apis-bundle-ApplicationInfo.md) diff --git a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md index 7d00454ea5ce5b0051c2fff6856f9653be89b455..846aefcd37eff322c5d5aa215bad3f812da6ed4d 100644 --- a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -224,7 +224,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba ```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { @@ -293,7 +293,7 @@ Requests a continuous task from the system. This API uses a promise to return th ```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ @@ -445,7 +445,6 @@ particleAbility.disconnectAbility(connId).then((data) => { }).catch((error) => { console.log('particleAbilityTest result errCode : ' + error.code) }); - ``` ## particleAbility.disconnectAbility @@ -491,10 +490,10 @@ var connId = particleAbility.connectAbility( onFailed: onFailedCallback, }, ); -var result = particleAbility.disconnectAbility(connId).then((data) => { - console.log(" data: " + data); -}).catch((error) => { - console.log('particleAbilityTest result errCode : ' + error.code) + +particleAbility.disconnectAbility(connId, (err) => { + console.log("particleAbilityTest disconnectAbility err====>" + + ("json err=") + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md index 88aab2d4026afac5edaf8c3c7ff58033976e3e66..388761074dd2e6e53e2ca4ee621a6875f292996a 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -9,7 +9,7 @@ The **Configuration** module defines environment change information. ## Modules to Import ```ts -import Configuration from '@ohos.app.ability.Configuration' +import Configuration from '@ohos.app.ability.Configuration'; ``` **System capability**: SystemCapability.Ability.AbilityBase @@ -26,30 +26,30 @@ import Configuration from '@ohos.app.ability.Configuration' For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file. **Example** - + ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; - export default class EntryAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - let envCallback = { - onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) - let language = config.language; - let colorMode = config.colorMode; - let direction = config.direction; - let screenDensity = config.screenDensity; - let displayId = config.displayId; - let hasPointerDevice = config.hasPointerDevice; + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + try { + let applicationContext = this.context.getApplicationContext(); + let callbackId = applicationContext.on("environment", envCallback); + console.log("callbackId: " + callbackId); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); } - }; - try { - let applicationContext = this.context.getApplicationContext(); - let callbackId = applicationContext.on("environment", envCallback); - console.log("callbackId: " + callbackId); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } } - } +} ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md index d61484f86b36bafd74ded1860272ac1a4b86089a..8b314c792e584149219e7baf46e05cc9cdb9033f 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -124,7 +124,7 @@ Updates a widget. This API uses an asynchronous callback to return the result. **Example** ```ts -import formBindingData from '@ohos.application.formBindingData'; +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let formId = "12400633174999288"; @@ -173,7 +173,7 @@ Updates a widget. This API uses a promise to return the result. **Example** ```ts -import formBindingData from '@ohos.application.formBindingData'; +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let formId = "12400633174999288"; @@ -349,7 +349,7 @@ Requests to publish a widget carrying data to the widget host. This API uses an **Example** ```ts -import formBindingData from '@ohos.application.formBindingData'; +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let want = { diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index efba928564b2c9aa34e35b2af7485674ea99274d..6e96d0194a712340cd63a5510a190ea971d04e01 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -8,14 +8,17 @@ This module provides the following common ability-related functions: - [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. > **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 are deprecated since API version 9. You are advised to use [@ohos.app.ability.UIAbility (UIAbility)](js-apis-app-ability-uiAbility.md) instead. +> +> 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 can be used only in the stage model. ## Modules to Import ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.application.Ability'; ``` ## Attributes @@ -72,7 +75,7 @@ Called when a **WindowStage** is created for this ability. **Example** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); } @@ -91,7 +94,7 @@ Called when the **WindowStage** is destroyed for this ability. **Example** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageDestroy() { console.log('onWindowStageDestroy'); } @@ -116,7 +119,7 @@ Called when the **WindowStage** is restored during the migration of this ability **Example** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); } @@ -133,9 +136,9 @@ Called when this ability is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onDestroy() { console.log('onDestroy'); } @@ -152,9 +155,9 @@ Called when this ability is switched from the background to the foreground. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onForeground() { console.log('onForeground'); } @@ -171,9 +174,9 @@ Called when this ability is switched from the foreground to the background. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onBackground() { console.log('onBackground'); } @@ -202,10 +205,11 @@ Called to save data during the ability migration preparation process. | AbilityConstant.OnContinueResult | Continuation result.| **Example** - + ```ts - import AbilityConstant from "@ohos.application.AbilityConstant" - class myAbility extends Ability { + import AbilityConstant from "@ohos.app.ability.AbilityConstant"; + + export default class EntryAbility extends UIAbility { onContinue(wantParams) { console.log('onContinue'); wantParams["myData"] = "my1234567"; @@ -231,9 +235,9 @@ Called when a new Want is passed in and this UIAbility is started again. | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); @@ -256,9 +260,9 @@ Called when the global configuration is updated. | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, language:' + config.language); } @@ -280,9 +284,9 @@ Dumps client information. | params | Array\ | Yes| Parameters in the form of a command.| **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { dump(params) { console.log('dump, params:' + JSON.stringify(params)); return ["params"] @@ -305,9 +309,9 @@ Called when the system has decided to adjust the memory level. For example, this | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| **Example** - + ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); } @@ -338,9 +342,9 @@ Called when the framework automatically saves the ability state in the case of a **Example** ```ts -import AbilityConstant from '@ohos.application.AbilityConstant' +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; -class myAbility extends Ability { +export default class EntryAbility extends UIAbility { onSaveState(reason, wantParam) { console.log('onSaveState'); wantParam["myData"] = "my1234567"; @@ -349,8 +353,6 @@ class myAbility extends Ability { } ``` - - ## Caller Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). @@ -387,7 +389,7 @@ Sends sequenceable data to the target ability. | 16000050 | Internal Error. | **Example** - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -545,7 +547,6 @@ Releases the caller interface of the target ability. | 16000050 | Internal Error. | **Example** - ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -589,7 +590,7 @@ Registers a callback that is invoked when the stub on the target ability is disc | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| **Example** - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -716,7 +717,6 @@ Deregisters a caller notification callback, which is invoked when the target abi **Example** - ```ts import UIAbility from '@ohos.app.ability.UIAbility'; diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index ae72afeca2e3214d00a785c0639793e8df47d715..4dd701b54e2924b5ec1b928e4c0f5ad8a8d3f05f 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -9,7 +9,7 @@ The **AbilityDelegatorRegistry** module provides APIs for storing the global reg ## Modules to Import ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; ``` ## AbilityLifecycleState diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index 040448220bb9da59779f0d449c43a59d8ab920bd..5e29491014719ab9e5cf09dd976ed71f2b449c6e 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -156,7 +156,7 @@ Called when an ability is continued on another device. **Example** ```ts -import AbilityStage from "@ohos.application.AbilityStage"; +import AbilityStage from "@ohos.app.ability.AbilityStage"; var lifecycleId; diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index e509a1b5d13a2d0d20b8d6dee4efee9487c5ee92..b734efe10a8dcd445e7a51db1509a0c1d4bedc5f 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -10,7 +10,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ## Modules to Import ```ts -import abilityManager from '@ohos.application.abilityManager' +import abilityManager from '@ohos.application.abilityManager'; ``` ## AbilityState @@ -38,7 +38,7 @@ Updates the configuration. This API uses an asynchronous callback to return the **Permission required**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Ability.AbilityRuntime.Core - + **Parameters** | Name | Type | Mandatory | Description | @@ -176,7 +176,7 @@ abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { getExtensionRunningInfos(upperLimit: number): Promise\> Obtains the extension running information. This API uses a promise to return the result. - + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -232,7 +232,7 @@ abilityManager.getTopAbility((err,data) => { getTopAbility(): Promise\; Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. - + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** 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 a47e3e8908f69f5515beab95cea6f74351719a77..2a665f5febb82481993674c7501279b838ea05db 100644 --- a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -1,4 +1,4 @@ -# @ohos.application.AccessibilityExtensionAbility +# @ohos.application.AccessibilityExtensionAbility (AccessibilityExtensionAbility) The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework. diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md index 591f5ec77a34ef2eb36979a00b9553241b33ddb3..a31f9c88969155dc1f0fc7717fd2aa6267ac3180 100644 --- a/en/application-dev/reference/apis/js-apis-application-appManager.md +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -420,7 +420,7 @@ Deregisters the application state observer. This API uses a promise to return th getForegroundApplications(callback: AsyncCallback\>): void; Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). - + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 81870036a845c61f852f671616f63c12f92851b8..82d964e100a1bda94ad0f6f470ae29895d2acde5 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -26,7 +26,6 @@ import Configuration from '@ohos.application.Configuration' For details about the fields, see the **ohos.application.Configuration.d.ts** file. **Example** - ```ts import hilog from '@ohos.hilog'; import UIAbility from '@ohos.app.ability.UIAbility'; diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md index c1eaa2d35e90966795e4b98f4b75cffc0570e855..2fbd840782cefe200f53d6df090bff9220b52c49 100644 --- a/en/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -8,7 +8,7 @@ The **ErrorManager** module provides APIs for registering and deregistering erro ## Modules to Import ```ts -import errorManager from '@ohos.application.errorManager' +import errorManager from '@ohos.application.errorManager'; ``` ## ErrorManager.registerErrorObserver @@ -20,7 +20,7 @@ Registers an error observer. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| @@ -45,7 +45,7 @@ Deregisters an error observer. This API uses an asynchronous callback to return **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | Yes| Numeric code of the observer.| @@ -74,7 +74,7 @@ Deregisters an error observer. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | Yes| Numeric code of the observer.| diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md index 5fbc52c95dc9e573947fb9820f00100a76a06f22..e82f3f2f199c103a6b2ee6d1f15c54144ece2036 100644 --- a/en/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -48,7 +48,7 @@ Creates a **FormBindingData** object. **Example** ```ts -import formBindingData from @ohos.application.formBindingData; +import formBindingData from '@ohos.application.formBindingData'; import fs from '@ohos.file.fs'; try { diff --git a/en/application-dev/reference/apis/js-apis-application-formProvider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md index 4d604ff7295eb9903d450bc96f9c00fde253ee11..15428096d42ef9321249dc924e3569bbe4c4809a 100644 --- a/en/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -94,7 +94,7 @@ Updates a widget. This API uses an asynchronous callback to return the result. **Example** ```ts - import formBindingData from '@ohos.application.formBindingData'; + import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let formId = "12400633174999288"; diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 5552792aadadd04fca72d4fe88ffdfc8219b3ec9..86fc2ceeebebd248a2e51f6454ea74dbc2f80602 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -1001,7 +1001,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; // WantAgentInfo object let wantAgentInfo = { @@ -1066,7 +1066,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; // WantAgentInfo object let wantAgentInfo = { @@ -2222,7 +2222,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; controller.getLaunchAbility().then((agent) => { console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`); @@ -2257,7 +2257,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err **Example** ```js -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; controller.getLaunchAbility(function (err, agent) { if (err) { diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 6080d2c9bc52e30b6fa987f9cb65ea9b42a28024..775bc6665152c9d2870e28f677022d8734a551fe 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -173,7 +173,7 @@ FA model: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { @@ -207,7 +207,7 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { @@ -270,7 +270,7 @@ FA model: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ @@ -299,7 +299,7 @@ Stage model: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index d227b545aa9f5ad3b719b2da86800cab6ccc5084..274836333aa773d32a386ad22b03706e890859c7 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,6 +1,7 @@ # @ohos.util.Deque (Linear Container Deque) > **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. Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects: diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index f9a998f37ca17b4d4c70342bc648ed519fbe1652..813b44ccf0088142fccbc22f3087aede4669f2bc 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# @ohos.deviceUsageStatistics (Device Usage Statistics) +# @ohos.bundleState (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -454,6 +454,20 @@ Provides the usage duration information of an application. | infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.| | infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.| +### merge(deprecated) + +merge(toMerge: BundleStateInfo): void + +Merges the device usage statistics of applications with the same bundle name. + +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| toMerge | [BundleStateInfo](#bundlestateinfo) | Yes| Device usage statistics to merge.| + ## BundleActiveState Provides information about an application event. diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index ad4f7e19a9fd40b82684c0acc11a458073bbb16b..70aefed8b0d382421459175f3b19e10304917c3b 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -10,7 +10,7 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**. ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` @@ -35,13 +35,13 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -75,13 +75,13 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -92,8 +92,6 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { }); ``` - - ### removeAbilityMonitor9+ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; @@ -112,13 +110,13 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -129,8 +127,6 @@ abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { }); ``` - - ### removeAbilityMonitor9+ removeAbilityMonitor(monitor: AbilityMonitor): Promise\; @@ -154,13 +150,13 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re - Example ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -171,8 +167,6 @@ abilityDelegator.removeAbilityMonitor(monitor).then(() => { }); ``` - - ### waitAbilityMonitor9+ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; @@ -191,13 +185,13 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -227,14 +221,14 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo **Example** ```ts -var abilityDelegator; -var timeout = 100; +let abilityDelegator; +let timeout = 100; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -271,13 +265,13 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { abilityName: "abilityname", onAbilityCreate: onAbilityCreateCallback } @@ -288,8 +282,6 @@ abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { }); ``` - - ### getAppContext9+ getAppContext(): Context; @@ -307,14 +299,12 @@ Obtains the application context. **Example** ```ts -var abilityDelegator; +let abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -var context = abilityDelegator.getAppContext(); +let context = abilityDelegator.getAppContext(); ``` - - ### getAbilityState9+ getAbilityState(ability: UIAbility): number; @@ -338,20 +328,18 @@ Obtains the lifecycle state of an ability. **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { console.info("getCurrentTopAbility callback"); ability = data; - var state = abilityDelegator.getAbilityState(ability); + let state = abilityDelegator.getAbilityState(ability); console.info("getAbilityState" + state); }); ``` - - ### getCurrentTopAbility9+ getCurrentTopAbility(callback: AsyncCallback\): void; @@ -369,8 +357,8 @@ Obtains the top ability of this application. This API uses an asynchronous callb **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -379,8 +367,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### getCurrentTopAbility9+ getCurrentTopAbility(): Promise\; @@ -398,8 +384,8 @@ Obtains the top ability of this application. This API uses a promise to return t **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility().then((data : any) => { @@ -408,8 +394,6 @@ abilityDelegator.getCurrentTopAbility().then((data : any) => { }); ``` - - ### startAbility9+ startAbility(want: Want, callback: AsyncCallback\): void; @@ -428,8 +412,8 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts -var abilityDelegator; -var want = { +let abilityDelegator; +let want = { bundleName: "bundleName", abilityName: "abilityName" }; @@ -440,8 +424,6 @@ abilityDelegator.startAbility(want, (err : any, data : any) => { }); ``` - - ### startAbility9+ startAbility(want: Want): Promise\; @@ -465,8 +447,8 @@ Starts an ability. This API uses a promise to return the result. **Example** ```ts -var abilityDelegator; -var want = { +let abilityDelegator; +let want = { bundleName: "bundleName", abilityName: "abilityName" }; @@ -477,8 +459,6 @@ abilityDelegator.startAbility(want).then((data: any) => { }); ``` - - ### doAbilityForeground9+ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void; @@ -497,8 +477,8 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -510,8 +490,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### doAbilityForeground9+ doAbilityForeground(ability: UIAbility): Promise\; @@ -535,8 +513,8 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -548,8 +526,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### doAbilityBackground9+ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void; @@ -568,8 +544,8 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -581,8 +557,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### doAbilityBackground9+ doAbilityBackground(ability: UIAbility): Promise\; @@ -606,8 +580,8 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { @@ -619,8 +593,6 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { }); ``` - - ### printSync9+ printSync(msg: string): void; @@ -638,15 +610,13 @@ Prints log information to the unit test console. **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.printSync(msg); ``` - - ### print print(msg: string, callback: AsyncCallback\): void; @@ -665,8 +635,8 @@ Prints log information to the unit test console. This API uses an asynchronous c **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.print(msg, (err : any) => { @@ -674,8 +644,6 @@ abilityDelegator.print(msg, (err : any) => { }); ``` - - ### print print(msg: string): Promise\; @@ -699,8 +667,8 @@ Prints log information to the unit test console. This API uses a promise to retu **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.print(msg).then(() => { @@ -708,8 +676,6 @@ abilityDelegator.print(msg).then(() => { }); ``` - - ### executeShellCommand executeShellCommand(cmd: string, callback: AsyncCallback\): void; @@ -728,8 +694,8 @@ Executes a shell command. This API uses an asynchronous callback to return the r **Example** ```ts -var abilityDelegator; -var cmd = "cmd"; +let abilityDelegator; +let cmd = "cmd"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { @@ -737,8 +703,6 @@ abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { }); ``` - - ### executeShellCommand executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void; @@ -758,9 +722,9 @@ Executes a shell command with the timeout period specified. This API uses an asy **Example** ```ts -var abilityDelegator; -var cmd = "cmd"; -var timeout = 100; +let abilityDelegator; +let cmd = "cmd"; +let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { @@ -768,8 +732,6 @@ abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { }); ``` - - ### executeShellCommand executeShellCommand(cmd: string, timeoutSecs?: number): Promise\; @@ -794,9 +756,9 @@ Executes a shell command with the timeout period specified. This API uses a prom **Example** ```ts -var abilityDelegator; -var cmd = "cmd"; -var timeout = 100; +let abilityDelegator; +let cmd = "cmd"; +let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { @@ -804,8 +766,6 @@ abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { }); ``` - - ### finishTest9+ finishTest(msg: string, code: number, callback: AsyncCallback\): void; @@ -825,8 +785,8 @@ Finishes the test and prints log information to the unit test console. This API **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.finishTest(msg, 0, (err : any) => { @@ -834,8 +794,6 @@ abilityDelegator.finishTest(msg, 0, (err : any) => { }); ``` - - ### finishTest9+ finishTest(msg: string, code: number): Promise\; @@ -860,8 +818,8 @@ Finishes the test and prints log information to the unit test console. This API **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = "msg"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.finishTest(msg, 0).then(() => { @@ -887,9 +845,9 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -900,8 +858,6 @@ abilityDelegator.addAbilityStageMonitor(monitor, (err : any) => { }); ``` - - ### addAbilityStageMonitor9+ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; @@ -925,9 +881,9 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -956,9 +912,9 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -969,8 +925,6 @@ abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => { }); ``` - - ### removeAbilityStageMonitor9+ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; @@ -994,9 +948,9 @@ Removes an **AbilityStageMonitor** object from the application memory. This API **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -1025,13 +979,13 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -1066,13 +1020,13 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } @@ -1102,14 +1056,14 @@ Waits a period of time for an **AbilityStage** instance that matches the conditi **Example** ```ts -var abilityDelegator; -var timeout = 100; +let abilityDelegator; +let timeout = 100; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); } -var monitor = { +let monitor = { moduleName: "moduleName", srcEntrance: "srcEntrance", } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index a5f131c3e02071f3d55cbfdc73955ffef42889d3..737a5bc8c3ba7daa37af06f92a843fea27b40b8a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -26,7 +26,7 @@ Describes the ability delegator arguments. **Example** ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; var args = AbilityDelegatorRegistry.getArguments(); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md index d8726205b8caec547f270e8efe6472e37cd99eb4..3185bd98b51260135e6b3bf1524d6bab8187d2bf 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -30,7 +30,7 @@ Describes an ability monitor. **Example** ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 62b1f7e1fae204f2e6b1f6dcdc76521da3c51777..e076913ed7dda35586084acdad77df1e94720e83 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -28,7 +28,8 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; +import abilitymanager from '@ohos.app.ability.abilityManager'; + abilitymanager.getAbilityRunningInfos((err,data) => { console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); for (let i = 0; i < data.length; i++) { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 79f750797c12bfd9c323e2f613650c016ea2930b..5237e134c8500cec81840e14c7d5153ee59d27a0 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -14,7 +14,8 @@ This module provides APIs for accessing a specific ability stage. You can use th The ability stage context is obtained through an **AbilityStage** instance. ```ts -import AbilityStage from '@ohos.application.AbilityStage'; +import AbilityStage from '@ohos.app.ability.AbilityStage'; + class MyAbilityStage extends AbilityStage { onCreate() { let abilityStageContext = this.context; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index 76a4ae2e425ce91acb0f79d22889cba231809c26..a8b67e09b0d6809cf9b79e08e09f466a62d46b44 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -11,7 +11,7 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta **Example** ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let monitor = { moduleName: "feature_as1", diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index e6d3137582ee3b485e4a342a4a5a3b6b5473ed32..d8e4688d78931edf9018eed4c5a092a84f9d15e8 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -16,7 +16,7 @@ The **ApplicationStateObserver** module defines an observer to listen for applic **Example** ```ts -import appManager from "@ohos.application.appManager" +import appManager from "@ohos.app.ability.appManager"; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index a855d9577c9ef364caa7436a89983ca58d320d3c..85fff22533b515eba4bb36c274e2d8782f28a356 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -31,8 +31,9 @@ To adapt to devices with different performance, an application provides three mo Define a **ServiceExtension** with the same name for the three modules. ```ts -import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' -import Want from '@ohos.application.Want' +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility'; +import Want from '@ohos.app.ability.Want'; + export default class TheServiceExtension extends ServiceExtension { onCreate(want:Want) { console.log('ServiceAbility onCreate, want: ' + want.abilityName); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processData.md b/en/application-dev/reference/apis/js-apis-inner-application-processData.md index c6e91944c5ed16800f3a2a7785de5a5e60dc623a..41401037a32bb0231b721bb470dec7f2e7a3d175 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -17,7 +17,7 @@ The **ProcessData** module defines process data. If a lifecycle change listener **Example** ```ts -import appManager from '@ohos.application.appManager' +import appManager from '@ohos.app.ability.appManager'; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index 0652791f728de12c144459146287ecbbb680480e..16dd713d9bf284ce001df342c4a963920977f112 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -23,7 +23,7 @@ The process running information is obtained by using [getProcessRunningInfos](js **Example** ```ts -import appManager from '@ohos.application.appManager'; +import appManager from '@ohos.app.ability.appManager'; appManager.getProcessRunningInfos().then((data) => { console.log('success:' + JSON.stringify(data)); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 51b10659d38d55686ced548c624798d77391f102..8db813f610095cb4b19412291f34f3bf53c5dc57 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -19,7 +19,7 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio **Example** ```ts -import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; +import AbilityDelegatorRegistry from "@ohos.app.ability.abilityDelegatorRegistry"; let abilityDelegator; let cmd = "cmd"; diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md index d96cd241e7e4c198497712f7fa75c6990b847f6e..a61dd42ece2d52f0da53dd51f33770483b37757e 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @@ -1,4 +1,4 @@ -# @ohos.inputmethodextensionability (InputMethodExtensionAbility) +# @ohos.InputMethodExtensionAbility (InputMethodExtensionAbility) The **InputMethodExtensionAbility** module provides APIs for developing input methods and managing their lifecycles. @@ -9,7 +9,7 @@ The **InputMethodExtensionAbility** module provides APIs for developing input me ## Modules to Import ```js -import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; +import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility'; ``` ## Attributes diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index b33db13faa840a1660a42e612ef5a4d523241877..37dadd8e2ce6cd3e7c2f33ab05154f20b52cf844 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -1,4 +1,4 @@ -# @ohos.inputmethodextensioncontext (InputMethodExtensionContext) +# @ohos.InputMethodExtensionContext (InputMethodExtensionContext) The **InputMethodExtensionContext** module, inherited from **ExtensionContext**, provides context for **InputMethodExtension** abilities. @@ -11,7 +11,7 @@ You can use the APIs of this module to start, terminate, connect, and disconnect ## Modules to Import ``` -import InputMethodExtensionContext from '@ohos.inputmethodextensioncontext'; +import InputMethodExtensionContext from '@ohos.InputMethodExtensionContext'; ``` ## Usage @@ -19,7 +19,7 @@ import InputMethodExtensionContext from '@ohos.inputmethodextensioncontext'; Before using the **InputMethodExtensionContext** module, you must define a child class that inherits from **InputMethodExtensionAbility**. ```js -import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; +import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility'; class EntryAbility extends InputMethodExtensionAbility { onCreate() { let context = this.context; @@ -66,9 +66,9 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```js -this.context.destroy().then((data) => { - console.log('success:' + JSON.stringify(data)); +this.context.destroy().then(() => { + console.log('Succeed in destroying context.'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('Failed to destroy context: ' + JSON.stringify(error)); }); ``` 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 1b5f9dfb662145fe2220d1d244cb3ac91dce9698..8f1a3fddc9344bcf5d04a526b5c70a77837e29d0 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md @@ -1,6 +1,6 @@ -# @ohos.inputmethodsubtype (Input Method Subtype) +# @ohos.InputMethodSubtype (Input Method Subtype) -The **inputMethodSubtype** module provides APIs for managing the attributes of input method subtypes. Different attribute settings result in different subtypes. +The **InputMethodSubtype** module provides APIs for managing the attributes of input method subtypes. Different attribute settings result in different subtypes. > **NOTE** > @@ -9,7 +9,7 @@ The **inputMethodSubtype** module provides APIs for managing the attributes of i ## Modules to Import ``` -import inputMethodEngine from '@ohos.inputMethodSubtype'; +import InputMethodSubtype from '@ohos.InputMethodSubtype'; ``` ## Attributes diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index e7ff69abcf62ef6957875badde01857b05087659..bdc166cd9d3b5a60636214b72311a2c8368c8d6d 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,4 +1,4 @@ -# @ohos.inputmethod (Input Method Framework) +# @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. @@ -10,7 +10,7 @@ The **inputMethod** module provides an input method framework, which can be used ## Modules to Import ```js -import inputMethod from '@ohos.inputmethod'; +import inputMethod from '@ohos.inputMethod'; ``` ## Constants8+ @@ -111,7 +111,7 @@ Switches to another input method. This API uses an asynchronous callback to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | target | [InputMethodProperty](#inputmethodproperty8) | Yes| Input method 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. | +| 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** @@ -160,15 +160,15 @@ Switches to another input method. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -|target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + |target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| **Return value** -| Type | Description | -| ----------------------------------------- | ---------------------------- | -| Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| + | Type | Description | + | ----------------------------------------- | ---------------------------- | + | Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| **Error codes** @@ -240,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.| -| 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. | +| 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** @@ -376,7 +376,7 @@ Switches to a specified subtype of a specified input method. This API uses an as | -------- | -------- | -------- | -------- | |inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| |inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| 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. | +| 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** @@ -557,7 +557,7 @@ Ends this input session. The invoking of this API takes effect only after the in | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| 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. | +| 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** @@ -643,7 +643,7 @@ Shows this soft keyboard. This API must be used with the input text box and work | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | +| 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** @@ -715,7 +715,7 @@ Hides this soft keyboard. This API must be used with the input text box and work | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | +| 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** @@ -789,7 +789,7 @@ Ends this input session. The invoking of this API takes effect only after the in | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| 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. | +| 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.| **Example** @@ -1157,7 +1157,7 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| 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. | +| 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** @@ -1291,7 +1291,7 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index f5becc73ca2132e8864c3bd8b8a9830312b96188..7cfb76e570ae3faf57fdf3ff31cd6cbcb9103eae 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) +# @ohos.inputMethodEngine (Input Method Service) -The **inputMethodEngine** module streamlines the interaction between input methods and applications. By calling APIs of this module, applications can be bound to input method services to accept text input through the input methods, request the keyboard to display or hide, listen for the input method status, and much more. +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. > **NOTE** > @@ -9,7 +9,7 @@ The **inputMethodEngine** module streamlines the interaction between input metho ## Modules to Import ``` -import inputMethodEngine from '@ohos.inputmethodengine'; +import inputMethodEngine from '@ohos.inputMethodEngine'; ``` ## Constants @@ -203,7 +203,7 @@ Enables listening for a keyboard event. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** indicates the keyboard display event.
- The value **'keyboardHide'** indicates the keyboard hiding event. | +| type | string | Yes | Listening type.
- The value **'keyboardShow'** indicates the keyboard display event.
- The value **'keyboardHide'** indicates the keyboard hiding event.| | callback | () => void | Yes | Callback used to return the result. | **Example** @@ -418,7 +418,7 @@ Disables listening for a keyboard event. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'keyboardShow'** indicates the keyboard display event.
The value **'keyboardHide'** indicates the keyboard hiding event.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** indicates the keyboard display event.
- The value **'keyboardHide'** indicates the keyboard hiding event.| | callback | () => void | No | Callback used to return the result. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md index 505c29ae0ef6cc18404767eaa4a4b4ac88296651..3180bf582281372886331d6d37ff059cad79e1db 100644 --- a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -1,4 +1,4 @@ -# @ohos.bundle.launcherBundleManager +# @ohos.bundle.launcherBundleManager (launcherBundleManager) The **bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 0e745d749c0967cd515a91356750f7de0703ace7..bc51f25fbb6c54f7fadc6bdd05533113a1c7254c 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -389,7 +389,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirst method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **Example** @@ -424,7 +424,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message| | -------- | -------- | | 10200011 | The removeLast method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **Example** @@ -504,7 +504,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirstFound method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **Example** @@ -544,7 +544,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | ID| Error Message| | -------- | -------- | | 10200011 | The removeLastFound method cannot be bound. | -| 10200010 | The container is empty. | +| 10200010 | Container is empty. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 29b20c42950323df2346d817922f178d71d11a80..3f9387defec0e68dc6414fdb4b21c5bca9cb1490 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,4 +1,4 @@ -# @ohos.reminderAgent (reminderAgent) +# @ohos.reminderAgent (Reminder Agent) The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index ab3d0f116871392e6cdbf0c004b9c418c5660e16..f443c028e40072e8b402f93b54be1e9ecfdc0842 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,4 +1,4 @@ -# @ohos.reminderAgentManager (reminderAgentManager) +# @ohos.reminderAgentManager (Reminder Agent Management) The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index d3a0eeb30ea75a3109b6917d50b7b1d24cdd2fb4..ff95e4da7e13247791af681c793b5aade7ba84d3 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -2,7 +2,8 @@ The **request** module provides applications with basic upload, download, and background transmission agent capabilities. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -77,7 +78,7 @@ The table below lists the causes of download pause that may be returned by [getT | PAUSED_QUEUED_FOR_WIFI7+ | number | 0 | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| | PAUSED_WAITING_FOR_NETWORK7+ | number | 1 | Download paused due to a network connection problem, for example, network disconnection.| | PAUSED_WAITING_TO_RETRY7+ | number | 2 | Download paused and then retried.| -| PAUSED_BY_USER9+ | number | 3 | The user paused the session. | +| PAUSED_BY_USER9+ | number | 3 | The user paused the session.| | PAUSED_UNKNOWN7+ | number | 4 | Download paused due to unknown reasons.| ### Download Task Status Codes @@ -378,6 +379,8 @@ Uploads files. This API uses an asynchronous callback to return the result. Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile9+](#requestuploadfile9) in promise mode or [request.uploadFile9+](#requestuploadfile9-1) in callback mode. + + ### on('progress') on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void @@ -399,8 +402,8 @@ Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes| Size of the uploaded files, in bytes. | -| totalSize | number | Yes| Total size of the files to upload, in bytes. | +| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to upload, in bytes.| **Example** @@ -504,12 +507,12 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| | callback | function | No| Callback for the upload progress event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes| Size of the uploaded files, in bytes. | -| totalSize | number | Yes| Total size of the files to upload, in bytes. | +| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to upload, in bytes.| **Example** @@ -764,7 +767,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | filename | string | Yes| File name in the header when **multipart** is used.| | name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| -| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt

internal://cache/path/to/file.txt | +| uri | string | Yes| Local path for storing files.
Only the **internal** protocol type is supported. In the value, **internal://cache/** is mandatory. Example:
internal://cache/path/to/file.txt | | type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| @@ -1047,12 +1050,12 @@ Subscribes to a download event. This API uses an asynchronous callback to return | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| | callback | function | Yes| Callback for the download progress event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes| Size of the downloaded files, in bytes. | -| totalSize | number | Yes| Total size of the files to download, in bytes. | +| receivedSize | number | Yes| Size of the downloaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to download, in bytes.| **Example** @@ -1085,8 +1088,8 @@ Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes| Size of the downloaded files, in bytes. | -| totalSize | number | Yes| Total size of the files to download, in bytes. | +| receivedSize | number | Yes| Size of the downloaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to download, in bytes.| **Example** @@ -1252,7 +1255,7 @@ Removes this download task. This API uses a promise to return the result. delete(callback: AsyncCallback<boolean>): void -Removes this download task. This API uses an asynchronous callback to return the result. +Deletes this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1262,7 +1265,7 @@ Removes this download task. This API uses an asynchronous callback to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task deletion result. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index d5daa5d41e299d368b7d38af4428856bf343c516..e1ee89e11a5bb2e69f48e9575c1443ae850afcdc 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -67,8 +67,8 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { console.info("Request suspension delay will time out."); }) - var id = delayInfo.requestId; - var time = delayInfo.actualDelayTime; + let id = delayInfo.requestId; + let time = delayInfo.actualDelayTime; console.info("The requestId is: " + id); console.info("The actualDelayTime is: " + time); } catch (error) { @@ -258,7 +258,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ```js import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; function callback(error, data) { if (error) { @@ -282,14 +282,18 @@ export default class EntryAbility extends UIAbility { wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } } }; ``` @@ -337,7 +341,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ```js import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { @@ -353,18 +357,22 @@ export default class EntryAbility extends UIAbility { wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((error) => { + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } } }; ``` diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 70f20b743d5ee09f2c79877ab626d76fdaeb0d95..0e7ad7e7c38f32e85af6ab3504252da38afb32eb 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,4 +1,4 @@ -# @ohos.resourceschedule.workScheduler (workScheduler) +# @ohos.resourceschedule.workScheduler (Work Scheduler) The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 80451d894a244a7cd2c1f91e4d4fed86cf1f898e..4c4b818f1cb692f8ff5256017287fc9e36d9075a 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -40,32 +40,28 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | -| 100002 | If the uri is not exist. | -| 100003 | If the pages are pushed too much. | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | **Example** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); }) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; ``` ## router.pushUrl9+ @@ -81,7 +77,7 @@ Navigates to a specified page in the application. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | --------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -89,32 +85,28 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | -| 100002 | If the uri is not exist. | -| 100003 | If the pages are pushed too much. | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | **Example** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } - } - }, (err) => { - if (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - return; +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - console.info('pushUrl success'); - }); -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.pushUrl9+ @@ -143,32 +135,28 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | -| 100002 | If the uri is not exist. | -| 100003 | If the pages are pushed too much. | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | **Example** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - }, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.pushUrl9+ @@ -185,7 +173,7 @@ Navigates to a specified page in the application. | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -193,32 +181,28 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | -| 100002 | If the uri is not exist. | -| 100003 | If the pages are pushed too much. | +| 100001 | if UI execution context not found. | +| 100002 | if the uri is not exist. | +| 100003 | if the pages are pushed too much. | **Example** ```js -try { - router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } - } - }, router.RouterMode.Standard, (err) => { - if (err) { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - return; +router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] } - console.info('pushUrl success'); - }); -} catch (error) { - console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); -}; + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); +}) ``` ## router.replaceUrl9+ @@ -247,28 +231,24 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found, only throw in standard system. | -| 200002 | If the uri is not exist. | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | **Example** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); }) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; ``` ## router.replaceUrl9+ @@ -284,7 +264,7 @@ Replaces the current page with another one in the application and destroys the c | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------ | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -292,28 +272,24 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found, only throw in standard system. | -| 200002 | If the uri is not exist. | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | **Example** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, (err) => { - if (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('replaceUrl success'); - }); -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); +}) ``` ## router.replaceUrl9+ @@ -344,28 +320,24 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found, only throw in standard system. | -| 200002 | If the uri is not exist. | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | **Example** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) ``` ## router.replaceUrl9+ @@ -382,7 +354,7 @@ Replaces the current page with another one in the application and destroys the c | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -390,28 +362,25 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found, only throw in standard system. | -| 200002 | If the uri is not exist. | +| 100001 | if UI execution context not found, only throw in standard system. | +| 200002 | if the uri is not exist. | **Example** ```js -try { - router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } - }, router.RouterMode.Standard, (err) => { - if (err) { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - return; - } - console.info('replaceUrl success'); - }); -} catch (error) { - console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); -}; +router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } +}, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); +}); + ``` ## router.back @@ -524,7 +493,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | If UI execution context not found. | +| 100001 | if UI execution context not found. | **Example** @@ -571,9 +540,9 @@ Obtains the parameters passed from the page that initiates redirection to the cu **Return value** -| Type | Description | -| ------ | ----------------- | -| Object | Parameters passed from the page that initiates redirection to the current page.| +| Type | Description | +| ------ | ---------------------------------- | +| object | Parameters passed from the page that initiates redirection to the current page.| **Example** @@ -636,7 +605,7 @@ export default { ### TypeScript-based Declarative Development Paradigm ```ts -// Navigate to the target page through router.push with the params parameter carried. +// Navigate to the target page through router.pushUrl with the params parameter carried. import router from '@ohos.router' @Entry @@ -745,37 +714,6 @@ router.push({ } }); ``` -## router.push(deprecated) - -push(options: RouterOptions, mode: RouterMode): void - -Navigates to a specified page in the application. - -This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------- | -| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | -| mode | [RouterMode](#routermode9) | Yes | Routing mode.| - - -**Example** - -```js -router.push({ - url: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - } - } -},router.RouterMode.Standard); -``` ## router.replace(deprecated) @@ -785,7 +723,7 @@ Replaces the current page with another one in the application and destroys the c This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Lite **Parameters** @@ -804,34 +742,6 @@ router.replace({ }); ``` -## router.replace(deprecated) - -replace(options: RouterOptions, mode: RouterMode): void - -Replaces the current page with another one in the application and destroys the current page. - -This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. - -**System capability**: SystemCapability.ArkUI.ArkUI.Lite - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------- | -| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | -| mode | [RouterMode](#routermode9) | Yes | Routing mode.| - -**Example** - -```js -router.replace({ - url: 'pages/detail/detail', - params: { - data1: 'message' - } -}, router.RouterMode.Standard); -``` - ## router.enableAlertBeforeBackPage(deprecated) enableAlertBeforeBackPage(options: EnableAlertOptions): void diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index c726ec7c8fdd4cd6f16d71f5a6892bc565b66cf6..f7f2a551648df0db4ad96733ef1a169f8fb42e14 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -226,7 +226,7 @@ screenlock.lock().then((data) => { onSystemEvent(callback: Callback<SystemEvent>): boolean -Registers a callback for system events related to screen locking. +Registers a callback for system events related to screen locking. This API can be called only by system screen lock applications. **System capability**: SystemCapability.MiscServices.ScreenLock diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 4fa5e15b59c8d70b09f5bcf8cd1e9686ba329a14..309a1bc64491497bf61aaf6f2695a9d5c4fbd9d4 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,4 +1,4 @@ -# @ohos.screenshot +# @ohos.screenshot (Screenshot) The **Screenshot** module provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. diff --git a/en/application-dev/reference/apis/js-apis-stationary.md b/en/application-dev/reference/apis/js-apis-stationary.md index ceae25ac4c711e8dd3664520290fda7b897c9ae9..bd7c29020ed3d0b65501421c4b9547423986fdf9 100644 --- a/en/application-dev/reference/apis/js-apis-stationary.md +++ b/en/application-dev/reference/apis/js-apis-stationary.md @@ -5,6 +5,8 @@ The **stationary** module provides APIs to report the device status, including a > **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. +> +> This module does not support x86 emulators. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-system-bluetooth.md b/en/application-dev/reference/apis/js-apis-system-bluetooth.md index a8c77cd86a20c0401d01ce1e54a61c58c7aace17..c65aef6079cb393917d7f8a44ef9d62de5e49478 100644 --- a/en/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -1,4 +1,4 @@ -# Bluetooth +# @system.bluetooth (Bluetooth) > **NOTE**
diff --git a/en/application-dev/reference/apis/js-apis-system-configuration.md b/en/application-dev/reference/apis/js-apis-system-configuration.md index dfeb0cf7db9c94d7831fe96cc19c6a6c09afd471..934ceb020412a18c64499de1cb0ef1593ace2e50 100644 --- a/en/application-dev/reference/apis/js-apis-system-configuration.md +++ b/en/application-dev/reference/apis/js-apis-system-configuration.md @@ -1,4 +1,4 @@ -# Application Configuration +# @system.configuration (Application Configuration) > **NOTE**
> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.i18n`](js-apis-i18n.md) and [`@ohos.intl`](js-apis-intl.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-fetch.md b/en/application-dev/reference/apis/js-apis-system-fetch.md index b9566ae178fb1bd4d4400eb998f3b12bea609845..529dc836e0132e77cae90c08f855d8ecb2c5fe8c 100644 --- a/en/application-dev/reference/apis/js-apis-system-fetch.md +++ b/en/application-dev/reference/apis/js-apis-system-fetch.md @@ -1,8 +1,9 @@ -# Data Request +# @system.fetch (Data Request) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.net.http`](js-apis-http.md) instead. -> +> > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-file.md b/en/application-dev/reference/apis/js-apis-system-file.md index 841f0b90056e377710f20336a3a5bf07ba58dde8..8483433af3dd490b8ae640b74d2e31378c45b6d2 100644 --- a/en/application-dev/reference/apis/js-apis-system-file.md +++ b/en/application-dev/reference/apis/js-apis-system-file.md @@ -1,4 +1,4 @@ -# File Storage +# @system.file (File Storage) > **NOTE**
> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.fileio`](js-apis-fileio.md). diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index f1ada5f0f2e7df99e3aa9889889d66eece5b2b3f..4f34c5ade9c9721f58ab188320291136e19eba73 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -1,4 +1,4 @@ -# Geographic Location +# @system.geolocation (Geographic Location) > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-system-request.md b/en/application-dev/reference/apis/js-apis-system-request.md index 82ba741d0964faa44066b5d43568b4fa25316f87..675a7fb9977fb5756d8a9a84296eebf0049011cb 100644 --- a/en/application-dev/reference/apis/js-apis-system-request.md +++ b/en/application-dev/reference/apis/js-apis-system-request.md @@ -3,8 +3,8 @@ The **system.request** module provides applications with basic upload and download capabilities. > **NOTE** +> - The APIs of this module are deprecated since API version 9. You are advised to use [@ohos.request](js-apis-request.md) instead. > -> - The APIs of this module are deprecated since API version 9. You are advised to use [`@ohos.request`](js-apis-request.md) instead. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -25,9 +25,9 @@ Uploads a file. This API returns no value. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | options | [UploadRequestOptions](#uploadrequestoptions) | Yes| Upload configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [UploadRequestOptions](#uploadrequestoptions) | Yes| Upload configurations.| **Example** @@ -61,27 +61,27 @@ Uploads a file. This API returns no value. **System capability**: SystemCapability.MiscServices.Upload - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | url | string | Yes| URL of the upload server.| - | data | Array<[RequestData](#requestdata)> | No| Form data in the request body.| - | files | Array<[RequestFile](#requestfile)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| - | header | Object | No| Request header.| - | method | string | No| Request method, which can be **'POST'** or **'PUT'**. The default value is **POST**.| - | success | Function | No| Called when API call is successful.| - | fail | Function | No| Called when API call has failed.| - | complete | Function | No| Called when API call is complete.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| URL of the upload server.| +| data | Array<[RequestData](#requestdata)> | No| Form data in the request body.| +| files | Array<[RequestFile](#requestfile)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| +| header | Object | No| Request header.| +| method | string | No| Request method, which can be **'POST'** or **'PUT'**. The default value is **POST**.| +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| **success parameter** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | data | [UploadResponse](#uploadresponse) | Yes| Information returned when the upload task is successful.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [UploadResponse](#uploadresponse) | Yes| Information returned when the upload task is successful.| **fail parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | data | any | Yes| Header information returned when the upload task fails.| - | code | number | Yes| HTTP status code returned when the upload task fails.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | any | Yes| Header information returned when the upload task fails.| +| code | number | Yes| HTTP status code returned when the upload task fails.| @@ -89,33 +89,33 @@ Uploads a file. This API returns no value. **System capability**: SystemCapability.MiscServices.Upload - | Name| Type| Description| - | -------- | -------- | -------- | - | code | number | HTTP status code returned by the server.| - | data | string | Content returned by the server. The value type is determined by the type in the returned headers.| - | headers | Object | Headers returned by the server.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| code | number | Yes| HTTP status code returned by the server.| +| data | string | Yes| Content returned by the server. The value type is determined by the type in the returned headers.| +| headers | Object | Yes| Headers returned by the server.| ## RequestFile **System capability**: SystemCapability.MiscServices.Upload - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filename | string | No| File name in the header when **multipart** is used.| - | name | string | No| Name of a form item when **multipart** is used. The default value is **file**.| - | uri | string | Yes| Local path for storing files.| - | type | string | No| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| filename | string | No| File name in the header when **multipart** is used.| +| name | string | No| Name of a form item when **multipart** is used. The default value is **file**.| +| uri | string | Yes| Local path for storing files.| +| type | string | No| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| ## RequestData **System capability**: SystemCapability.MiscServices.Upload - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the form element.| - | value | string | Yes| Value of the form element.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the form element.| +| value | string | Yes| Value of the form element.| @@ -129,9 +129,9 @@ Downloads a file. This API returns no value. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | options | [DownloadRequestOptions](#downloadrequestoptions) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [DownloadRequestOptions](#downloadrequestoptions) | Yes| Download configurations.| **Example** @@ -164,34 +164,34 @@ Downloads a file. This API returns no value. **System capability**: SystemCapability.MiscServices.Download - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | url | string | Yes| Resource URL.| - | filename | string | No| Name of the file to download. The value is obtained from the current request or resource URL by default.| - | header | Object | No| Request header.| - | description | string | No| Download description. The default value is the file name.| - | success | Function | No| Called when API call is successful.| - | fail | Function | No| Called when API call has failed.| - | complete | Function | No| Called when API call is complete.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Resource URL.| +| filename | string | No| Name of the file to download. The value is obtained from the current request or resource URL by default.| +| header | Object | No| Request header.| +| description | string | No| Download description. The default value is the file name.| +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| **success parameter** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | data | [DownloadResponse](#downloadresponse) | Yes| Information returned when the download task is successful.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [DownloadResponse](#downloadresponse) | Yes| Information returned when the download task is successful.| **fail parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | data | any | Yes| Header information returned when the download task fails.| - | code | number | Yes| HTTP status code returned when the download task fails.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | any | Yes| Header information returned when the download task fails.| +| code | number | Yes| HTTP status code returned when the download task fails.| ## DownloadResponse **System capability**: SystemCapability.MiscServices.Download - | Name| Type| Description| - | -------- | -------- | -------- | - | token | string | Download token, which is used to obtain the download status| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| token | string | Yes| Download token, which is used to obtain the download status| ## request.onDownloadComplete @@ -204,9 +204,9 @@ Listens for download task status. This API returns no value. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | options | [OnDownloadCompleteOptions](#ondownloadcompleteoptions) | Yes| Configurations of the download task.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [OnDownloadCompleteOptions](#ondownloadcompleteoptions) | Yes| Configurations of the download task.| **Example** @@ -231,29 +231,29 @@ Listens for download task status. This API returns no value. **System capability**: SystemCapability.MiscServices.Download - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | token | string | Yes| Result token returned by the download API.| - | success | Function | No| Called when API call is successful.| - | fail | Function | No| Called when API call has failed.| - | complete | Function | No| Called when API call is complete.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| token | string | Yes| Result token returned by the download API.| +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| **success parameter** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | data | [OnDownloadCompleteResponse](#ondownloadcompleteresponse) | Yes| Information returned when the download task is successful.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [OnDownloadCompleteResponse](#ondownloadcompleteresponse) | Yes| Information returned when the download task is successful.| **fail parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | data | any | Yes| Header information returned when the download task fails.| - | code | number | Yes| HTTP status code returned when the download task fails.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | any | Yes| Header information returned when the download task fails.| +| code | number | Yes| HTTP status code returned when the download task fails.| ## OnDownloadCompleteResponse **System capability**: SystemCapability.MiscServices.Download - | Name| Type| Description| - | -------- | -------- | -------- | - | uri | string | URI of the download file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| URI of the download file.| diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index 6e45d6c012ee2ba4ff6664e1f68ffcd38f9d7570..5ca064cb6ca57c6b2b3449def902dcfd44be6029 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -127,7 +127,7 @@ Returns to the previous page or a specified page. | Name | Type | Mandatory | Description | | ------- | --------------------------------------- | ---- | ----------------------- | -| options | [BackRouterOptions](#backrouteroptions) | Yes | For details, see **BackRouterOptions**.| +| options | [BackRouterOptions](#backrouteroptions) | No | For details, see **BackRouterOptions**.| **Example** @@ -188,7 +188,7 @@ export default { > > In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. -## router.getParams +## router.getParams7+ getParams(): ParamsInterface @@ -397,6 +397,6 @@ Defines the **DisableAlertBeforeBackPage** parameters. ## ParamsInterface -| Name | Type | Description | -| ------------- | ------ | ------- | -| [key: string] | Object | List of routing parameters.| +| Name | Type| Description | +| ------------- | -------- | -------------- | +| [key: string] | object | List of routing parameters.| diff --git a/en/application-dev/reference/apis/js-apis-system-storage.md b/en/application-dev/reference/apis/js-apis-system-storage.md index a593a0972638bbbf376fb9bcb0693009b081e197..0549fac53863bd341d1ff0d1aa8d0e95a0a262c8 100644 --- a/en/application-dev/reference/apis/js-apis-system-storage.md +++ b/en/application-dev/reference/apis/js-apis-system-storage.md @@ -1,23 +1,22 @@ -# Data Storage +# @system.storage (Data Storage) -> **NOTE**
+> **NOTE** > -> - The APIs of this module are no longer maintained since API Version 6, and you are advised to use [`@ohos.data.storage`](js-apis-data-storage.md). From API Version 9, you are advised to use [`@ohos.data.preferences`](js-apis-data-preferences.md). +> - The APIs of this module are no longer maintained since API version 6, and you are advised to use [`@ohos.data.storage`](js-apis-data-storage.md). From API version 9, you are advised to use [`@ohos.data.preferences`](js-apis-data-preferences.md). > -> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module can be used only in the FA model. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs of this module can be used only in the FA model. ## Modules to Import - ```js import storage from '@system.storage'; ``` - ## storage.get -get(Object): void +get(options: GetStorageOptions): void Reads the value stored in the cache based on the specified key. @@ -25,13 +24,9 @@ Reads the value stored in the cache based on the specified key. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to read.| -| default | string | No| Default value returned when the **key** does not exist.| -| success | Function | No| Called to return the value obtained when **storage.get()** is successful.| -| fail | Function | No| Called when **storage.get()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.| -| complete | Function | No| Called when **storage.get()** is complete.| +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------- | +| options | [GetStorageOptions](#getstorageoptions) | Yes | API configuration.| **Example** @@ -54,10 +49,9 @@ export default { } ``` - ## storage.set -set(Object): void +get(options: SetStorageOptions): void Sets the value in the cache based on the specified key. @@ -65,13 +59,9 @@ Sets the value in the cache based on the specified key. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to set.| -| value | string | Yes| New value to set. The length must be less than 128 bytes.| -| success | Function | No| Called when **storage.set()** is successful.| -| fail | Function | No| Called when **storage.set()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.| -| complete | Function | No| Called when **storage.set()** is complete.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ---------- | +| options | [SetStorageOptions](#setstorageoptions) | Yes | API configuration.| **Example** @@ -92,10 +82,9 @@ export default { } ``` - ## storage.clear -clear(Object): void +clear(options?: ClearStorageOptions): void Clears the key-value pairs from the cache. @@ -103,11 +92,9 @@ Clears the key-value pairs from the cache. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| success | Function | No| Called when **storage.clear()** is successful.| -| fail | Function | No| Called when **storage.clear()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.| -| complete | Function | No| Called when **storage.clear()** is complete.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | -------------- | +| options | [ClearStorageOptions](#clearstorageoptions) | No | API configuration.| **Example** @@ -126,10 +113,9 @@ export default { } ``` - ## storage.delete -delete(Object): void +delete(options: DeleteStorageOptions): void Deletes the key-value pair based on the specified key. @@ -137,12 +123,9 @@ Deletes the key-value pair based on the specified key. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to delete.| -| success | Function | No| Called when **storage.delete()** is successful.| -| fail | Function | No| Called when **storage.delete()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.| -| complete | Function | No| Called when **storage.delete()** is complete.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | -------------- | +| options | [DeleteStorageOptions](#deletestorageoptions) | Yes | API configuration.| **Example** @@ -161,3 +144,52 @@ export default { } } ``` + +## GetStorageOptions + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Name | Type | Mandatory| Description | +| -------- | ---------------- | ---- | ------------------- | +| key | string | Yes | Key of the target data. | +| default | string | No | Default value returned when the specified key does not exist. | +| success | (data: any) => void | No | Called to return the result when **storage.get()** is called successfully. **data** is the value indexed by the specified key. | +| fail | (data: string, code: number) => void | No | Called to return the result when **storage.get()** fails to be called. **data** is the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when **storage.get()** is complete. | + + +## SetStorageOptions + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | -------------------- | +| key | string | Yes | Key of the data to set. | +| value | string | Yes | New value to set. The length must be less than 128 bytes. | +| success | () => void | No | Called when **storage.set()** is called successfully. | +| fail | (data: string, code: number) => void | No | Called to return the result when **storage.get()** fails to be called. **data** is the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when **storage.get()** is complete. | + + +## ClearStorageOptions + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| success | () => void | No | Called when **storage.clear()** is called successfully. | +| fail | (data: string, code: number) => void | No | Called to return the result when **storage.clear()** fails to be called. **data** is the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when **storage.clear()** is complete. | + + +## DeleteStorageOptions + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------ | +| key | string | Yes | Key of the data to delete. | +| success | () => void | No | Called when **storage.delete()** is called successfully. | +| fail | (data: string, code: number) => void | No | Called to return the result when **storage.delete()** fails to be called. **data** is the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when **storage.delete()** is complete. | + diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md new file mode 100644 index 0000000000000000000000000000000000000000..a441a39e8bb232fd589a0b03e473890ef6bbbc5f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -0,0 +1,243 @@ +# @ohos.taskpool (Using the Task Pool) + +The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance. + +You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**. (The task priority mechanism is not supported yet.) + +If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads. (The load balancing mechanism is not supported yet.) + +The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.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 + +```js +import taskpool from '@ohos.taskpool'; +``` + +## Priority + +Enumerates the priorities available for created tasks. (This enum is not supported yet.) + +**System capability**: SystemCapability.Utils.Lang + +| Name| Value| Description| +| -------- | -------- | -------- | +| HIGH | 0 | The task has a high priority.| +| MEDIUM | 1 | The task has a medium priority.| +| LOW | 2 | The task has a low priority.| + +## Task + +Implements a task. Before using any of the following APIs, you must create a **Task** instance. + +### constructor + +constructor(func: Function, ...args: unknown[]) + +A constructor used to create a **Task** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | -------------------------------------------------------------------- | +| func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | --------------------------------------- | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```js +function func(args) { + "use concurrent" + console.log("func: " + args); + return args; +} +let task = new taskpool.Task(func, "this is my first Task"); +``` + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name | Type | Readable| Writable| Description | +| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- | +| function | Function | Yes | Yes | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| arguments | unknown[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| + +## taskpool.execute + +execute(func: Function, ...args: unknown[]): Promise\ + +Executes a task in the task pool. You must pass in a function and arguments to execute the task, and the task executed in this mode cannot be canceled. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| func | Function | Yes | Function used to execute the task. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200003 | Worker initialization failure. | +| 10200006 | Serializing an uncaught exception failed. | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```js +function func(args) { + "use concurrent" + console.log("func: " + args); + return args; +} + +let value = taskpool.execute(func, 100); +``` + +## taskpool.execute + +execute(task: Task, priority?: Priority): Promise\ + +Executes a task in the task pool. You must pass in a created task, and the task executed in this mode can be canceled. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------ | +| task | [Task](#task) | Yes | Task to be executed. | +| priority | [Priority](#priority) | No | Priority of the task (not supported yet).| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200003 | Worker initialization failure. | +| 10200006 | Serializing an uncaught exception failed. | +| 10200014 | The function is not mark as concurrent. | + +**Example** + +```js +function func(args) { + "use concurrent" + console.log("func: " + args); + return args; +} +let task = new taskpool.Task(func, "this is my first Task"); +let value = taskpool.execute(task); +``` + +## taskpool.cancel + +cancel(task: Task): void + +Cancels a task in the task pool. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | -------------------- | +| task | [Task](#task) | Yes | Task to cancel.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 10200015 | If the task is not exist. | +| 10200016 | If the task is running. | + +**Example** + +```js +function func(args) { + "use concurrent" + console.log("func: " + args); + return args; +} +let task = new taskpool.Task(func, "this is first Task"); +let value = taskpool.execute(task); +taskpool.cancel(task); +``` + +## Additional Information + +### Sequenceable Data Types +The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray. + +### Precautions +A task in the task pool can reference only variables passed in by input parameters or imported variables. It does not support closure variables. + +```js +// 1. Reference a variable passed in by the input parameter. +function func(args) { + "use concurrent" + console.log("func: " + args); + return args; +} + +let task = new taskpool.Task(func, "create task, then execute"); +let val1 = taskpool.execute(task); + +let val2 = taskpool.execute(func, "execute task by func"); +``` + +```js +// 2. Reference an imported variable. + +// b.ts +export var c = 2000; + +// a.ts +import { c } from './b' + +function test(a) { + "use concurrent" + console.log(a); + console.log(c); + return a; +} + +let task = new taskpool.Task(test, "create task, then execute"); +let val1 = taskpool.execute(task); + +let val2 = taskpool.execute(test, "execute task by func"); +``` diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index 00bf51656958f8ca58b926cb54ad9fd1d82a8e53..b3fb6f7a3ea58550cfa93a514591715952c52ad6 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -35,7 +35,7 @@ Naming format: A standard URI consists of the following parts: [scheme:]scheme-specific-part[#fragment] -- Scheme: scheme component, which is mandatory. Example values: **http**, **https**, **ftp**, **datashare**, and **dataability**. +- scheme: scheme component. Set this parameter as required. Example values: **http**, **https**, **ftp**, **datashare**, and **dataability**. - scheme-specific-part: specific part of the URI decoding scheme. The value consists of [//][authority][path][?query]. Set this parameter as required. - authority: decoding authority component of the URI. The value consists of [userinfo@]host[:port]. Set this parameter as required. - userinfo: user information. Set this parameter as required. @@ -226,7 +226,9 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi ```js const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp'); -uriInstance.checkIsAbsolute(); +console.log(uriInstance.checkIsAbsolute()); // true +const uriInstance1 = new uri.URI('xxx.com/suppliers.htm'); +console.log(uriInstance1.checkIsAbsolute()); // false ``` @@ -248,6 +250,7 @@ Normalizes the path of this URI. ```js const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); +console.log(uriInstance.path); // /path/path1/../path2/./path3 let uriInstance1 = uriInstance.normalize(); -uriInstance1.path; +console.log(uriInstance1.path); // /path/path2/path3 ``` diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 8a972e121d32b041e1ff7f8319c4e26261afb2f5..d4d453a59685a23f228ca2d4bc7e56ac0608a8e8 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -87,7 +87,7 @@ paramsObject.delete('fod'); getAll(name: string): string[] -Obtains all the key-value pairs based on the specified name. +Obtains all the values based on the specified key. **System capability**: SystemCapability.Utils.Lang @@ -95,13 +95,13 @@ Obtains all the key-value pairs based on the specified name. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Key specified to obtain all key-value pairs.| +| name | string | Yes| Target key.| **Return value** | Type| Description| | -------- | -------- | -| string[] | Key-value pairs obtained.| +| string[] | All the values obtained.| **Example** @@ -432,7 +432,7 @@ A no-argument constructor used to create a URL. It returns a **URL** object afte **System capability**: SystemCapability.Utils.Lang ### parseURL9+ - + static parseURL(url : string, base?: string | URL): URL Parses a URL. @@ -514,7 +514,7 @@ A constructor used to create a **URLSearchParams** instance. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+](#constructor9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.constructor9+](#constructor9) instead. **System capability**: SystemCapability.Utils.Lang @@ -542,7 +542,7 @@ Appends a key-value pair into the query string. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.append9+](#append9) instead. **System capability**: SystemCapability.Utils.Lang @@ -569,7 +569,7 @@ Deletes key-value pairs of the specified key. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.delete9+](#delete9) instead. **System capability**: SystemCapability.Utils.Lang @@ -595,7 +595,7 @@ Obtains all the key-value pairs based on the specified key. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.getAll9+](#getall9) instead. **System capability**: SystemCapability.Utils.Lang @@ -603,7 +603,7 @@ Obtains all the key-value pairs based on the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Key specified to obtain all key-value pairs.| +| name | string | Yes| Target key.| **Return value** @@ -628,7 +628,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.entries9+](#entries9) instead. **System capability**: SystemCapability.Utils.Lang @@ -656,7 +656,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.forEach9+](#foreach9) instead. **System capability**: SystemCapability.Utils.Lang @@ -693,7 +693,7 @@ Obtains the value of the first key-value pair based on the specified key. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.get9+](#get9) instead. **System capability**: SystemCapability.Utils.Lang @@ -727,7 +727,7 @@ Checks whether a key has a value. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.has9+](#has9) instead. **System capability**: SystemCapability.Utils.Lang @@ -760,7 +760,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.set9+](#set9) instead. **System capability**: SystemCapability.Utils.Lang @@ -788,7 +788,7 @@ Sorts all key-value pairs contained in this object based on the Unicode code poi > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.sort9+](#sort9) instead. **System capability**: SystemCapability.Utils.Lang @@ -809,7 +809,7 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.keys9+](#keys9) instead. **System capability**: SystemCapability.Utils.Lang @@ -837,7 +837,7 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.values9+](#values9) instead. **System capability**: SystemCapability.Utils.Lang @@ -865,7 +865,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [Symbol.iterator]9+](#symboliterator9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.[Symbol.iterator]9+](#symboliterator9) instead. **System capability**: SystemCapability.Utils.Lang @@ -892,7 +892,7 @@ Obtains search parameters that are serialized as a string and, if necessary, per > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tostring9+](#tostring9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams.tostring9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md index 68a127a08bdfd1df0ca558866dc3cde577e2b25a..95eb105b0a25fc824b4f7762a73e035283097ddc 100644 --- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -43,7 +43,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); vendorId: 7531, productId: 2, clazz: 9, - subclass: 0, + subClass: 0, protocol: 1, devAddress: 1, busNum: 1, @@ -60,7 +60,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); id: 0, protocol: 0, clazz: 9, - subclass: 0, + subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ @@ -171,7 +171,7 @@ usb.requestRight(devicesName).then((ret) => { ## usb.claimInterface -claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number +claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number Claims a USB interface. @@ -348,7 +348,7 @@ let ret = usb.getFileDescriptor(devicepipe); ## usb.controlTransfer -controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise<number> +controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise<number> Performs control transfer. @@ -380,7 +380,7 @@ usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { ## usb.bulkTransfer -bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise<number> +bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> Performs bulk transfer. diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index a0a0dc40c837d45da72209b5faa6a57ed0b95909..521fef517823a160e22a17b752fdc62443eeba7a 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -42,7 +42,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); vendorId: 7531, productId: 2, clazz: 9, - subclass: 0, + subClass: 0, protocol: 1, devAddress: 1, busNum: 1, @@ -59,7 +59,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); id: 0, protocol: 0, clazz: 9, - subclass: 0, + subClass: 0, alternateSetting: 0, name: "1-1", endpoints: [ @@ -252,7 +252,7 @@ if (usb.addRight(bundleName, devicesName) { ## usb.claimInterface -claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number +claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number Claims a USB interface. @@ -429,7 +429,7 @@ let ret = usb.getFileDescriptor(devicepipe); ## usb.controlTransfer -controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise<number> +controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise<number> Performs control transfer. @@ -461,7 +461,7 @@ usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { ## usb.bulkTransfer -bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise<number> +bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> Performs bulk transfer. diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index f4193680d4d0732a38ab9564bbd67428c7a3497a..21ac9df11df7cabdf260edf97fc5fe17f83871b8 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -497,6 +497,7 @@ Decodes the input content. | -------- | -------- | -------- | -------- | -------- | | encoding | string | Yes| No| Encoding format. The default format is **utf-8**.| + ### constructor constructor() @@ -1456,7 +1457,7 @@ Performs subsequent operations after a value is removed. | Name | Type | Mandatory| Description | | -------- | ------- | ---- | ------------------------------------------------------------ | -| isEvict | boolean | Yes | Whether the cache capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | +| isEvict | boolean | Yes | Whether the cache capacity is insufficient. If the value is **true**, this API is called due to insufficient capacity. | | key | K | Yes | Key removed. | | value | V | Yes | Value removed. | | newValue | V | Yes | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| @@ -3358,7 +3359,7 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.constructor9+](#constructor9-3) instead. **System capability**: SystemCapability.Utils.Lang @@ -3382,7 +3383,7 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.updateCapacity9+](#updatecapacity9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3407,7 +3408,7 @@ Obtains the string representation of this **LruBuffer** object. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3435,7 +3436,7 @@ Obtains the capacity of this buffer. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.getCapacity9+](#getcapacity9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3459,7 +3460,7 @@ Clears key-value pairs from this buffer. The **afterRemoval()** method will be c > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.clear9+](#clear9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3480,7 +3481,7 @@ Obtains the number of return values for **createDefault()**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.getCreateCount9+](#getcreatecount9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3506,7 +3507,7 @@ Obtains the number of times that the queried values are mismatched. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.getMissCount9+](#getmisscount9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3533,7 +3534,7 @@ Obtains the number of removals from this buffer. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.getRemovalCount9+](#getremovalcount9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3561,7 +3562,7 @@ Obtains the number of times that the queried values are matched. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.getMatchCount9+](#getmatchcount9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3588,7 +3589,7 @@ Obtains the number of additions to this buffer. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.getPutCount9+](#getputcount9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3614,7 +3615,7 @@ Checks whether this buffer is empty. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.isEmpty9+](#isempty9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3640,7 +3641,7 @@ Obtains the value of the specified key. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.get9+](#get9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3672,7 +3673,7 @@ Adds a key-value pair to this buffer. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.put9+](#put9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3704,7 +3705,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.values9+](#values9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3732,7 +3733,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.keys9+](#keys9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3743,6 +3744,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce | K [] | All keys in the buffer, listed from the most to the least recently accessed.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -3757,7 +3759,7 @@ Removes the specified key and its value from this buffer. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.remove9+](#remove9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3788,7 +3790,7 @@ Performs subsequent operations after a value is removed. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.afterRemoval9+](#afterremoval9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3796,7 +3798,7 @@ Performs subsequent operations after a value is removed. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| +| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this API is called due to insufficient capacity.| | key | K | Yes| Key removed.| | value | V | Yes| Value removed.| | newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| @@ -3832,7 +3834,7 @@ Checks whether this buffer contains the specified key. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3864,7 +3866,7 @@ Creates a value if the value of the specified key is not available. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.createDefault9+](#createdefault9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3895,7 +3897,7 @@ Obtains a new iterator object that contains all key-value pairs in this object. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.entries9+](#entries9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3921,7 +3923,7 @@ Obtains a two-dimensional array in key-value pairs. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache.Symbol.iterator9+](#symboliterator9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3953,7 +3955,7 @@ A constructor used to create a **Scope** object with the specified upper and low > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.constructor9+](#constructor9-4) instead. **System capability**: SystemCapability.Utils.Lang @@ -3980,7 +3982,7 @@ Obtains a string representation that contains this **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.toString9+](#tostring9-1) instead. **System capability**: SystemCapability.Utils.Lang @@ -4007,7 +4009,7 @@ Obtains the intersection of this **Scope** and the given **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4043,7 +4045,7 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.intersect9+](#intersect9-1) instead. **System capability**: SystemCapability.Utils.Lang @@ -4079,7 +4081,7 @@ Obtains the upper limit of this **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.getUpper9+](#getupper9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4106,7 +4108,7 @@ Obtains the lower limit of this **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.getLower9+](#getlower9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4133,7 +4135,7 @@ Obtains the union set of this **Scope** and the given lower and upper limits. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4169,7 +4171,7 @@ Obtains the union set of this **Scope** and the given **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.expand9+](#expand9-1) instead. **System capability**: SystemCapability.Utils.Lang @@ -4205,7 +4207,7 @@ Obtains the union set of this **Scope** and the given value. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.expand9+](#expand9-2) instead. **System capability**: SystemCapability.Utils.Lang @@ -4239,7 +4241,7 @@ Checks whether a value is within this **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.contains9+](#contains9-1) instead. **System capability**: SystemCapability.Utils.Lang @@ -4273,7 +4275,7 @@ Checks whether a range is within this **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.contains9+](#contains9-2) instead. **System capability**: SystemCapability.Utils.Lang @@ -4310,7 +4312,7 @@ Limits a value to this **Scope**. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper.clamp9+](#clamp9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4351,7 +4353,7 @@ A constructor used to create a **Base64** object. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.constructor9+](#constructor9-5) instead. **System capability**: SystemCapability.Utils.Lang @@ -4369,7 +4371,7 @@ Encodes the input content. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.encodeSync9+](#encodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4401,7 +4403,7 @@ Encodes the input content. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.encodeToStringSync9+](#encodetostringsync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4433,7 +4435,7 @@ Decodes the input content. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.decodeSync9+](#decodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4465,7 +4467,7 @@ Encodes the input content asynchronously. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.encode9+](#encode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4502,7 +4504,7 @@ Encodes the input content asynchronously. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.encodeToString9+](#encodetostring9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4537,7 +4539,7 @@ Decodes the input content asynchronously. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper.decode9+](#decode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4565,5 +4567,3 @@ Decodes the input content asynchronously. } }) ``` - - diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 215816e358a3c70d147a149db7c9142a15535ec1..6657eb3e558732fa50af4c7bb82f7b26e3457433 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,4 +1,4 @@ -# @ohos.wantAgent +# @ohos.wantAgent (wantAgent) The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 4a7bee42b6eba3d30626dac89817440efeebff2e..08c8413e6107382b516a25676cb19bafde1a1e2a 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -1,3 +1,5 @@ + + # @ohos.web.webview (Webview) The **Webview** module provides APIs for web control. @@ -262,6 +264,45 @@ struct WebComponent { } ``` +### setWebDebuggingAccess + +static setWebDebuggingAccess(webDebuggingAccess: boolean): void + +Sets whether to enable web debugging. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description| +| ------------------ | ------- | ---- | ------------- | +| webDebuggingAccess | boolean | Yes | Whether to enable web debugging.| + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + aboutToAppear():void { + try { + web_webview.WebviewController.setWebDebuggingAccess(true); + } catch(error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + } + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ### loadUrl loadUrl(url: string | Resource, headers?: Array\): void @@ -1469,10 +1510,8 @@ struct WebComponent { try { // 1. Create two message ports. this.ports = this.controller.createWebMessagePorts(); - // 2. Send one of the message ports to the HTML side, which can then save and use the port. - this.controller.postMessage('__init_port__', [this.ports[0]], '*'); - // 3. Register a callback for the other message port on the application side. - this.ports[1].onMessageEvent((result: WebMessage) => { + // 2. Register a callback on a message port (for example, port 1) on the application side. + this.ports[1].onMessageEvent((result: web_webview.WebMessage) => { var msg = 'Got msg from HTML:'; if (typeof(result) == "string") { console.log("received string message from html5, string is:" + result); @@ -1489,12 +1528,14 @@ struct WebComponent { } this.receivedFromHtml = msg; }) + // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. + this.controller.postMessage('__init_port__', [this.ports[0]], '*'); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - // 4. Use the port on the application side to send messages to the message port that has been sent to the HTML. + // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. Button('SendDataToHTML') .onClick(() => { try { @@ -1504,7 +1545,7 @@ struct WebComponent { console.error(`ports is null, Please initialize first`); } } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) Web({ src: $rawfile('xxx.html'), controller: this.controller }) @@ -1526,7 +1567,7 @@ struct WebComponent {

WebView Message Port Demo


-
+

display received message send from ets

@@ -2748,6 +2789,104 @@ struct WebComponent { } ``` +### pageUp + +pageUp(top:boolean): void + +Scrolls the page up by half the view port or jumps to the top of the page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the view port.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('pageUp') + .onClick(() => { + try { + this.controller.pageUp(false); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### pageDown + +pageDown(bottom:boolean): void + +Scrolls the page down by half the view port or jumps to the bottom of the page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the view port.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('pageDown') + .onClick(() => { + try { + this.controller.pageDown(false); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ### getBackForwardEntries getBackForwardEntries(): BackForwardList @@ -2797,6 +2936,122 @@ struct WebComponent { } ``` +### serializeWebState + +serializeWebState(): Uint8Array + +Serializes the page status history of the current Webview. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ---------- | --------------------------------------------- | +| Uint8Array | Serialized data of the page status history of the current WebView.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; +import fileio from '@ohos.fileio'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('serializeWebState') + .onClick(() => { + try { + let state = this.controller.serializeWebState(); + let path = globalThis.AbilityContext.cacheDir; + path += '/WebState'; + let fd = fileio.openSync(path, 0o2 | 0o100, 0o666); + fileio.writeSync(fd, state.buffer); + fileio.closeSync(fd); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### restoreWebState + +restoreWebState(state: Uint8Array): void + +Restores the page status history from the serialized data of the current WebView. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ---------------------------- | +| state | Uint8Array | Yes | Serialized data of the page status history.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; +import fileio from '@ohos.fileio'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('RestoreWebState') + .onClick(() => { + try { + let path = globalThis.AbilityContext.cacheDir; + path += '/WebState'; + let fd = fileio.openSync(path, 0o002, 0o666); + let stat = fileio.fstatSync(fd); + let size = stat.size; + let buf = new ArrayBuffer(size); + fileio.read(fd, buf, (err, data) => { + if (data) { + this.controller.restoreWebState(new Uint8Array(data.buffer)); + } + fileio.closeSync(fd); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ### customizeSchemes static customizeSchemes(schemes: Array\): void @@ -3999,7 +4254,7 @@ Stores this web page. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | | baseName | string | Yes| Save path. The value cannot be null. | -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | | callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.| **Example** @@ -4080,6 +4335,10 @@ Stores this web page. This API uses a promise to return the result. Implements a **GeolocationPermissions** object. +### Required Permissions + +**ohos.permission.LOCATION**, **ohos.permission.APPROXIMATELY_LOCATION**, and **ohos.permission.LOCATION_IN_BACKGROUND**, which are required for accessing the location information. For details about the permissions, see [@ohos.geolocation (Geolocation)](./js-apis-geolocation.md). + ### allowGeolocation static allowGeolocation(origin: string): void @@ -4467,6 +4726,8 @@ Provides the element information of the area being clicked. For details about th Describes the data types supported for [WebMessagePort](#webmessageport). +**System capability**: SystemCapability.Web.Webview.Core + | Type | Description | | -------- | -------------------------------------- | | string | String type.| @@ -4490,10 +4751,10 @@ Provides the historical information list of the current webview. **System capability**: SystemCapability.Web.Webview.Core -| Name | Type | Readable| Writable| Description | -| ------------ | ------ | ---- | ---- | ---------------------------- | -| currentIndex | number | Yes | No | Index of the current page in the page history stack.| -| size | number | Yes | No | Number of indexes in the history stack. | +| Name | Type | Readable| Writable| Description | +| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| currentIndex | number | Yes | No | Index of the current page in the page history stack. | +| size | number | Yes | No | Number of indexes in the history stack. The maximum value is 50. If this value is exceeded, the earliest index will be overwritten.| ### getItemAtIndex diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index bc1ad05712b63c8b2d990af46c8bf70242134e77..9f3a86e1a616d1fce7d3a2f732351b90f3eb2785 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,4 +1,4 @@ -# @ohos.window +# @ohos.window (Window) The **Window** module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. @@ -54,7 +54,7 @@ Defines the parameters for creating a subwindow or system window. | ---------- | -------------------------- | -- | ----------------------------------- | | name | string | Yes| Name of the window. | | windowType | [WindowType](#windowtype7) | Yes| Type of the window. | -| ctx | BaseContext | No| Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md). If this parameter is not set, no context is used.
A system window is created when **Context** is [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | No| Current application context. If this parameter is not set, no context is used.
You do not need to set this parameter to create a subwindow in the FA model or a system window in the stage model. | | displayId | number | No| ID of the current physical screen. If this parameter is not set, the default value **-1** is used.| | parentId | number | No| ID of the parent window. If this parameter is not set, the default value **-1** is used. | @@ -430,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous | Name| Type| Mandatory| Description| | -------- | -------------------------------------- | -- | ---------------------------------------- | -| ctx | BaseContext | Yes| Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Current application context.| | callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the top window obtained.| **Error codes** @@ -472,7 +472,7 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type| Mandatory| Description| | ------ | ----------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Current application context.| **Return value** @@ -897,7 +897,7 @@ promise.then((data)=> { create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses an asynchronous callback to return the result. +Creates a system window. This API uses an asynchronous callback to return the result. > **NOTE** > @@ -907,12 +907,12 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype7) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------ | +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Current application context. | +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| **Example** @@ -933,7 +933,7 @@ window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. +Creates a system window. This API uses a promise to return the result. > **NOTE** > @@ -945,7 +945,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Current application context.| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype7) | Yes | Window type. | @@ -1121,7 +1121,7 @@ Obtains the top window of the current application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Current application context.| | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** @@ -1154,7 +1154,7 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type | Mandatory| Description | | ------ | ----------- | ---- | ------------------------------------------------------------ | -| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Current application context.| **Return value** @@ -1864,7 +1864,7 @@ Obtains the area where this window cannot be displayed, for example, the system | Name| Type| Mandatory| Description| | ---- |----------------------------------| -- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. | +| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area.| **Return value** @@ -4629,10 +4629,10 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | -| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | --------------------------------- | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | +| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** @@ -4662,9 +4662,9 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ----------------- | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | **Return value** @@ -5237,10 +5237,10 @@ Sets a color space for this window. This API uses an asynchronous callback to re **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | --------- | ----------------------------------- | +| Name | Type | Mandatory | Description | +| ---------- | -------------------------- | --------- | ----------------------------------- | | colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5269,8 +5269,8 @@ Sets a color space for this window. This API uses a promise to return the result **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | --------- | ------------------- | +| Name | Type | Mandatory | Description | +| ---------- | -------------------------- | --------- | ------------------- | | colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. | **Return value** @@ -5305,8 +5305,8 @@ Obtains the color space of this window. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | | callback | AsyncCallback<[ColorSpace](#colorspace8)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. | **Example** @@ -5336,8 +5336,8 @@ Obtains the color space of this window. This API uses a promise to return the re **Return value** -| Type | Description | -| ---------------------------------------- | ----------------------------------------------- | +| Type | Description | +| ----------------------------------------- | ----------------------------------------------- | | Promise<[ColorSpace](#colorspace8)> | Promise used to return the current color space. | **Example** diff --git a/en/application-dev/reference/arkui-ts/figures/animateTo.gif b/en/application-dev/reference/arkui-ts/figures/animateTo.gif deleted file mode 100644 index 8755e2bc014f3843f8798acae725eeb0fee11f54..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/animateTo.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent1.png b/en/application-dev/reference/arkui-ts/figures/animationComponent1.png new file mode 100644 index 0000000000000000000000000000000000000000..b2aa53b14b112434bb736d2dc2f301bac3b46043 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/animationComponent1.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent2.png b/en/application-dev/reference/arkui-ts/figures/animationComponent2.png new file mode 100644 index 0000000000000000000000000000000000000000..c348c9305503698fab2f6b401450048a653e581a Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/animationComponent2.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent3.png b/en/application-dev/reference/arkui-ts/figures/animationComponent3.png new file mode 100644 index 0000000000000000000000000000000000000000..b53d8f308a879d4b4ce84db7adac1289c8b85cfa Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/animationComponent3.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/animationComponent4.png b/en/application-dev/reference/arkui-ts/figures/animationComponent4.png new file mode 100644 index 0000000000000000000000000000000000000000..a93f8390861d3638a35de13f38e2ab51816b8083 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/animationComponent4.png differ 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 8ee9c34e359dad14776f7fca6e55ec18d8381cc2..a661b6abc36a1820fbcd634178d5cf2654911336 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 @@ -24,7 +24,7 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType}) | ----------------- | -------- | ----- | -------- | | values | number[] | Yes | Data value list. A maximum of nine values are supported. If more than nine values are set, only the first nine ones are used. If the value is less than 0, the value 0 is used.| | 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.
Default value: **DataPanelType.Circle**| +| type8+ | [DataPanelType](#datapaneltype) | No| Type of the data panel (dynamic modification is not supported).
Default value: **DataPanelType.Circle**| ## DataPanelType diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md b/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md index f87d471b580ea09127f939d391af7a1acdaf6201..962a2de43931dc23157f7d168de50f2843afba06 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md @@ -21,7 +21,7 @@ ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: B | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | scroller | [Scroller](ts-container-scroll.md#scroller) | Yes| Scroller, which can be bound to scrollable components.| -| direction | ScrollBarDirection | No| Scrollbar direction in which scrollable components scroll.
Default value: **ScrollBarDirection.Vertical**| +| direction | [ScrollBarDirection](#scrollbardirection) | No| Scrollbar direction in which scrollable components scroll.
Default value: **ScrollBarDirection.Vertical**| | state | [BarState](ts-appendix-enums.md#barstate) | No| Scrollbar state.
Default value: **BarState.Auto**| > **NOTE** @@ -65,7 +65,7 @@ struct ScrollBarExample { .margin({ top: 5 }) } }, item => item) - }.margin({ left: 52 }) + }.margin({ right: 52 }) } .scrollBar(BarState.Off) .scrollable(ScrollDirection.Vertical) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index e2afb3e5eaa55dfb4d4509db3c87ba55821cd748..efd01a21bbdecede13695ffd8cfc44168cd8f05c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -577,7 +577,7 @@ Sets whether to display the horizontal scrollbar, including the system default s verticalScrollBarAccess(verticalScrollBar: boolean) -Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. +Sets whether to display the vertical scrollbar, including the default system scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. **Parameters** @@ -745,36 +745,6 @@ Sets the user agent. } ``` -### webDebuggingAccess9+ - -webDebuggingAccess(webDebuggingAccess: boolean) - -Sets whether to enable web debugging. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------------------ | ------- | ---- | ----- | ------------- | -| webDebuggingAccess | boolean | Yes | false | Whether to enable web debugging.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - @State webDebuggingAccess: boolean = true - build() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - .webDebuggingAccess(this.webDebuggingAccess) - } - } - } - ``` - ### blockNetwork9+ blockNetwork(block: boolean) @@ -1211,6 +1181,52 @@ struct WebComponent { } ``` +### allowWindowOpenMethod9+ + +allowWindowOpenMethod(flag: boolean) + +Sets whether to allow a new window to automatically open through JavaScript. + +When **flag** is set to **true**, a new window can automatically open through JavaScript. When **flag** is set to **false**, a new window can still automatically open through JavaScript for user behavior, but cannot for non-user behavior. The user behavior here refers to that a user requests to open a new window (**window.open**) within 5 seconds. + +This API takes effect only when [javaScriptAccess](#javascriptaccess) is enabled. + +This API opens a new window when [multiWindowAccess](#multiwindowaccess9) is enabled and opens a local window when [multiWindowAccess](#multiwindowaccess9) is disabled. + +The default value of **flag** is subject to the settings of the **persist.web.allowWindowOpenMethod.enabled** system attribute. If this attribute is not set, the default value of **flag** is **false**. + +To check the settings of **persist.web.allowWindowOpenMethod.enabled**, run the **hdc shell param get persist.web.allowWindowOpenMethod.enabled** command. If the attribute is set to 0 or does not exist, +you can run the **hdc shell param set persist.web.allowWindowOpenMethod.enabled 1** command to enable it. + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ------- | ---- | ----- | ------------------ | +| flag | boolean | Yes | Subject to the settings of the **persist.web.allowWindowOpenMethod.enabled** system attribute. If this attribute is set, the default value of **flag** is **true**. Otherwise, the default value of **flag** is **false**. | Whether to allow a new window to automatically open through JavaScript.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State access: boolean = true + @State multiWindow: boolean = true + @State flag: boolean = true + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .javaScriptAccess(this.access) + .multiWindowAccess(this.multiWindow) + .allowWindowOpenMethod(this.flag) + } + } + } + ``` + ## Events The universal events are not supported. @@ -1219,7 +1235,7 @@ The universal events are not supported. onAlert(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) -Triggered when **alert()** is invoked to display an alert dialog box on the web page. +Called when **alert()** is invoked to display an alert dialog box on the web page. **Parameters** @@ -1233,7 +1249,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web | Type | Description | | ------- | ---------------------------------------- | -| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\** component of the user's operation.| +| boolean | If the callback returns **true**, the application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **\** component to exit the current page based on the user operation. If the callback returns **false**, the **\** component cannot trigger the system dialog box.| **Example** @@ -1277,7 +1293,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) -Triggered when this page is about to exit after the user refreshes or closes the page. This callback is triggered only when the page has obtained focus. +Called when this page is about to exit after the user refreshes or closes the page. This API takes effect only when the page has obtained focus. **Parameters** @@ -1291,7 +1307,7 @@ Triggered when this page is about to exit after the user refreshes or closes the | Type | Description | | ------- | ---------------------------------------- | -| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\** component of the user's operation.| +| boolean | If the callback returns **true**, the application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **\** component to exit the current page based on the user operation. If the callback returns **false**, the **\** component cannot trigger the system dialog box.| **Example** @@ -1301,7 +1317,7 @@ Triggered when this page is about to exit after the user refreshes or closes the @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1338,7 +1354,7 @@ Triggered when this page is about to exit after the user refreshes or closes the onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) -Triggered when **confirm()** is invoked by the web page. +Called when **confirm()** is invoked by the web page. **Parameters** @@ -1352,7 +1368,7 @@ Triggered when **confirm()** is invoked by the web page. | Type | Description | | ------- | ---------------------------------------- | -| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\** component of the user's operation.| +| boolean | If the callback returns **true**, the application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **\** component to exit the current page based on the user operation. If the callback returns **false**, the **\** component cannot trigger the system dialog box.| **Example** @@ -1362,7 +1378,7 @@ Triggered when **confirm()** is invoked by the web page. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1412,7 +1428,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul | Type | Description | | ------- | ---------------------------------------- | -| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\** component of the user's operation.| +| boolean | If the callback returns **true**, the application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to instruct the **\** component to exit the current page based on the user operation. If the callback returns **false**, the **\** component cannot trigger the system dialog box.| **Example** @@ -1422,7 +1438,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1460,7 +1476,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul onConsole(callback: (event?: { message: ConsoleMessage }) => boolean) -Triggered to notify the host application of a JavaScript console message. +Called to notify the host application of a JavaScript console message. **Parameters** @@ -1482,7 +1498,7 @@ Triggered to notify the host application of a JavaScript console message. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1519,7 +1535,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1539,7 +1555,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void) -Triggered when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. +Called when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. **Parameters** @@ -1556,7 +1572,7 @@ Triggered when an error occurs during web page loading. For better results, simp @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1583,7 +1599,7 @@ Triggered when an error occurs during web page loading. For better results, simp onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: WebResourceResponse }) => void) -Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading. +Called when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading. **Parameters** @@ -1600,7 +1616,7 @@ Triggered when an HTTP error (the response code is greater than or equal to 400) @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1635,7 +1651,7 @@ Triggered when an HTTP error (the response code is greater than or equal to 400) onPageBegin(callback: (event?: { url: string }) => void) -Triggered when the web page starts to be loaded. This API is triggered only for the main frame content, and not for the iframe or frameset content. +Called when the web page starts to be loaded. This API is called only for the main frame content, and not for the iframe or frameset content. **Parameters** @@ -1651,7 +1667,7 @@ Triggered when the web page starts to be loaded. This API is triggered only for @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1668,7 +1684,7 @@ Triggered when the web page starts to be loaded. This API is triggered only for onPageEnd(callback: (event?: { url: string }) => void) -Triggered when the web page loading is complete. This API is triggered only for the main frame content. +Called when the web page loading is complete. This API takes effect only for the main frame content. **Parameters** @@ -1684,7 +1700,7 @@ Triggered when the web page loading is complete. This API is triggered only for @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1700,7 +1716,7 @@ Triggered when the web page loading is complete. This API is triggered only for onProgressChange(callback: (event?: { newProgress: number }) => void) -Triggered when the web page loading progress changes. +Called when the web page loading progress changes. **Parameters** @@ -1716,7 +1732,7 @@ Triggered when the web page loading progress changes. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1732,7 +1748,7 @@ Triggered when the web page loading progress changes. onTitleReceive(callback: (event?: { title: string }) => void) -Triggered when the document title of the web page is changed. +Called when the document title of the web page is changed. **Parameters** @@ -1748,7 +1764,7 @@ Triggered when the document title of the web page is changed. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1764,7 +1780,7 @@ Triggered when the document title of the web page is changed. onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void) -Triggered when loading of the web page is complete. This API is used by an application to update the historical link it accessed. +Called when loading of the web page is complete. This API is used by an application to update the historical link it accessed.. **Parameters** @@ -1781,7 +1797,7 @@ Triggered when loading of the web page is complete. This API is used by an appli @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1797,7 +1813,7 @@ Triggered when loading of the web page is complete. This API is used by an appli onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) -Triggered when the rendering process exits abnormally. +Called when the rendering process exits abnormally. **Parameters** @@ -1813,7 +1829,7 @@ Triggered when the rendering process exits abnormally. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'chrome://crash/', controller: this.controller }) @@ -1829,7 +1845,7 @@ Triggered when the rendering process exits abnormally. onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => boolean) -Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. +Called to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. **Parameters** @@ -1842,7 +1858,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t | Type | Description | | ------- | ---------------------------------------- | -| boolean | The value **true** means that the pop-up window provided by the system is displayed. The value **false** means that the default web pop-up window is displayed.| +| boolean | The value **true** means that the pop-up window provided by the system is displayed. If the callback returns **false**, the **\** component cannot trigger the system dialog box.| **Example** @@ -1885,7 +1901,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t onResourceLoad(callback: (event: {url: string}) => void) -Invoked to notify the **\** component of the URL of the loaded resource file. +Called to notify the **\** component of the URL of the loaded resource file. **Parameters** @@ -1901,7 +1917,7 @@ Invoked to notify the **\** component of the URL of the loaded resource fil @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1917,7 +1933,7 @@ Invoked to notify the **\** component of the URL of the loaded resource fil onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void) -Invoked when the display ratio of this page changes. +Called when the display ratio of this page changes. **Parameters** @@ -1934,7 +1950,7 @@ Invoked when the display ratio of this page changes. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1950,7 +1966,7 @@ Invoked when the display ratio of this page changes. onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) -Triggered when the **\** component is about to access a URL. This API is used to determine whether to block the access. +Called when the **\** component is about to access a URL. This API is used to determine whether to block the access. **Parameters** @@ -1972,7 +1988,7 @@ Triggered when the **\** component is about to access a URL. This API is us @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -1989,7 +2005,7 @@ Triggered when the **\** component is about to access a URL. This API is us onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse) -Invoked when the **\** component is about to access a URL. This API is used to block the URL and return the response data. +Called when the **\** component is about to access a URL. This API is used to block the URL and return the response data. **Parameters** @@ -2054,7 +2070,7 @@ Invoked when the **\** component is about to access a URL. This API is used onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, realm: string}) => boolean) -Invoked when an HTTP authentication request is received. +Called when an HTTP authentication request is received. **Parameters** @@ -2080,7 +2096,7 @@ Invoked when an HTTP authentication request is received. struct WebComponent { controller: WebController = new WebController() httpAuth: boolean = false - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2123,7 +2139,7 @@ Invoked when an HTTP authentication request is received. onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslError }) => void) -Invoked when an SSL error occurs during resource loading. +Called when an SSL error occurs during resource loading. **Parameters** @@ -2141,7 +2157,7 @@ Invoked when an SSL error occurs during resource loading. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -2176,7 +2192,7 @@ Invoked when an SSL error occurs during resource loading. onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array, issuers : Array}) => void) -Invoked when an SSL client certificate request is received. +Called when an SSL client certificate request is received. **Parameters** @@ -2231,7 +2247,7 @@ Invoked when an SSL client certificate request is received. onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) -Invoked when a permission request is received. +Called when a permission request is received. **Parameters** @@ -2320,7 +2336,7 @@ Shows a context menu after the user clicks the right mouse button or long presse onScroll(callback: (event: {xOffset: number, yOffset: number}) => void) -Invoked when the scrollbar of the page scrolls. +Called when the scrollbar of the page scrolls. **Parameters** @@ -2398,7 +2414,7 @@ Registers a callback for receiving a request to obtain the geolocation informati onGeolocationHide(callback: () => void) -Triggered to notify the user that the request for obtaining the geolocation information received when **[onGeolocationShow](#ongeolocationshow)** is called has been canceled. +Called to notify the user that the request for obtaining the geolocation information received when **[onGeolocationShow](#ongeolocationshow)** is called has been canceled. **Parameters** @@ -2430,7 +2446,7 @@ Triggered to notify the user that the request for obtaining the geolocation info onFullScreenEnter(callback: (event: { handler: FullScreenExitHandler }) => void) -Registers a callback for the component's entering into full screen mode. +Called when the component enters full screen mode. **Parameters** @@ -2463,7 +2479,7 @@ Registers a callback for the component's entering into full screen mode. onFullScreenExit(callback: () => void) -Registers a callback for the component's exiting full screen mode. +Called when the component exits full screen mode. **Parameters** @@ -2568,7 +2584,7 @@ Registers a callback for window closure. onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute -Invoked to notify the caller of the search result on the web page. +Called to notify the caller of the search result on the web page. **Parameters** @@ -2603,7 +2619,7 @@ Invoked to notify the caller of the search result on the web page. onDataResubmitted(callback: (event: {handler: DataResubmissionHandler}) => void) -Invoked when the web form data is resubmitted. +Called when the web form data is resubmitted. **Parameters** @@ -2636,7 +2652,7 @@ Invoked when the web form data is resubmitted. onPageVisible(callback: (event: {url: string}) => void) -Invoked when the old page is not displayed and the new page is about to be visible. +Called when the old page is not displayed and the new page is about to be visible. **Parameters** @@ -2668,7 +2684,7 @@ Invoked when the old page is not displayed and the new page is about to be visib onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) -Invoked when the key event is intercepted, before being consumed by the Webview. +Called when the key event is intercepted, before being consumed by the Webview. **Parameters** @@ -2710,7 +2726,7 @@ Invoked when the key event is intercepted, before being consumed by the Webview. onTouchIconUrlReceived(callback: (event: {url: string, precomposed: boolean}) => void) -Invoked when an apple-touch-icon URL is received. +Called when an apple-touch-icon URL is received. **Parameters** @@ -2743,7 +2759,7 @@ Invoked when an apple-touch-icon URL is received. onFaviconReceived(callback: (event: {favicon: image.PixelMap}) => void) -Invoked when this web page receives a new favicon. +Called when this web page receives a new favicon. **Parameters** @@ -3243,7 +3259,7 @@ Performs HTTP authentication with the user name and password provided by the use isHttpAuthInfoSaved(): boolean -Uses the password cached on the server for authentication. +Uses the account name and password cached on the server for authentication. **Return value** @@ -3611,7 +3627,7 @@ This API is deprecated since API version 9. You are advised to use [requestFocus @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('requestFocus') @@ -3646,7 +3662,7 @@ This API is deprecated since API version 9. You are advised to use [accessBackwa @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('accessBackward') @@ -3682,7 +3698,7 @@ This API is deprecated since API version 9. You are advised to use [accessForwar @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('accessForward') @@ -3725,7 +3741,7 @@ This API is deprecated since API version 9. You are advised to use [accessStep @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('forward') @@ -3818,7 +3834,7 @@ Performs a specific number of steps forward or backward on the current page base struct WebComponent { controller: WebController = new WebController() @State step: number = -2 - + build() { Column() { Button('backOrForward') @@ -3854,7 +3870,7 @@ This API is deprecated since API version 9. You are advised to use [deleteJavaSc struct WebComponent { controller: WebController = new WebController() @State name: string = 'Object' - + build() { Column() { Button('deleteJavaScriptRegister') @@ -3871,7 +3887,7 @@ This API is deprecated since API version 9. You are advised to use [deleteJavaSc getHitTest(): HitTestType -Obtains the element type of the area being clicked. +Obtains the element type of the area being clicked. This API is deprecated since API version 9. You are advised to use [getHitTest9+](../apis/js-apis-webview.md#gethittest). @@ -3889,7 +3905,7 @@ This API is deprecated since API version 9. You are advised to use [getHitTest** component, which can be used for **\< @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getWebId') @@ -3989,7 +4005,7 @@ Obtains the title of the current web page. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getTitle') @@ -4022,7 +4038,7 @@ Obtains the height of the current web page. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getPageHeight') @@ -4055,7 +4071,7 @@ Obtains the default user agent of the current web page. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getDefaultUserAgent') @@ -4099,7 +4115,7 @@ This API is deprecated since API version 9. You are advised to use [loadData @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('loadUrl') @@ -4160,7 +4176,7 @@ This API is deprecated since API version 9. You are advised to use [loadUrl onActive(): void -Invoked when the **\** component enters the active state. +Called when the **\** component enters the active state. This API is deprecated since API version 9. You are advised to use [onActive9+](../apis/js-apis-webview.md#onactive). @@ -4172,7 +4188,7 @@ This API is deprecated since API version 9. You are advised to use [onActive** component enters the inactive state. +Called when the **\** component enters the inactive state. This API is deprecated since API version 9. You are advised to use [onInactive9+](../apis/js-apis-webview.md#oninactive). @@ -4201,7 +4217,7 @@ This API is deprecated since API version 9. You are advised to use [onInactive9+< struct WebComponent { controller: WebController = new WebController() @State factor: number = 1 - + build() { Column() { Button('zoom') @@ -4268,7 +4284,7 @@ Zooms in on this web page by 20%. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('zoomIn') @@ -4301,7 +4317,7 @@ Zooms out of this web page by 20%. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('zoomOut') @@ -4319,7 +4335,7 @@ Zooms out of this web page by 20%. refresh() -Invoked when the **\** component refreshes the web page. +Called when the **\** component refreshes the web page. This API is deprecated since API version 9. You are advised to use [refresh9+](../apis/js-apis-webview.md#refresh). @@ -4331,7 +4347,7 @@ This API is deprecated since API version 9. You are advised to use [refresh @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('refresh') @@ -4409,7 +4425,7 @@ This API is deprecated since API version 9. You are advised to use [registerJava } - + ``` ### runJavaScript(deprecated) @@ -4489,7 +4505,7 @@ This API is deprecated since API version 9. You are advised to use [stop9+< @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('stop') @@ -4518,7 +4534,7 @@ This API is deprecated since API version 9. You are advised to use [clearHistory @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('clearHistory') @@ -4605,7 +4621,7 @@ Obtains the cookie management object of the **\** component. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getCookieManager') @@ -4959,7 +4975,7 @@ Sets the cookie. This API returns the result synchronously. Returns **true** if @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('setCookie') @@ -4992,7 +5008,7 @@ Saves the cookies in the memory to the drive. This API returns the result synchr @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('saveCookieSync') @@ -5032,7 +5048,7 @@ Obtains the cookie value corresponding to the specified URL. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('getCookie') @@ -5073,7 +5089,7 @@ Sets a cookie value for the specified URL. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('setCookie') @@ -5107,7 +5123,7 @@ Saves the cookies in the memory to the drive. This API uses a promise to return @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('saveCookieAsync') @@ -5146,7 +5162,7 @@ Saves the cookies in the memory to the drive. This API uses an asynchronous call @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('saveCookieAsync') @@ -5181,7 +5197,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('isCookieAllowed') @@ -5215,7 +5231,7 @@ Sets whether the **WebCookieManager** instance has the permission to send and re @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('putAcceptCookieEnabled') @@ -5248,7 +5264,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('isThirdPartyCookieAllowed') @@ -5282,7 +5298,7 @@ Sets whether the **WebCookieManager** instance has the permission to send and re @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('putAcceptThirdPartyCookieEnabled') @@ -5315,7 +5331,7 @@ Checks whether cookies exist. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('existCookie') @@ -5343,7 +5359,7 @@ Deletes all cookies. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('deleteEntireCookie') @@ -5370,7 +5386,7 @@ Deletes all session cookies. @Component struct WebComponent { controller: WebController = new WebController() - + build() { Column() { Button('deleteSessionCookie') @@ -5670,7 +5686,7 @@ Sets the message port in this object. For the complete sample code, see [postMes struct WebComponent { controller: WebController = new WebController() ports: WebMessagePort[] = null - + build() { Column() { Button('setPorts') diff --git a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md index 97b08d90ca88b2cef08ac931cc6a6405c2236dd5..0a33bf8135951134bb63fcd80caba5c00b77e683 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md @@ -35,9 +35,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | selectedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected item.
Default value: **0x1F0A59F7** | | popupBackground | [ResourceColor](ts-types.md#resourcecolor) | Background color of the pop-up text.
Default value: **0xFFF1F3F5** | | usingPopup | boolean | Whether to use pop-up text.
Default value: **false** | -| selectedFont | [Font](ts-types.md#font) | Font style of the selected text.
Default value:
{
fontSize:10,
fontStyle:FontStyle.Normal,
fontWeight:FontWeight.Normal,
fontFamily:HarmonyOS Sans
} | -| popupFont | [Font](ts-types.md#font) | Font style of the pop-up text.
Default value:
{
fontSize:10,
fontStyle:FontStyle.Normal,
fontWeight:FontWeight.Normal,
fontFamily:HarmonyOS Sans
} | -| font | [Font](ts-types.md#font) | Default font style of the alphabetic index bar.
Default value:
{
fontSize:10,
fontStyle:FontStyle.Normal,
fontWeight:FontWeight.Normal,
fontFamily:HarmonyOS Sans
} | +| selectedFont | [Font](ts-types.md#font) | Font style of the selected text.
Default value:
{
size:10,
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
} | +| popupFont | [Font](ts-types.md#font) | Font style of the pop-up text.
Default value:
{
size:10,
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
} | +| font | [Font](ts-types.md#font) | Default font style of the alphabetic index bar.
Default value:
{
size:10,
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
} | | itemSize | string \| number | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. This attribute cannot be set to a percentage.
Default value: **24.0** | | alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported.
Default value: **IndexerAlign.Right**| | selected | number | Index of the selected item.
Default value: **0**| diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index 9de0b8a25a4bf88c91c0883561cc9ff61b63c086..5ff83b20ec921e32c2b3c4e6d078f89941ec55d2 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -1,6 +1,6 @@ # ListItem -The **\** component displays specific items in the list. Its width occupies the **\** component by default and must be used together with **\**. +The **\** component displays specific items in the list. It must be used together with **\**. > **NOTE** > @@ -22,7 +22,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| sticky(deprecated) | [Sticky](#stickydeprecated) | Sticky effect of the list item.
Default value: **Sticky.None**
This API is deprecated since API version 9. You are advised to use **sticky** of the [\](ts-container-list.md#attributes) component. | +| sticky(deprecated) | [Sticky](#stickydeprecated) | Sticky effect of the list item.
Default value: **Sticky.None**
This API is deprecated since API version 9. You are advised to use **sticky** of the [\](ts-container-list.md#attributes) component.| | editable(deprecated) | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.
This API is deprecated since API version 9.
Default value: **false**| | selectable8+ | boolean | Whether the current list item is selectable by mouse drag.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| | swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Component displayed when the list item is swiped out from the screen edge.
- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).
- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
| diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index 90d17f70d4fc01ef8e80d9f13069e6d08b5d02fd..a0efd8457d392485781624d95fef53017706964a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -131,7 +131,7 @@ Scrolls to the item with the specified index. > **NOTE** > -> Only the **\** component is supported. +> Only the **\**, **\**, and **\** components are supported. **Parameters** diff --git a/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md b/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md index 7e38b90f2497876d12af34b965cc34ed4e71af21..7c62710b64759d42e205eb91b010fb50e478e108 100644 --- a/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md +++ b/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md @@ -50,7 +50,7 @@ struct TransitionExample { }) }) if (this.flag) { - // Apply different transition effects to the appearance and disappearance of the image. + // Apply different transition effects to the showing and hiding of the image. Image($r('app.media.testImg')).width(300).height(300) .transition({ type: TransitionType.Insert, scale: { x: 0, y: 1.0 } }) .transition({ type: TransitionType.Delete, rotate: { angle: 180 } }) @@ -60,4 +60,20 @@ struct TransitionExample { } ``` -![animateTo](figures/animateTo.gif) +Diagrams: + +When the image is completely displayed: + +![animationComponent1](figures/animationComponent1.png) + +When the transition effect of 180° clockwise rotation is applied to the hiding of the image: + +![animationComponent3](figures/animationComponent3.png) + +When the image disappears completely: + +![animationComponent2](figures/animationComponent2.png) + +When the transition effect of zooming in twice horizontally is applied to the image displayed: + +![animationComponent4](figures/animationComponent4.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md index 363bb92058913192b1353e819c27eb74bc0cdb63..53cc8c854b46f4acd7e8a51d618ad85595bb2d2e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md @@ -201,7 +201,7 @@ Sample code for **focusControl.requestFocus**: Use the **focusContrl.requestFocus** API to enable a specified component to obtain focus. ```ts // requestFocus.ets -import prompt from '@ohos.prompt' +import promptAction from '@ohos.promptAction'; @Entry @Component @@ -253,9 +253,9 @@ struct RequestFocusExample { .onClick(() => { var res = focusControl.requestFocus(this.selectId) // Enable the component selected by this.selectId to obtain focus. if (res) { - prompt.showToast({message: 'Request success'}) + promptAction.showToast({message: 'Request success'}) } else { - prompt.showToast({message: 'Request failed'}) + promptAction.showToast({message: 'Request failed'}) } }) } diff --git a/en/application-dev/task-management/continuous-task-dev-guide.md b/en/application-dev/task-management/continuous-task-dev-guide.md index b278a686e4267d7b62d123c2f6f2c338a9278ab7..b301ee707bf62ce6cf773be2b744d905e807da42 100644 --- a/en/application-dev/task-management/continuous-task-dev-guide.md +++ b/en/application-dev/task-management/continuous-task-dev-guide.md @@ -89,18 +89,22 @@ struct Index { }; // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } } stopContinuousTask() { @@ -151,7 +155,7 @@ struct Index { ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.app.ability.wantAgent'; const MSG_SEND_METHOD: string = 'CallSendMsg'; @@ -176,25 +180,29 @@ function startContinuousTask() { }; // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((error) => { + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((error) => { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + }); + } catch (error) { console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } } function stopContinuousTask() { try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { + }).catch((error) => { console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); }); } catch (error) { @@ -312,7 +320,7 @@ If an application needs to interact with a continuous task in the background (fo 2. Call the APIs for requesting and canceling a continuous task in the Service ability. ```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; import wantAgent from '@ohos.app.ability.wantAgent'; import rpc from "@ohos.rpc"; @@ -335,18 +343,22 @@ function startContinuousTask() { }; // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); + try { + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); + } catch (error) { + console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`); + } } function stopContinuousTask() { @@ -396,7 +408,7 @@ class MyStub extends rpc.RemoteObject { } export default { - onStart(want) { + onStart() { console.info('ServiceAbility onStart'); mMyStub = new MyStub("ServiceAbility-test"); // Call the API to start the task. @@ -416,7 +428,7 @@ export default { onDisconnect() { console.info('ServiceAbility onDisconnect'); }, - onCommand(want, restart, startId) { + onCommand(want, startId) { console.info('ServiceAbility onCommand'); } }; diff --git a/en/application-dev/tools/aa-tool.md b/en/application-dev/tools/aa-tool.md index e03cdd52c6df142c13a06c918ae242c4115b323c..69db1fd8814bd5880063bb063f6c77db1b4a281c 100644 --- a/en/application-dev/tools/aa-tool.md +++ b/en/application-dev/tools/aa-tool.md @@ -6,14 +6,14 @@ The Ability Assistant provides the application debugging and testing capabilitie - help -Displays help information for the Ability Assistant. - -**Return value** - -Returns the help information. - -**Method** - + Displays help information for the Ability Assistant. + + **Return value** + + Returns the help information. + + **Method** + ```bash aa help @@ -22,97 +22,97 @@ Returns the help information. - start -Starts an application component. The target component can be the PageAbility and ServiceAbility components of the FA model or the UIAbility and ServiceExtensionAbility components of the Stage model. The **visible** tag in the configuration file of the target component cannot be set to **false**. - + Starts an application component. The target component can be the PageAbility and ServiceAbility components of the FA model or the UIAbility and ServiceExtensionAbility components of the Stage model. The **visible** tag in the configuration file of the target component cannot be set to **false**. + | Name| Description| | -------- | -------- | | -h/--help | Help information.| | -d | Device ID. Optional.| | -a | Ability name. Mandatory.| | -b | Bundle name. Mandatory.| -| -D | Debugging mode. Optional.| - -**Return value** - -Returns "start ability successfully." if the ability is started; returns "error: failed to start ability." and the corresponding error information otherwise. - -**Method** - + | -D | Debugging mode. Optional.| + + **Return value** + + Returns "start ability successfully." if the ability is started; returns "error: failed to start ability." and the corresponding error information otherwise. + + **Method** + ```bash aa start [-d ] -a -b [-D] -``` - + ``` + - stop-service -Stops a ServiceAbility. - + Stops a ServiceAbility. + | Name| Description| | -------- | -------- | | -h/--help | Help information.| | -d | Device ID. Optional.| | -a | Ability name. Mandatory.| -| -b | Bundle name. Mandatory.| - -**Return value** - -Returns "stop service ability successfully." if the ServiceAbility is stopped; returns "error: failed to stop service ability." otherwise. - -**Method** - + | -b | Bundle name. Mandatory.| + + **Return value** + + Returns "stop service ability successfully." if the ServiceAbility is stopped; returns "error: failed to stop service ability." otherwise. + + **Method** + ```bash aa stop-service [-d ] -a -b -``` - + ``` + - dump - + Prints information about an application component. - | Name| Level-2 Parameter| Description| + | Name| Level-2 Parameter| Description| | -------- | -------- | -------- | | -h/--help | - | Help information.| | -a/--all | - | Application component information in all missions.| - | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Mission stack information.
The following values are available for **type**:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | + | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| For better management, the service side maintains four types of MissionLists, as described below:
- **NORMAL**: MissionList that is started normally. For example, if A starts B and C, the corresponding MissionList is A->B->C.
- **DEFAULT_STANDARD**: If a MissionList is damaged, missions with the launch type set to **standard** are removed to this MissionList. The Missions in it are not associated with each other.
- **DEFAULT_SINGLE**: If a MissionList is damaged, missions with the launch type set to **singleton** are removed to this MissionList. The Missions in it are not associated with each other.
- **LAUNCHER**: MissionList for launcher abilities. | | -e/--extension | elementName | Extended component information.| | -u/--userId | UserId | Mission stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: **aa dump -a -u 100** and **aa dump -d -u 100**.| | -d/--data | - | DataAbility information.| -| -i/--ability | AbilityRecord ID | Detailed information about an application component.| + | -i/--ability | AbilityRecord ID | Detailed information about an application component.| | -c/--client | - | Detailed information about an application component. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| **Method** - + ```bash -aa dump -a + aa dump -a ``` ![aa-dump-a](figures/aa-dump-a.png) - + ```bash -aa dump -l + aa dump -l ``` ![aa-dump-l](figures/aa-dump-l.png) - + ```bash -aa dump -i 12 + aa dump -i 12 ``` - ![aa-dump-i](figures/aa-dump-i.png) - + ![aa-dump-i](figures/aa-dump-i.png) + - force-stop -Forcibly stops a process based on the bundle name. - -**Return value** - -Returns "force stop process successfully." if the process is forcibly stopped; returns "error: failed to force stop process." otherwise. - -**Method** - + Forcibly stops a process based on the bundle name. + + **Return value** + + Returns "force stop process successfully." if the process is forcibly stopped; returns "error: failed to force stop process." otherwise. + + **Method** + ```bash aa force-stop diff --git a/en/application-dev/ui/ui-ts-building-data-model.md b/en/application-dev/ui/ui-ts-building-data-model.md index bb3454cc6299d4910445caaae2e14f7478591425..c520596252a9652ce8ad9e00e21a0e33a93e2ba3 100644 --- a/en/application-dev/ui/ui-ts-building-data-model.md +++ b/en/application-dev/ui/ui-ts-building-data-model.md @@ -1,21 +1,19 @@ # Building a Food Data Model - -On the created page, we use various items to describe food, such as food names, calories, proteins, fats, carbohydrates, and vitamin C. This form of coding is impractical in actual development. Therefore, you need to create food data models to store and manage data in a unified manner. +In real-world development, it is impractical to describe all aspects of food in code, including the food name and nutrition facts. This is where the food data model comes into the picture. With the food data model, you can store and manage data in a unified manner. ![en-us_image_0000001267767897](figures/en-us_image_0000001267767897.png) -1. Create a folder named model and create a file named FoodData.ets therein. - -![en-us_image_0000001223127760](figures/en-us_image_0000001223127760.png) - -2. Define a food data storage model, FoodData, and an enum variable, Category. The FoodData class contains the food ID, name, category, image, calories, protein, fat, carbohydrates, and vitamin C attributes. - The ArkTS programming language is an extension of the TS language and also supports the TS syntax. +1. Create a folder named **model** and create a file named **FoodData.ets** therein. + ![en-us_image_0000001223127760](figures/en-us_image_0000001223127760.png) - ``` +2. Define a food data storage model, **FoodData**, and an enum variable, **Category**. The **FoodData** class contains **id**, **name**, **category**, **image**, **calories**, **protein**, **fat**, **carbohydrates**, and **vitaminC** attributes. + The ArkTS programming language is an extension of the TS language and also supports the TS syntax. + + ```ts enum Category { Fruit, Vegetable, @@ -50,14 +48,21 @@ On the created page, we use various items to describe food, such as food names, } ``` -3. Store food image resources in the resources > base > media directory. Use food names as the image names. - -4. Create food resource data. Create FoodDataModels.ets in the model folder and declare a food composition array, FoodComposition on the page. - In this example, you can customize more data resources when needed. Use LazyForEach to load data if a large amount of food data is involved. +3. Store food images in the **resources** > **base** > **media** directory. Use food names as the image names. -5. Create the initializeOnStartUp method to initialize the FoodData array. Export the FoodData class from FoodData.ets, and import FoodData and Category in FoodDataModels.ets. +4. Create food resource data. Create **FoodDataModels.ets** in the **model** folder and declare the food composition array **FoodComposition** on the page. The following example creates two pieces of food data. + ```ts + const FoodComposition: any[] = [ + { 'name': 'Tomato', 'image': $r('app.media.Tomato'), 'category': Category.Vegetable, 'calories': 17, 'protein': 0.9, 'fat': 0.2, 'carbohydrates': 3.9, 'vitaminC': 17.8 }, + { 'name': 'Walnut', 'image': $r('app.media.Walnut'), 'category': Category.Nut, 'calories': 654 , 'protein': 15, 'fat': 65, 'carbohydrates': 14, 'vitaminC': 1.3 } + ] ``` + + In real-world development, you can customize more data resources when needed. Use [Lazy Loading](../quick-start/arkts-rendering-control.md#lazy-loading) to load data if a large amount of food data is involved. + +5. Create the **initializeOnStartUp** method to initialize the **FoodData** array. Export the **FoodData** class from **FoodData.ets**, and import **FoodData** and **Category** in **FoodDataModels.ets**. + ```ts // FoodData.ets export enum Category { ...... diff --git a/en/application-dev/ui/ui-ts-layout-grid-container-new.md b/en/application-dev/ui/ui-ts-layout-grid-container-new.md index 8afee0cc3d48894ff646a4251c38227daef3c0fb..f51288b2a77901abf6620a6bcc8f0499fb647289 100644 --- a/en/application-dev/ui/ui-ts-layout-grid-container-new.md +++ b/en/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -27,12 +27,12 @@ After you set the breakpoints, the layout listens for changes in the application The grid system defines breakpoints, which are screen width types in effect, based on the horizontal width (screen density pixels, in vp) of the screens. You can use the breakpoints to meet specific layout requirements. By default, the grid system provides four breakpoints: xs, sm, md, and lg. -| Breakpoint | Value Range (vp)| -| --------| ------ | -| xs | [0, 320) | -| sm | [320, 520) | -| md | [520, 840) | -| lg | [840, +∞) | +| Breakpoint | Value Range (vp)| +| --------| ------ | +| xs | [0, 320) | +| sm | [320, 520) | +| md | [520, 840) | +| lg | [840, +∞) | In the **\** component, you can use **breakpoints** to customize the value range of breakpoints. A maximum of six breakpoints are supported. In addition to the four default breakpoints, you can also enable the xl and xxl breakpoints for your application window layout. @@ -83,15 +83,15 @@ GridRow({ } }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") }.backgroundColor(color) }) } -``` + ``` ![](figures/breakpoints.gif) - + ### Columns @@ -173,7 +173,7 @@ In the **\**, **columns** is used to set the total number of columns in ``` ![](figures/columns3.gif) - As shown above, if **columns** is only set for the sm and md screen size types, screen sizes smaller than sm use the default value 12, and screen sizes larger than md (lg, xl, and xxl) use the value of **columns** of the md type. + As shown above, if **columns** is only set for the sm and md screen size types, screen sizes smaller than sm use the default value **12**, and screen sizes larger than md (lg, xl, and xxl) use the value of **columns** of the md type. ### Gutters @@ -264,7 +264,7 @@ Sets the number of columns occupied by a child component in the grid layout, whi ForEach(this.bgColors, (color, index) => { GridCol({ span: 2 }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") } .backgroundColor(color) @@ -281,7 +281,7 @@ Sets the number of columns occupied by a child component in the grid layout, whi ForEach(this.bgColors, (color, index) => { GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") } .backgroundColor(color) @@ -333,8 +333,8 @@ Sets the column offset of a child component relative to the previous child compo ### order - Sets the sequence number of a child component in the grid layout. If a child component shares an **order** value with another child component or does not have **order** set, it is displayed based on its code sequence number. A child components with a larger **order** value is placed before the one with a smaller **order** value. - If **order** is not set for all child components, those that have **order** set are displayed after those that do not have **order** set and are sorted in descending order based on the value. +Sets the sequence number of a child component in the grid layout. If a child component shares an **order** value with another child component or does not have **order** set, it is displayed based on its code sequence number. A child components with a smaller **order** value is placed before the one with a larger **order** value. +If **order** is not set for all child components, those that have **order** set are displayed after those that do not have **order** set and are sorted in ascending order based on the value. - When the value type is number, child components are sorted in the same order across screen sizes. diff --git a/en/application-dev/windowmanager/application-window-fa.md b/en/application-dev/windowmanager/application-window-fa.md index b2123e720b1bf1cb15cfe648597e6f82e7b3dae4..ee7848d49aaccd039c59a1bac2553f0b485ecc1c 100644 --- a/en/application-dev/windowmanager/application-window-fa.md +++ b/en/application-dev/windowmanager/application-window-fa.md @@ -52,7 +52,7 @@ You can create a subwindow, such as a dialog box, and set its properties. let windowClass = null; // Method 1: Create a subwindow. - let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP, ctx: this.context}; + let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP}; window.createWindow(config, (err, data) => { if (err.code) { console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); diff --git a/en/application-dev/windowmanager/application-window-stage.md b/en/application-dev/windowmanager/application-window-stage.md index 709d58ba9f469f11a3675f8fd4326e1b490a1b5d..c9d15a6227008938ed361929f6811596d55ca2ad 100644 --- a/en/application-dev/windowmanager/application-window-stage.md +++ b/en/application-dev/windowmanager/application-window-stage.md @@ -67,9 +67,9 @@ In the stage model, the main window of an application is created and maintained Call **loadContent** to load the page content to the main window. ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { // 1. Obtain the main window of the application. let windowClass = null; @@ -127,11 +127,11 @@ You can create an application subwindow, such as a dialog box, and set its prope When the subwindow is no longer needed, you can call **destroyWindow** to destroy it. ```ts - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; let windowStage_ = null; let sub_windowClass = null; - class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { showSubWindow() { // 1. Create a subwindow. windowStage_.createSubWindow("mySubWindow", (err, data) => { @@ -220,9 +220,9 @@ To create a better video watching and gaming experience, you can use the immersi Call **loadContent** to load the content to the immersive window. ```ts - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; - class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { // 1. Obtain the main window of the application. let windowClass = null; @@ -303,7 +303,7 @@ A floating window is created based on an existing task. It is always displayed i "name" : "ohos.permission.SYSTEM_FLOAT_WINDOW", "usedScene": { "abilities": [ - "MainAbility" + "EntryAbility" ], "when":"inuse" } @@ -330,11 +330,11 @@ A floating window is created based on an existing task. It is always displayed i When the floating window is no longer needed, you can call **destroyWindow** to destroy it. ```ts - import Ability from '@ohos.application.Ability' - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import ExtensionContext from '@ohos.app.ability.ServiceExtensionAbility'; import window from '@ohos.window'; - class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { // 2. Create a floating window. let windowClass = null; @@ -390,4 +390,3 @@ A floating window is created based on an existing task. It is always displayed i }; ``` - \ No newline at end of file diff --git a/en/application-dev/windowmanager/system-window-stage.md b/en/application-dev/windowmanager/system-window-stage.md index 33240f364106fdab17a34926bc225e0685b2d70b..01ea738913af6d167d2ae3fffd6b10d92f40b02a 100644 --- a/en/application-dev/windowmanager/system-window-stage.md +++ b/en/application-dev/windowmanager/system-window-stage.md @@ -58,12 +58,11 @@ This section uses the volume bar as an example to describe how to develop a syst When the volume bar window is no longer needed, you can call **hide** or **destroyWindow** to hide or destroy it. ```ts -import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; +import ExtensionContext from '@ohos.app.ability.ServiceExtensionAbility'; import window from '@ohos.window'; export default class ServiceExtensionAbility1 extends ExtensionContext { onCreate(want) { - console.log("[Demo] MainAbility onCreate") globalThis.abilityWant = want; // 1. Create a volume bar window. let windowClass = null; @@ -151,7 +150,6 @@ import window from '@ohos.window'; export default class ServiceExtensionAbility1 extends ExtensionContext { onCreate(want) { - console.log("[Demo] MainAbility onCreate") globalThis.abilityWant = want; // Create a volume bar window. let windowClass = null; diff --git a/en/contribute/OpenHarmony-build-rule.md b/en/contribute/OpenHarmony-build-rule.md new file mode 100644 index 0000000000000000000000000000000000000000..27f69325582cba08daf6eb66aebbf823c641af84 --- /dev/null +++ b/en/contribute/OpenHarmony-build-rule.md @@ -0,0 +1,613 @@ +# OpenHarmony Build Specifications + +## Overview + +This topic aims to guide OpenHarmony developers to enhance the build reproducibility, maintainability, and quality. The build standards team has analyzed a variety of typical build issues and summarized the build guidelines and recommendations in this topic. + +## General Build Principles + +**P01 Automate the entire build process.** + +Manual operations are error-prone and time-consuming. Automate all the build operations to make the build process more efficient and reliable. + +**P02 Make build projects and build environments code-based.** + +Use a high-level build framework such as CMake, Maven, and Gradle to describe build projects, and use Ansible or Dockerfile to describe build environments. + +This principle helps hide the complexity of the build system from developers. + +**P03 Make the build process reproducible and traceable.** + +Manage build dependencies and always explicitly specify fixed dependency versions to ensure version consistency. Incorporate build environments and build projects into the configuration file as configuration options to ensure that the build projects are traceable. + +**P04 Ensure that the build scripts are simple, clear, and easy to maintain.** + +Build scripts are also code and should be easy to read. + +**P05 Standardize the build process.** + +The build directory structure, dependencies, initialization, entry, and naming must be standardized to ensure consistency among all OpenHarmony products, platforms, and components for easier management and maintenance. + +## Build Projects + +### General Guidelines + +#### One-Click Build + +##### G.COM.01 Use build scripts to implement one-click, automated build by delivery unit. + +One-click, automated build means that no manual interventions are allowed throughout the entire build process (until the final delivery package is generated) in a build environment. + +Manual interventions include but are not limited to: manual parameter setting on the IDE; file directory creation or deletion; file creation, copying, moving, deletion, or renaming; manual setting of file attributes; file compression/decompression. + +Delivery unit refers to a product, platform, or component that can be independently compiled, loaded, deployed, and run. + +[Type] Requirement + +[Description] One-click build improves operation efficiency while greatly reducing the possibility of operation errors. + +[Negative Example] The one-click build of a component can be triggered only by the CI system but cannot be triggered locally. + +[Negative Example] Manually set the memory mapping address on the Xplorer IDE UI for a component, and then perform manual build. + +[Negative Example] Manually create the **r6c03_view\r6c03_client_view** directory for a component. + +[Positive Example] Use the python script to automatically create a directory. + +```python +dir_src = os.getcwd() +dir_client_view = r"r6c03_client_view" +# os.path is used to shield system differences. +dir_mk = os.path.join(dir_src, dir_client_view) + +cmd = "{0} {1}".format("mkdir", dir_mk) +cmd_re = subprocess.run(cmd) +``` + +#### Build Directory + +##### G.COM.02 DO NOT delete or modify source code files and their directory structures during build. + +[Type] Forbidden + +[Description] + +- If the source code directory structure is deleted or modified during the build, the build process will be non-reproducible. + +- During the build, the build output (including the target files, temporary files, and build logs) should not pollute the source code directory. + +- During the build, do not modify source files, including but not limited to copying, moving, and running **dos2unix** to convert the source code format. Any modification to the source files must be completed in the code preparation phase before the build. + +- The tool-triggered, automatic generation of source code must also be completed in the preparation phase before the build. If tools are used to automatically generate source code during the build, the source code generated (low-value and reproducible) must be isolated from the existing source code directory for better distinguishing, so as to reduce the complexity of the build system. + +[Exception] Some source code may be added or adjusted during patch build. + +##### G.COM.12 Provide appropriate permissions for files and directories created during the build. + +[Type] Requirement + +[Description] Directories or files of the target system that are created during the build must comply with the design of least privilege. For example, do not create directories or files with the **777** permission in the Linux system during the build. + +For details about common directory files and permissions in the Linux system, see the *Linux Security Configuration Standard*. + +#### Build Initialization + +##### G.COM.03 Provide the clean command for each component. + +- If the **clean** command is executed with no arguments specified, all target files, temporary files, and build logs in the build project of the current level will be cleared, and the **clean** commands of the lower-level build project are recursively called to restore the build projects to the initial state. +- If the **clean** command is executed with certain arguments specified, only the corresponding target files, temporary files, and build logs generated in the specified build will be cleared. + +[Type] Requirement + +[Description] The **clean** command prevents a build from being affected by historical build files and build logs, ensuring build reproducibility. The **clean** command without any arguments must be supported. The **clean** command with arguments applies only to internal delivery and local build. + +[Positive Example] + +``` +base_dir + |---build.suffix + |---logs + |---component_depository_1 + |---build.suffix + |---logs + |---component_depository_2 + |---build.suffix + |---logs + +# No arguments +base_dir/build.suffix clean +#....Call clean of component_depository_1 and component_depository_2. + +# With arguments: component name +base_dir/build.suffix clean component_depository_1 +#....Call clean of component_depository_1 only. + +# With arguments +component_depository_1/build.suffix clean makebin hert umpt +#....Call clean of the umpt board of component_depository_1. +``` + +##### G.COM.04 Clear legacy build files in the build environment before the build of a component. + +[Type] Requirement + +[Description] If code is downloaded for the first time and the build environment has been initialized, the build environment does not have legacy build files. In this case, you do not need to run the **clean** command. If build has been performed, run the **clean** command to clear legacy build files. + +#### Full Build + +##### G.COM.05 For a version release build, recompile all the archived deliverables (including all dependent platforms and components). DO NOT use incremental build. DO NOT change the installation disk by manually replacing files. + +A version release build refers to the build of a formally released product version (including all dependent platforms and components). + +[Type] Requirement + +[Description] Conducting incremental build after file modification may cause failures in updating some binary files and integrating new security build options into the version, causing inconsistent build results. Manually replacing files may make the build unreproducible and inconsistent. + + +#### Build Configurations + +Separate the build configuration data from the build script to prevent the build project architecture from decaying. Store configuration data, such as the source code path, build options, and target file path, in a file different from the file that stores the build script to minimize the maintenance cost of build scripts. + +##### G.COM.06 DO NOT use a file that is strongly bound to the operating system (for example, an Excel file) as a build configuration file. Use a file format recognized by different platforms, such as an XML file, as the build configuration file. + +[Type] Requirement + +[Description] Using an Excel configuration file brings the following problems: + +- The file calls Microsoft Office APIs during the build. Each time the Excel file is accessed, the Excel program is started in the background, causing slow responding. + +- A large number of Excel configurations require manual operations on the GUI, resulting in poor manageability. + +#### Build Logs + +##### G.COM.07 Generate simple and clear build logs, and use the format "timestamp + [module name] (optional) + log level + log content" for each log record. +[Type] Requirement + +You are advised to set the timestamp in the format of date and time, for example, *MM/dd/yyyy HH:mm:ss*. + +Log levels are classified into error, warning (warn), and information (info), either in lowercase or uppercase. + +You are advised to use square brackets ([]) to enclose each part of a log record. + +[Positive Example] + +[05/21/2020 00:12:40] [ERROR] mkdir: cannot create directory Permission denied. + +[Exception] If the entire log is automatically generated by a tool, you can skip the log file in the following way: Output "This project is built using + *tool name*" at the beginning of the log, for example, "This project is built using CMake." + +##### G.COM.08 Stop the build if error is displayed in the log. + +[Type] Requirement + +[Description] An error log indicates a build error that requires manual intervention, for example, an incorrect environment variable, tool version error, operating system error, or incorrect software source code. For a version release build, all errors generated during the build must be eliminated. DO NOT shield build errors. + +[Negative Example] A component is successfully built, but the build log contains a large amount of exception information, such as "fail", "critical", "cannot", "not found", "missing" and "no input files". + +##### G.COM.09 Retain only the logs of the current build in the build log file. + +[Type] Requirement + +[Description] Retaining historical build logs in the build log file may cause confusing. For example, when a new build fails, users may confuse the logs of historical successful builds with those of the new build and mistakenly consider the new build successful. + +##### G.COM.10 Add the corresponding module name to each log for quick fault locating. + +[Type] Recommendation + +[Description] If there are a large number of logs, it is difficult to quickly locate the module involved in a specific fault. Adding the corresponding module name facilitates quick fault locating. + +[Exception] The native logs of tools such as CMake contain the module paths, which can be used to locate the modules. For such logs, you do not need to add the module name information. + +#### Build Users + +##### G.COM.11 DO NOT use the super administrator **root** or system user for build. Instead, use a common user account. + +[Type] Requirement + +[Description] The super administrator **root** and system user have high system permissions. Using such an account for the build may cause the build environment to be tampered with. + +In the installation state, the **root** user account can be used. In the running state, use a common user account. If you need to run the **sudo** command for privilege escalation, comply with *IAM Security Design Specifications*. + +#### Build Output Files + +##### G.COM.12 Follow the industry conventions for build output file name extensions. + +[Type] Requirement + +[Description] An incorrect file name extension is misleading. + +The file name extensions of the output files, such as .lib and .obj files, must comply with the default naming rules of the build tools. + +[Negative Example] A text file is named ***Example*.lib**. + +[Negative Example] An object file is named ***Example*.a**. + +[Negative Example] A static library is named **lib*Example***, without a file name extension. + +[Positive Example] Query the common file name extension conventions at http://www.fileextension.org/, https://fileinfo.com/, https://www.file-extensions.org/, and http://file-extension.net/. + +Conventions about common file name extensions are as follows: + +| File Name Extension| Type Convention | File Name Extension| Type Convention | +| ---------- | -------------------- | ---------- | --------------- | +| .a | Static library | .so | Dynamic library | +| .o | Object file | .7z | 7-zip compressed file | +| .tar | TAR archive file | .gz/.gzip | GNU zip archive file| +| .pack | Java pack200 compressed file| .rar/.rar5 | RAR compressed file | + +### C/C++ Build Projects + +#### Build Directory + +##### G.C&C++.01 Standardize the build directory structure. + +Build directories are classified into Source Tree, Build Tree, and Install Tree by functionality. + +- Source Tree is the directory for storing source code and build scripts. +- Build Tree is the directory for storing build middleware. Generally, the directory name is **build**. +- Install Tree is the directory for storing build deliverables. The directory name is fixed at **output**. + +The Source Tree, Build Tree, and Install Tree directories should be isolated from each other and should not overlap. One directory cannot be used for two or more purposes. For example, it is prohibited that a directory is used as both Source Tree to store source code and Build Tree to store build middleware. + +Source Tree contains the following files and directories: + +- Build tool entry file, such as **CMakeLists.txt**. After the **add_subdirectory()** command is executed in the upper-level **CMakeLists.txt** file, the CMake automatically invokes the **CMakeLists.txt** files in the subdirectory and lower-level subdirectories. +- **build.*suffix*** script file, which is the one-click build entry. You only need to invoke this script to complete the build. In the build entry file name, *.suffix* (such as .bat, .sh, or .py) indicates the programming language used by the build script. +- **config.*suffix*** configuration file, which is used to store build options and is the unique entry for configuration. +- Build script directory, which is optional. For example, the **cmake** directory is used to store CMake scripts. CMake script files include macros, functions, and the toolchain. The **CMakeLists.txt** script contains CMake script files by executing the **include()** command, and invokes the macros and functions in the script files. +- Component code directory, which is used to store source code and build scripts of each component. + +Among the preceding files and directories, only the **CMakeLists.txt**, **build.*suffix***, and **config.*suffix*** files are mandatory. Other files and directories are optional and provided as examples for your better understanding. + +Build Tree contains the following directories: + +- **build** directory, which is used to store the build middleware. This directory may be created during the build process and may not exist in the Git repository. If the **build** directory is used to store build scripts, you can create another directory as Build Tree. + +Install Tree contains the following directories: + +- **output** directory, which is used to store deliverables. This directory may be created during the build process and may not exist in the Git repository. + +[Type] Requirement + +[Description] + +A typical directory structure is as follows: + +``` +base_dir + |---CMakeLists.txt ---| + |---build.suffix | + |---config.suffix | + |---cmake |--> Source Tree + |---component_1 | + |---component_2 | + |---...... | + |---component_n ---| + |---build ------> Build Tree + |---output ------> Install Tree +``` + +The directory structure of each component is similar to the top directory structure. Example: + +``` +component_1 + |---CMakeLists.txt ---| + |---build.suffix | + |---config.suffix | + |---cmake |--> Source Tree + |---module_1 | + |---module_2 | + |---...... | + |---module_n ---| + |---build ------> Build Tree + |---output ------> Install Tree +``` + +##### G.C&C++.02 DO NOT modify Source Tree in any form during the build process. + +[Type] Recommendation + +[Description] If Source Tree is modified during the build, the build process will be non-reproducible. + +The common operations for modifying Source Tree are as follows: + +- Patch installation +- Dotting +- Tailoring +- Automatic source code generation +- Modifying source code and then restoring it +- Adding, modifying, or deleting temporary files or directories +- Modifying the attribute or format of a file or directory (For example, modify the execute permission of a file or **dos2unix**.) + +Recommended operations are as follows: + +(1) Copy code to Build Tree, install a patch, and build the code. + +(2) As the dotting tool modifies source code and makes the build process untrustworthy, do not use the dotting tool during the build. Instead, upload the dotted code to the code repository and use the dotted code for the build. + +(3) Tailoring is an independent source code delivery requirement and can be considered as the code preparation phase. Source Tree in the versions before and after tailoring must not be modified during the build. + +(4) The automatically generated source code must be stored in Build Tree. + +(5) Modifying and then restoring source code is prohibited because the source code has changed during the build. + +(6) Temporary files or directories must be stored in Build Tree. + +(7) Ensure that the attributes and formats of files in the code repository are correct to prevent modifying them during the build. + +To check for Source Tree changes, run the **git status** command in the source code directory after the build. Source Tree should not have any change. The **git status** command may fail to detect changes to Source Tree where source code is modified and then restored. + +[Exception] + +(1) Changes in the Build Tree and Install Tree directories detected by the **git status** command are allowed. + +(2) Tailoring-caused changes detected by the **git status** command are allowed. + +##### G.C&C++.03 Use D:\*deliveryUnitName + versionNumber (optional)* and /usr1/*deliveryUnitName + versionNumber (optional)* as the build root directory in Windows and Linux, respectively. + +[Type] Recommendation + +[Description] Name the build root directory in the format of *deliveryUnitName + versionNumber*, where *versionNumber* is optional. DO NOT use the directory name that cannot identify a specific delivery unit, such as **build** or **code**. + +A clear build directory structure helps test personnel set build parameters, execute one-click build entries, and compare build results. + +The following are two root directory examples: + +``` +D:\Offering [Version (optional)] or /usr1/Offering [Version (optional)] +``` + +##### G.C&C++.04 Store all middleware generated during the build in Build Tree. + +[Type] Requirement + +[Description] The middleware generated during the build includes the makefile automatically generated by the build tool CMake, the source code automatically generated by the build script, the source code and patches copied by the build script, as well as the object files, repository files, executable programs, and build logs generated during the build. Store the middleware in Build Tree only, to avoid pollution to Source Tree or Install Tree. Do not store anything else in Build Tree. +Create the **logs** subdirectory under Build Tree and name build log files in .log format. + +##### G.C&C++.05 You can specify any directory except Source Tree and Install Tree as Build Tree. + +[Type] Requirement + +[Description] You can specify any directory other than Source Tree and Install Tree as Build Tree. In this way, the build process is irrelevant to the directory. The directory where the build is executed is Build Tree, and the build middleware is stored in this directory. Generally, the Build Tree directory name is **build**. You can also use another name. + +[Positive Example] Use CMake system variables **CMAKE_BINARY_DIR** and **CMAKE_CURRENT_BINARY_DIR** to access Build Tree to prevent coupling between Build Tree and Source Tree. + +##### G.C&C++.06 Store all deliverables in Install Tree. + +[Type] Requirement + +[Description] In the local build scenario, deliverables are directly installed on the host computer and run. In the cross-build scenario, deliverables run on the target computer. + +The deliverables include library files, executable programs, package files, and header files. They are binary interfaces provided by components. All the deliverables must be stored in Install Tree. + +Do not place any file other than deliverables (such as build middleware) in Install Tree. + +##### G.C&C++.07 You can specify any directory except Source Tree and Build Tree as Install Tree. + +[Type] Requirement + +[Description] You can specify any directory other than Source Tree and Build Tree as Install Tree. In this way, the build process is irrelevant to the directory. The Install Tree directory name is fixed at **output**. + +[Positive Example] The CMake build project supports the function of specifying the Install Tree directory through the system variable **CMAKE_INSTALL_PREFIX**. + +#### Build Entry + +##### G.C&C++.08 Provide a unique build entry for each delivery unit. Name all the build entry scripts in the **build.*suffix*** format, and store them in the build root directory. + +[Type] Requirement + +[Description] A unique build entry allows for a more efficient and automated build process. Each delivery unit has a unique build entry, making one-click, automated build possible. + +[Negative Example] The following build has multiple entry points. If no description document is provided, it is difficult to determine which entry point is correct. + +build.bat + +build_all.sh + +build_v6.sh + +[Positive Example] A typical one-click build script **build.sh** is as follows: + +```bash +#!/bin/bash + +if [ -d "build" ]; then + rm -fr build/* +else + mkdir build +fi + +if [ -d "output" ]; then + rm -fr output/* +else + mkdir output +fi + +cd build +cmake .. + +cpu_processor_num=$(grep processor /proc/cpuinfo | wc -l) +job_num=$(expr "$cpu_processor_num" \* 2) +echo Parallel job num is "$job_num" +make -j"$job_num" +``` + +##### G.C&C++.09 You can specify the build target. + +[Type] Requirement + +[Description] In routine development scenarios, you can specify the target to build modified code. A project can be built by specifying the target to meet flexible build and debugging requirements. + +[Positive Example] A typical command is as follows: + +``` +base_dir # cd build +base_dir/build # cmake .. +# Build all targets. +base_dir/build # make +# Build a specific target. +base_dir/build # make target_name +``` + +##### G.C&C++.10 Reproducible build is supported. + +[Type] Requirement + +[Description] If you do not modify the source code, clear the middleware and deliverables, or modify the build environment after the last successful build, you can perform a new round of build and obtain the same result. + +##### G.C&C++.11 Incremental build is supported. + +[Type] Recommendation + +[Description] In routine development scenarios, incremental build can improve development efficiency. Therefore, it is advised to support incremental build. + +##### G.C&C++.12 Parallel build is supported. + +[Type] Requirement + +[Description] You can run the **make -jN** command for quicker parallel build. This guideline applies only to projects that use the make tool. + +Support unified scheduling in jobserver mode to optimize the project load to the best level. The following alarms are not allowed: + +``` +warning: jobserver unavailable: using -j1. Add '+' to parent make rule. +warning: -jN forced in submake: disabling jobserver mode. +``` + +To support the jobserver mode, perform any of the following operations: + +1. Use **$(MAKE)** to directly invoke the **make** command. + + ```cmake + ExternalProject_Add(foo + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/foo + CONFIGURE_COMMAND sh configure_ext.sh + BUILD_COMMAND $(MAKE) + ) + ``` + +2. Use the shell script to invoke the **make** command. + + ```cmake + ExternalProject_Add(foo + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/foo + CONFIGURE_COMMAND sh configure_ext.sh + BUILD_COMMAND sh build_ext.sh $(MAKE) + ) + ``` + + The content of **build_ext.sh** is as follows: + + ```bash + #!/bin/bash + + make + ``` + + Note: **build_ext.sh** does not need to parse or use the **$(MAKE)** parameter. + +3. Use the python script to invoke the **make** command. + + ```cmake + ExternalProject_Add(foo + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/foo + CONFIGURE_COMMAND sh configure_ext.sh + BUILD_COMMAND python build_ext.py $(MAKE) + ) + ``` + + The content of **build_ext.py** is as follows: + + ```bash + #!/usr/bin/python + # -*- coding: UTF-8 -*- + + import subprocess + + def main(): + child = subprocess.Popen("make", close_fds=False) + ret = child.wait() + return + + if __name__ == '__main__': + main() + ``` + + Note: **build_ext.py** does not need to parse or use the **$(MAKE)** parameter. + + +#### Build Dependencies + +##### G.C&C++.13 Define a build dependency file **dependence.xml** to describe all components on which the build depends. The build script automatically reads the dependency file to produce the final software package. + +[Type] Recommendation + +[Description] Make software packages based on the dependency file, so that you do not need to define dependency components in the build scripts. This improves the build process maintainability. + +#### Build Configurations + +##### G.C&C++.14 Use the configuration file **config.*suffix*** in the build root directory as the unique configuration entry for the entire delivery project. + +[Type] Requirement + +[Description] Expose the least configuration options in the top-level **config.*suffix*** file. Configure only the information about the build environment and build tool in this file. + +[Exception] If there are a small number of build options and key-value pairs are used, the configuration file can be named **config.conf**. + +### GN Build Specifications + +#### Build Rules + +##### Rule 1.1 DO NOT use GN to invoke external build tools to build software modules. + +[Type] Forbidden + +[Description] Port external components to the GN build mode to avoid unnecessary dependencies on the environment during the build and obtain common capabilities, such as compiler security options and AddressSanitizer (ASan), provided by the build framework. + +[Negative Example] In GN, use **action** to invoke **automake** and **Make** to build third-party components. + +[Exception] The Linux kernel build framework builds user-mode programs. The kernel can be independently built outside the build framework. It is acceptable that some platforms use GN to include the kernel build in the build process to deliver one-click builds. + +##### Rule 1.2 DO NOT add compiler security options that have been added to the build system to the GN file of the module. + +[Type] Forbidden + +[Description] The default options that have been added globally should not be added again to meet internal and external rules. + +| Option| Parameter | Default Value | +|---------|------------|------------| +| Stack protection | -fstack-protector-strong| Enabled| +| Fortify Source | -D_FORTIFY_SOURCE=2 -O2 | Enabled| + +[Negative Example] Add **-fstack-protector-strong** to the GN file of the module. + +##### Rule 1.3 DO NOT add build options that are opposite to the default build options to GN. + +[Type] Forbidden + +[Description] The default build options represent the default capabilities of the build system. If your module needs to remove some default build options, there must be sufficient reasons. + +[Negative Example] Add **-wno-unused** to a module to clear build alarms. + +[Exception] When porting or using a third-party component, you can overwrite the default build options based on the component requirements. + +##### Rule 2.1 Use **gn format** to format GN files to meet the format and typesetting requirements. + +[Type] Requirement + +##### Rule 2.2 Use Python instead of shell to compile **action**. + +[Type] Recommendation + +[Description] The Python environment is easier to keep code unified and can run on multiple operating systems. It also provides better scalability, readability, and testability. + +##### Rule 2.3 DO NOT modify the content in the source code directory during the execution of GN and Ninja. + +[Type] Forbidden + +[Description] The forbidden operations include but are not limited to installing patches for, copying files to, performing build tasks in, and generating intermediate files in the source code directory. + +##### Rule 2.4 Set the encoding format of the build script to UTF-8 and the newline character to UNIX format. + +[Type] Requirement + +[Negative Example] After a script is compiled on Windows, Chinese comments are used and saved as local codes. \ No newline at end of file diff --git a/en/contribute/OpenHarmony-compile-rule.md b/en/contribute/OpenHarmony-compile-rule.md new file mode 100644 index 0000000000000000000000000000000000000000..d7129129e259839de22e9c51d4907d9283fce17c --- /dev/null +++ b/en/contribute/OpenHarmony-compile-rule.md @@ -0,0 +1,1369 @@ + +# OpenHarmony Compilation Specifications + +## Overview + +**Introduction** + +This topic covers C, C++, and Java compiler options or system configurations, including language options, warning options, security options, general options, code generation options, architecture options, optimization options, and compiler macros. + +**Scope** + +This topic specifies the C, C++, and Java compiler options or system configurations to be added during the compilation and build, and briefly describes the functionalities of these options. It also explains the involved exceptions. + +This topic does not cover security options in non-OS cases (such as bare core, BIOS, Bootloader, and BSBC). It is recommended that stack protection be implemented before related specifications are released. + +You can apply for arbitration for any dispute over exceptions that are not described in this document. + +**Clause Composition** + +Each clause generally includes the title, level, and description. In the description part, "Positive Example" provides an example that meets the clause, and "Negative Example" provides an example that does not meet the clause. + +**Title** + +Brief description of the clause. + +Clauses are classified into principles and guidelines. Principles can be used to evaluate the quality of guidelines and serve as a guide for their adjustment. Guidelines are practices that need to be followed or referenced. The identifier preceding a title tells whether the clause is a principle (P) or guideline (G). + +As stipulated in *Security Engineering Guidelines*, a principle identifier takes the format of P.Number, and a guideline identifier takes the format of G.Language.Element.Number, where **Language** indicates the programming language in use, **Element** is an abbreviation of the key element (corresponding to the level-1 title in this topic) in the domain, and **Number** is a 2-bit number incremented from 01. + +| Language | Element | Catalog | Language | Element | Catalog | +|----------|---------|----------|----------|---------|--------------| +| C&C++ | LANG | Language options| C&C++ | WARN | Warning options | +| C&C++ | SEC | Security options| C&C++ | CDG | Code generation options| +| C&C++ | OPT | Optimization options| C&C++ | MD | Architecture options | +| C&C++ | OVA | General options| C&C++ | LNK | Link options | +| C&C++ | DBG | Debugging options| C&C++ | PRE | Compiler macros | +| C&C++ | OTH | Other | Java | JAVAC | Javac | +| Java | MAVEN | Maven | | | | + +**Level** + +Guidelines are classified into requirements and recommendations by level. + +- Requirement: a guideline that must be followed in principle, but can be implemented phase by phase based on the specific product version plan. + +- Recommendation: a best practice that helps mitigate risks. Your team can determine whether to follow the recommendation based on actual business conditions. + +**Description** + +This part describes the clause, its working principle, and positive and negative examples. For some clauses, exceptions are provided. + +## C/C++ Compiler Options + +### Language Options + +##### G.C&C++.LANG.01 Explicitly set the compiler language standards. + +**[Type]** Requirement + +**[Description]** According to the time sequence, common ISO C standards include **-std=c90**, **-std=c99**, and **-std=c11**, and the corresponding GNU extension standards are **-std=gnu90**, **-std=gnu99**, and **-std=gnu11**. + +According to the time sequence, common ISO C++ standards include **-std=c++98**, **-std=c++11**, **-std=c++14**, and **-std=c++1z**, and the corresponding GNU extension standards are **-std=gnu++98**, **-std=gnu++11**, **-std=gnu++14**, and **-std=gnu++1z**. + +**-ansi** corresponds to **-std=c90** in the ISO C standard and **-std=c++98** in the ISO C++ standard. + +The GNU extensions fully support the corresponding ISO standards. + +Options such as **-Wpedantic**, **-pedantic**, and **-pedantic-errors** are used to check whether the ISO standards are strictly complied with. If the syntax does not comply with the ISO standards, a warning is generated. The GNU extension syntax may also trigger warnings. + +##### G.C&C++.LANG.02 Use the new language standards. + +**[Type]** Recommendation + +##### G.C&C++.LANG.03 Explicitly set the char type, either **-fsigned-char** or **-funsigned-char**. + +**[Type]** Recommendation + +**[Description]** In the x86 environment, char is of the signed type by default. In the ARM64 environment, char is of the unsigned type by default. Generally, use the **-fsigned-char** option to ensure that the compiler can adapt to instruction sets of different platforms. + +If char is equivalent to unsigned char (this is the case for some products), you are advised to use the **-funsigned-char** option. + +##### G.C&C++.LANG.04 DO NOT enable -fpermissive for C++. + +**[Type]** Requirement + +**[Description]** The **-fpermissive** option downgrades syntax errors in the C++ code to warnings. Therefore, do not enable this option. + +### Warning Options + +#### Options + +##### G.C&C++.WARN.01 Enable -Wall to check for useful warnings. + +**[Type]** Requirement + +**[Description]** **-Wall** is a set of useful warning options recognized by the GNU Compiler Collection (GCC), including **-Wpointer-sign**, **-Wframe-address**, **-Wmaybe-uninitialized**, and **-Wint-in-bool-context**. Learn the meanings of these warnings and modify code to clear them. + +##### G.C&C++.WARN.02 Enable -Wextra to check for additional warnings except -Wall. Use -Wno-XXXX to suppress huge numbers of false positives. + +**[Type]** Requirement + +**[Description]** **-Wextra** is a set of useful warning options except **-Wall**, including **-Wempty-body**, **Wmissing-field-initializers**, and **-Wunused-parameter**. + +Enabling **-Wextra** may cause many false positives. Based on the actual test, you can use **-Wno-XXXX** to suppress false positives. For example, if your product has a huge number of false positives for **-Wunused-parameter\-Wmissing-field-initializers**, you can set **-Wextra -Wno-unused-parameter\-Wno-missing-field-initializers**, after being approved by the chief software engineer of the product line. + +##### G.C&C++.WARN.03 Enable -Weffc++ to check for Scott Meyers' Effective C++ options. + +**[Type]** Recommendation + +**[Description]** **-Weffc++** is a set of warning options corresponding to Scott Meyers' Effective C++ options. + +#### Warning Suppression + +##### G.C&C++.WARN.04 DO NOT enable -w to suppress all warnings. + +**[Type]** Requirement + +**[Description]** The warnings displayed by the compiler are useful for identifying poor code and obscure bugs. Enabling the **-w** option will suppress all warnings. + +##### G.C&C++.WARN.05 DO NOT enable -Wno-XXXX to suppress all warning options contained in -Wall. + +**[Type]** Requirement + +**[Description]** **-Wall** is a set of useful alarm options recognized by the GCC compiler. Do not use **-Wno-pointer-sign**, **-Wno-frame-address**, **-Wno-maybe-uninitialized**, or **-Wno-int-in-bool-context** to suppress the **-Wpointer-sign**, **-Wframe-address**, **-Wmaybe-uninitialized**, and **-Wint-in-bool-context** options contained in **-Wall**. + +##### G.C&C++.WARN.06 DO NOT enable -Wno-error= XXXX to degrade a specific warning that has been upgraded to an error to a warning again. + +**[Type]** Requirement + +**[Description]** **-Werror=XXXX** escalates a warning to an error. **-Wno-error= XXXX** downgrades a warning that has been escalated to an error to a warning again. + +##### G.C&C++.WARN.07 DO NOT enable -Wno-XXXX to suppress the warning options enabled by the compiler by default. + +**[Type]** Recommendation + +**[Description]** The warning options enabled by the compiler by default are useful options recognized by the GCC, such as **-Wwrite-strings**, **-Wdelete-incomplete**, and **-Wsizeof-array-argument**. Learn the meanings of these warnings and modify code to clear them. + +**[Negative Example]** In the build project of a component, **-Wno-write-strings** is used to suppress the **-Wwrite-strings** warning for 7749 times. + +**[Exception]** To ensure build consistency, you can redefine the **\_*****FILE*****\_** macro to eliminate absolute paths. In this case, you can use **-Wno-builtin-macro-redefined** to suppress the **-Wbuiltin-macro-redefined** warning. + +#### Warning Escalation + +##### G.C&C++.WARN.08 Enable -Werror or -Werror=XXXX to escalate warnings to errors. + +**[Type]** Recommendation + +**[Description]** Enable the **-Werror** or **-Werror=XXXX** option to escalate warnings to errors. + +If **-Werror** is enabled, all warnings are escalated as errors. Once a warning is generated, the compilation will fail. This helps clear all warnings during development. + +If **-Werror=XXXX** is enabled, a specific type of warning is escalated as errors. This helps clear the specified warnings during development. Example: **-Werror=implicit-function-declaration** and **-Werror=format-SEC**. + +#### Warning Management + +##### G.C&C++.WARN.09 Use unified warning options in a build project. + +**[Type]** Requirement + +**[Description]** Use unified compilation warning options to ensure the same code quality of each part. + +#### Functions + +##### G.C&C++.WARN.10 Enable -Wtrampolines to check for trampolines pointed to by nested functions. + +**[Type]** Recommendation + +**[Description]** With the **-Wtrampolines** option enabled, a warning is generated when a nested function points to a trampoline. A trampoline is a small piece of data or code that is created at runtime and resides on the stack. It contains the address of a nested function and is used to indirectly call the nested function. On some platforms, a trampoline consists of only specially processed data. However, on most platforms, it is made up of code and requires an executable stack. For an executable stack, the CPU reads instructions from the stack and executes the instructions. This makes it possible for attackers to run their code in the stack memory by means of buffer overflow attacks. + +**[Negative Example]** Define a nested function **fun** in the **main** function, and use the function pointer to call **fun**. + +- Source program +``` +\#include \ +int main(){ + int ret; + int (\*pfunc)(int a, int b); + int fun(int a, int b){ + return a + b; + } + pfunc = fun; + ret = pfunc(10, 20); + printf("test gcc option -Wtrampolines! ret = %d\\n", ret); + return 0; +} +``` + +- Compiler options +``` +gcc -Wtrampolines trampolines.c -o out +``` + +- Compilation result +``` +warning: trampoline generated for nested function 'fun' [-Wtrampolines] +``` +**[Exception]** The **-Wtrampolines** option is not supported by xt-xcc and Clang compilers. + +##### G.C&C++.WARN.11 Enable -Wformat=2 to check input/output format functions. + +**[Type]** Recommendation + +**[Description]** **-Wformat=2** is a collection of **-Wformat**, **-Wformat-nonliteral**, **-Wformat-SEC**, and **\-Wformat-y2k**. + +1. With the **-Wformat** option enabled, a warning is generated when the parameter type or format of a format function is incorrect. + +2. With the **-Wformat-nonliteral** option enabled, a warning is generated when the format string is a non-string constant. + +3. **-Wformat-SEC** and **-Wformat-y2k**: If your product has encapsulated input and output framework format functions, declare the format attribute in the API to use the compiler check capabilities. For details, see the following: +[https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html\#Common-Function-Attributes](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes) + +##### G.C&C++.WARN.12 Enable -Wstrict-prototypes to check for unspecified parameter types in the function declaration or definition. + +**[Type]** Recommendation + +**[Description]** When a function is declared or defined, explicitly specify its parameter type. The compiler checks whether the parameter type in the call matches that in the definition. + +**[Negative Example]** + +- Source program +``` +\#include \ +int func(param){ + return param; +} + +``` +- Compiler options +``` +gcc -Wstrict-prototypes strict_prototypes.c -o out +``` +- Compilation result +``` + warning: function declaration isn't a prototype [-Wstrict-prototypes] int func(param){ +``` + +Related document: SEI CERT C Coding Standard DCL07-C.Include the appropriate type +information in function declarators + +#### Binary Consistency + +##### G.C&C++.WARN.13 Enable -Wdate-time to check for time macros. + +**[Type]** Recommendation + +**[Description]** Enable the **-Wdate-time** option to check for **__DATE__**, **TIME**, or **TIMESTAMP** in the code. This ensures binary consistency. + +**[Negative Example]** + +- Source program +``` +\#include \ +int main() { + printf ("%s %s %s\\n",_DATE_,_TIME_,_TIMESTAMP_); + return 0; +} +``` +- Compiler options +``` +gcc -Wdate-time datetime.c -o out +``` +- Compilation result +``` +warning:macro "_DATE_" might prevent reproducible builds [-Wdate-time] warning:macro "_TIME_" might prevent reproducible builds [-Wdate-time] warning:macro "_TIMESTAMP_" might prevent reproducible builds [-Wdate-time] +``` + +#### Statements + +##### G.C&C++.WARN.14 Enable -Wfloat-equal to check for equality comparison of floating point numbers. + +**[Type]** Requirement + +**[Description]** Floating point numbers have precision problems and cannot be accurately determined whether they are equal or not. You are advised to check whether the absolute value of the difference between two numbers is less than the acceptable error. You can use the C function **fabs()** to obtain the absolute value of the difference, and then compare the absolute value with the acceptable error. If the absolute value is less than the acceptable error, the two numbers are equal. Otherwise, they are not equal. Note that no warning is generated when the following comparison operators are used to compare floating point numbers: \>, \<, \>=, and \<=. + +**[Negative Example]** + +- Source program +``` +\#include \ +int main() { + double a = 0.3; + double b = 0.6; + ouble c = 0.9; + if ((a+b) == c) { + /\* It seems that a+b is equal to c, but actually not. \*/ + printf("double equal\\n"); + } + return 0; +} +``` + +- Compiler options +``` +gcc -Wfloat-equal float_equal.c -o out +``` + +In the preceding example, when double-precision floating point numbers are compared, the compiler generates "warning:comparing floating point with == or != is unsafe[-Wfloat-equal]". The correct method is to set an acceptable error range. If the absolute value of the difference between two floating point numbers is within the range, they are determined to be equal. + +**[Positive Example]** + +- Source program +``` +\#include \ \#include \ \#define EPSILON 1e-6 / +\* Acceptable error range for the comparison of double-precision floating point numbers \*/ +int main() { + double a = 0.3; + double b = 0.6; + double c = 0.9; + if (fabs((a+b)-c) \< EPSILON) { + printf("double equal\\n"); + } + return 0; +} +``` + +- Compiler options + +``` +gcc -Wfloat-equal float_equal.c -o out +``` + +##### G.C&C++.WARN.15 Enable -Wswitch-default to check whether the **switch** statement has the default branch. + +**[Type]** Recommendation + +**[Description]** If the **switch** statement does not have the default branch, a compilation warning is generated under the **-Wswitch-default** option. + +**[Negative Example]** + +- Source program +``` +enum TintColor{ + RED, DARK_RED, GREEN, LIGHT_GREEN +}; +void Colorize(enum TintColor Color) { + switch (Color) { + case RED: + /\* code \*/ + break; + case DARK_RED: + break; + } +} +``` +- Compiler options +``` +gcc -Wswitch-default switch_default.c -o out +``` +- Compilation result +``` +warning: switch missing default case [-Wswitch-default] switch (Color) +``` + +#### Variables + +##### G.C&C++.WARN.16 Enable -Wshadow to check variable coverage. + +**[Type]** Recommendation + +**[Description]** With the **-Wshadow** option enabled, a warning is generated when local variables overwrite global variables and function parameters. A large number of warnings will be generated when this option is enabled in C++. You can determine whether to enable it based on the actual situation. + +**[Negative Example]** + +- Source program +``` +int num = 0; +int foo(int a, int b){ + int num = a + b; + return num; +} + +``` +- Compiler options +``` +gcc -Wshadow shadow.c -o out +``` +- Compilation result +``` +warning: declaration of 'num' shadows a global declaration [-Wshadow] int num = a + b; +``` + +##### G.C&C++.WARN.17 Enable -Wstack-usage=len to set the stack size. + +**[Type]** Recommendation + +**[Description]** If the stack memory used by a function may exceed the number of bytes specified by **len**, a compilation warning is generated. You can set **len** based on the project requirements. + +**[Negative Example]** + +- Source program +``` +void foo(void) { + int arr[1000] = {0}; + return; +} +``` +- Compiler options +``` +gcc -Wstack-usage=1000 stack_usage.c -o out +``` +- Compilation result +``` +warning: stack usage is 4012 bytes [-Wstack-usage=] void foo(void) { +``` + +##### G.C&C++.WARN.18 Enable -Wframe-larger-than=len to set the stack framework size. + +**[Type]** Recommendation + +**[Description]** If the stack framework of a function exceeds the number of bytes specified by **len**, a compilation warning is generated. You can set **len** based on the project requirements. + +**[Negative Example]** + +- Source program +``` +void foo(void) { + int arr[1000] = {0}; + return; +} +``` +- Compiler options +``` +gcc -Wframe-larger-than=1000 stack_usage.c -o out +``` +- Compilation result +``` +warning: the frame size of 4000 bytes is larger than 1000 bytes [-Wframe-larger-than=] +``` + +##### G.C&C++.WARN.19 DO NOT enable -Wno-return-local-addr and check the returned local variable address. + +**[Type]** Recommendation + +**[Description]** If a function returns the address of a local variable, the **-Wreturn-local-addr** warning is generated by default during compilation. Do not enable the **-Wno-return-local-addr** option to suppress this warning. + +**[Negative Example]** + +- Source program +``` +int\* foo() { + int a=0; + return \&a; +} +``` +- Compiler options +``` +gcc -Wreturn-local-addr return_local_addr.c -o out +``` +- Compilation result +``` +warning: function returns address of local variable [-Wreturn-local-addr] return \&a; +``` + +#### Type Conversion + +##### G.C&C++.WARN.20 Enable -Wconversion to check for implicit conversion that results in value changes. + +**[Type]** Recommendation + +**[Description]** If implicit conversion in the code causes value changes, a compilation warning is generated under the **-Wconversion** option. + +Implicit conversions that may cause value changes include: converting a real number with a decimal to an integer, converting an unsigned number to a signed number (or vice versa), and converting a number of a larger type to a smaller type. If explicit conversion is used in the code, no warning is generated under **-Wconversion** during the compilation. + +**[Negative Example]** + +- Source program +``` +int foo(void) { + double num = 1.2; + return num; +} +``` +- Compiler options +``` +gcc-Wconversion conversion.c -o out +``` +- Compilation result +``` +warning: conversion from 'double' to 'int' may change value [-Wfloat-conversion] return num; +``` + +Do not forcibly convert object pointers from one type to another. + +##### G.C&C++.WARN.21 Enable -Wcast-qual to check for missing type qualifier of the target type when the pointer type is forcibly converted. + +**[Type]** Recommendation + +**[Description]** When the pointer type is forcibly converted, the target type may not contain the type qualifier. + +For example, if the const char\* pointer type is forcibly converted to a common char\* pointer type, the type qualifier **const** is not contained. Missing this qualifier may cause modifications to the memory that is not expected to be modified. + +**[Negative Example]** + +- Source program +``` +static char buf[8]; +void foo(){ + const char\* ptr = buf; + char\* q = (char\*)ptr; +} +``` +- Compiler options +``` +gcc -Wcast-qual cast_qual.c -o out +``` +- Compilation result +``` +warning: cast discards 'const' qualifier from pointer target type [-Wcast-qual] char\* q = (char\*)ptr; +``` + +##### G.C&C++.WARN.22 Enable -Wcast-align to check for explicit pointer type conversion to prevent the number of bytes used by the target type for address alignment from increasing. + +**[Type]** Recommendation + +**[Description]** A warning is generated when the number of bytes used by the target type for address alignment increases due to explicit conversion of a pointer type in the source program. For example, on a machine where an integer is aligned to a two- or four-byte boundary, a warning is generated when char \* is converted to int \*. + +#### Arrays + +##### G.C&C++.WARN.23 Enable -Wvla to check for variable-length arrays. + +**[Type]** Recommendation + +**[Description]** If the length of an array is a variable, a compilation warning is generated under the **-Wvla** option. + +**[Negative Example]** + +- Source program +``` +void foo(int len) { + int arr[len]; +} +``` +- Compiler options +``` +gcc -Wvla val.c -o out +``` +- Compilation result +``` +warning: ISO C90 forbids variable length array 'arr' [-Wvla] int arr[len]; +``` + +#### Invalid Code + +##### G.C&C++.WARN.24 Enable -Wunused to check for invalid code. + +**[Type]** Recommendation + +**[Description]** The **-Wunused** option checks for unused variables, functions, parameters, and aliases in the code. This option contains multiple suboptions, as listed below: + +- \-Wunused-but-set-variable + +- \-Wunused-function + +- \-Wunused-label + +- \-Wunused-local-typedefs + +- \-Wunused-variable + +- \-Wunused-value + + +Warnings about formal parameters that are not used in the function are generated only when **-Wextra \-Wunused** or **-Wunused-parameter** is enabled. + +**[Negative Example]** + +- Source program +``` +void foo(void) { + int a; +} +``` +- Compiler options +``` +gcc -Wunused unused.c -o out +``` +- Compilation result +``` +warning: unused variable 'a' [-Wunused-variable] int a; +``` + +#### Preprocessing + +##### G.C&C++.WARN.25 Enable -Wundef to check for undefined identifiers in the \#if statement of preprocessing directives. + +**[Type]** Recommendation + +**[Description]** When an undefined identifier appears in the \#if statement, a warning is generated. + +**[Negative Example]** + +- Source program +``` +\#if DEFINE_A_VALUE +\#endif +``` +- Compiler options +``` +gcc -Wunused unused.c -o out +``` + +- Compilation result +``` +warning: "DEFINE_A_VALUE" is not defined, evaluates to 0 [-Wundef] \#if DEFINE_A_VALUE +``` + +#### Classes + +##### G.C&C++.WARN.26 Enable -Wnon-virtual-dtor to check for undefined virtual destructors for the base class. + +**[Type]** Recommendation + +**[Description]** Destructors of the derived class can be called during polymorphism invocation only when destructors of the base class are virtual. + +**[Negative Example]** + +- Source program +``` +class Base { + public: virtual void foo() const = 0;\ + ~Base() {} +}; +class Derived: public Base { + public: virtual void foo() const {} + Derived() {} +}; +``` +- Compiler options +``` +gcc-Wnon-virtual-dtor non_virtual_destructors.cpp -o out +``` + +- Compilation result +``` +warning: 'class Base' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor] +``` + +##### G.C&C++.WARN.27 Enable -Wdelete-non-virtual-dtor to check whether the pointer of the base class is used for deletion when no virtual destructor is defined for the base class. + +**[Type]** Recommendation + +**[Description]** If the pointer of the base class is used for deletion when no virtual destructor is defined for a base class, undefined behavior may occur. Do not enable the **-Wno-delete-non-virtual-dtor** option to suppress this type of warning. + +**[Negative Example]** + +- Source program +``` +class Base { + public: virtual void f(); +}; +class Sub: public Base { + public: void f(int); +}; +int main() { + Sub\ * sub = new Sub(); + Base\ * base = sub; + delete base; +} +``` +- Compiler options +``` +gcc--Woverloaded-virtual overloaded_virtual.cpp -o out +``` +- Compilation result +``` +warning: deleting object of polymorphic class type 'Base' which has non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor] delete base; +``` + +##### G.C&C++.WARN.28 Enable -Woverloaded-virtual to check for hiding virtual functions of the base class. + +**[Type]** Recommendation + +**[Description]** A derived class redefines the virtual function of the base class, causing that function to be hidden. If this is the case, a warning is generated when **-Woverloaded-virtual** is enabled. + +**[Negative Example]** + +- Source program +``` +class Base { + public: virtual void f(); +}; +class Sub: public Base { + public: void f(int); +}; +``` +- Compiler options +``` +gcc--Woverloaded-virtual overloaded_virtual.cpp -o out +``` +- Compilation result +``` +warning: by 'void Sub::f(int)' [-Woverloaded-virtual] void f(int); +``` +### Security Options + +#### Options + +##### G.C&C++.SEC.01 Enable the stack protection options. + +**[Type]** Requirement + +**[Description]** + +**User-mode Linux** + +Application phase: compiler options + +Application scope: relocatable files (.o), dynamic libraries, and executable programs. + +Syntax: -fstack-protector-all/-fstack-protector-strong + +Description: + +In the case of a buffer overflow vulnerability, an attacker can overwrite the return address on the stack to hijack the control flow. When stack protection is enabled, a canary word is inserted between the buffer and the control flow. Generally, this canary word is overwritten when the attacker overwrites the return address. By checking the canary word, you can determine whether an overflow attack occurs. + +1\. Enable **-fstack-protector-strong** in GCC 4.9 and later versions. + +2\. Enable **-fstack-protector-all** in versions earlier than GCC 4.9. + +3\. This feature is not supported in the Wind River Linux 4.3 + MIPS environment. + +**Kernel-mode Linux** + +Application phase: compiler options + +Application scope: kernel mode of the Linux platform + +Usage: Enable **CONFIG_CC_STACKPROTECTOR** or **CONFIG_CC_STACKPROTECTOR_STRONG** before kernel compilation. + +Description: + +In kernel 3.14 and later versions, **CONFIG_CC_STACKPROTECTOR_STRONG** is supported, and **CONFIG_CC_STACKPROTECTOR** (corresponding to **-fstack-protector**) is changed to **CONFIG_CC_STACKPROTECTOR_REGULAR**. In kernel 4.18 and later versions, **CONFIG_CC_STACKPROTECTOR_REGULAR** (corresponding to **-fstack-protector**) is changed to **CONFIG_STACKPROTECTOR**, and **CONFIG_CC_STACKPROTECTOR_STRONG** (corresponding to **-fstack-protector-strong**) is changed to **CONFIG_STACKPROTECTOR_STRONG**. + +Exception: You do not need to enable this feature if the OS kernel in use, which must fall into one of the following scenarios, does not support it. + +1. The OS version is the latest official version or recommended version. + +2. The OS version in a mandatory selection for purposes of product compatibility. + +3. The OS version cannot be upgraded due to commercial reasons. + +**LiteOS** + +Application phase: compiler options + +Application scope: LiteOS V200R003C00 and later versions + +Syntax: -fstack-protector-all/-fstack-protector-strong + +Description: + +1. Enable **-fstack-protector-strong** in GCC 4.9 and later versions. + +2. Enable **-fstack-protector-all** in versions earlier than GCC 4.9. + +Exception: You do not need to enable this feature if the compiler does not provide this option or hardware stack protection is supported, as described below: + +1. Versions earlier than IAR 8.20 do not support stack protection. + +2. Hardware stack protection is provided. For example, some products in the ARC architecture can provide hardware stack protection, and hardware exceptions are triggered in the case of stack overflow. + +##### G.C&C++.SEC.02 Enable the ASLR option. + +**[Type]** Requirement + +Type for the high address space layout randomization (ASLR) and force ASLR option on the Windows platform: Recommendation + +**[Description]** + +**User-mode Linux** + +a. Run the **echo 2 \>/proc/sys/kernel/randomize_va_space** command to enable the system randomization configuration. + +Application phase: runtime system configuration + +Application scope: heap, stack, and memory mapping segment (mmap base address, shared libraries, and vDSO page) + +Syntax: echo 2 \>/proc/sys/kernel/randomize_va_space + +Description: + +ASLR is a security technique used to prevent the exploit of buffer overflow vulnerabilities. It randomizes the layout of linear regions such as heaps, stacks, and shared libraries, making it harder for attackers to predict target addresses and preventing them from locating attack code, which leads to reduced overflow attacks. When **randomize_va_space** is set to **1**, the stack, data segment, and vDSO are randomized. When **randomize_va_space** is set to **2**, the heap address is also randomized. + +To use the highest level ASLR, set **randomize_va_space** to **2**. + +b. Enable the PIC option to randomly load dynamic libraries. + +Application phase: compiler options + +Application scope: dynamic libraries + +Syntax: –fPIC(-fpic) + +Description: + +The position-independent code (PIC) option implements code segment relocation on a data segment, so the code segment does not change when .so files are being loaded. In this case, all processes share a code segment copy. + +Both the **\-fPIC** and **-fpic** options ensure that GCC produces PIC. The only difference is that **-fPIC** produces larger code whereas **-fpic** produces smaller code. + +c. Enable the PIE option to randomly load executable files. + +Application phase: compile options and link options + +Application scope: executable programs + +Syntax: –fPIE (-fpie) -pie + +Description: + +Position-independent executable (PIE) files can be loaded randomly in the same manner as shared libraries during loading and execution. The PIE can effectively reduce the success rate of fixed address attacks and buffer overflow attacks. + +(1) Check whether hot patch versions support the PIE options. If not, do not use any PIE option. + +(2) **-fPIE** is a compiler option, and **-pie** is a link option. + +(3) **-fPIE** produces larger code, whereas **-fpic** produces smaller code. + +**LiteOS** + +a. Enable random loading of code segments and data segments. + +Application phase: compiler options, link options, and runtime system configuration + +Application scope: LiteOS V200R003C00 and later versions + +Usage: Compile the image into a random image, and then randomly correct the address during image loading. + +Description: + +1. This feature depends on the bootloader that supports random address loading and depends on the MMU and DDR space. + +2. When this feature is enabled, the performance decreases by about 10%. + +3. The **-fPIE** and **-pie** options use the Global Offset Table (GOT) to implement address randomization. Both GCC and in-house HCC compilers support this feature. + +4. If the cost is high and cannot be implemented, provide specific data to the TMG for review. + +Exception: You do not need to enable this feature in the case of product hardware design or startup process restrictions, as described below: + +1. XIP scenario, where the system directly runs on the flash memory. + +2. ROM-based scenario, that is, all or part of the code is ROM-based and cannot be reloaded. + +3. The bootloader does not support random address loading. + +b. Enable random loading of dynamic libraries. + +Application phase: compiler options + +Application scope: LiteOS V200R003C00 and later versions + +Syntax: -fPIC + +Description: **-fPIC** is used in the dynamic library compilation phase. + +##### G.C&C++.SEC.03 Enable GOT RELRO. + +**[Type]** Requirement + +**[Description]** + +**User-mode Linux** + +a. Partial RELRO + +Application phase: link options + +Application scope: dynamic libraries and executable programs + +Syntax: -Wl,-z,relro + +Description: + +A dynamically linked executable and linkable format (ELF) binary uses the GOT to dynamically resolve functions in shared libraries. Attackers can leverage the buffer overflow to modify the function addresses of GOT entries in an attempt to attack the system. By adding the Relocation Read-Only (RELRO) option, you can prevent the GOT from being maliciously overwritten. + +b. Full RELRO + +Application phase: link options + +Application scope: dynamic libraries and executable programs + +Syntax: -Wl,-z,now + +Description: + +After partial RELRO is enabled and then the now option is enabled, full RELRO can be implemented. In other words, **-Wl,-z,relro,-z,now** is used to implement full RELRO. It can defend against Return to Procedural Linkage Table (Ret2PLT) attacks, but not buffer overflow attacks. + +If your product uses a large number of functions in shared libraries, applying RELRO will slow down program loading (startup), but it does not affect the runtime performance. + +##### G.C&C++.SEC.04 Enable the non-executable stack option/data execution protection option to implement non-executable stack protection. + +**[Type]** Requirement + +**[Description]** + +**User-mode Linux** + +Application phase: link options + +Application scope: dynamic libraries and executable programs + +Syntax: -Wl,-z,noexecstack + +Description: + +1. If there are nested functions, functional errors may occur. In this case, use **-Wtrampolines** to check the code. The version must be GCC 4.6.4 or later. +2. Wind River Linux 4.3 does not support this feature. +3. Wind River Linux 6 + MIPS does not support this feature. + +**LiteOS** + +Application phase: runtime system configuration + +Application scope: LiteOS V200R003C00 and later versions + +Usage: The runtime configuration stack cannot be executed, and the data segment (BSS and DATA) cannot be executed. + +Description: This feature requires the hardware to support memory protection units such as MMU, MPU, and PMP. + +##### G.C&C++.SEC.05 Use the -s option or the strip tool to remove the symbol tables. + +**[Type]** Requirement for user-mode Linux and recommendation for other platforms + +**[Description]** + +**User-mode Linux** + +Application phase: link options + +Application scope: dynamic libraries and executable programs + +Usage: -s (strip tool) + +Description: + +Symbols play a vital role in the linking process. The essence of a linking process is to link multiple target files together. A symbol can be regarded as the adhesive for linking. The entire linking process is completed based on symbols. After linking is complete, the symbol table will no longer affect the running of executable files. Instead, it can be exploited by attackers. Therefore, deleting the symbol table can help defend against hacker attacks. In addition, it can help reduce the file size. + +1. For static libraries, relocatable files (.o) cannot be stripped. Otherwise, compilation errors occur. The symbol table can be removed only for products involving ELF executable files and dynamic libraries. + +2. For components and platforms that are delivered only to internal products, a formal mechanism must be provided to instruct downstream products to delete the symbol table in the release phase. + +3. Stripping affects the locating of network problems and hot patches. Therefore, the versions before and after stripping must be synchronized in the build process. That is, the versions that are not stripped must be reserved locally for patch making and online commissioning. The following solutions can be used: + + 3.1 During compilation, the executor generates executable files and dynamic library versions whose symbol tables are not stripped. The versions are archived to the VMP (CMC) for hot patches. + + 3.2 Use the strip tool to delete symbol tables from dynamic libraries and executable files. + + 3.3 The executable files and dynamic libraries with symbol tables removed can be compressed to the startup software package. + +4. The strip tool and the **-s** option can achieve the same effect of removing the symbol table. If the **-s** option is used, the version will be compiled and built twice. You are advised to use the strip tool before release. The strip level is the default value, for example, stripbin.out. + +**LiteOS** + +Application phase: link options + +Application scope: LiteOS V200R003C00 and later versions + +Syntax: -s(strip) + +Description: The compilation result of LiteOS products for burning is a .bin file, which does not contain symbol table. Therefore, you are advised not to enable this feature. + +##### G.C&C++.SEC.06 Do not use the Run-time Search Path option. + +**[Type]** Requirement + +**[Description]** + +**User-mode Linux** + +Application phase: link options + +Application scope: dynamic libraries and executable programs + +Syntax: -Wl,--disable-new-dtags,--rpath,/libpath1:/libpath2;-Wl,--enable-new-dtags,--rpath,/libpath1:/libpath2 + +Description: + +This option is used to protect against the substitute of the **LD_LIBRARY_PATH** for a dynamic library with the same name. This option specifies a path for the runtime dynamic library search, which has a higher search priority than the path specified by **LD_LIBRARY_PATH**. When an executable file searches for a dynamic library at run time, it first searches the path specified by **--rpath** and then searches the path specified by **LD_LIBRARY_PATH**. In the case **LD_LIBRARY_PATH =[attackpath]**, using this option can effectively prevent against the substitute of the **LD_LIBRARY_PATH** for a dynamic library with the same name. However, this option has limitations. For example, if the specified path is not secure, common users can use malicious programs to replace normal programs in these directories, causing privilege escalation and subsequently resulting in insecure path vulnerabilities. + +##### G.C&C++.SEC.07 Enable write protection for code segments and data segments. + +**[Type]** Recommendation + +**[Description]** + +**LiteOS** + +a. Configure write protection for code segments and read-only data segments. + +Application phase: runtime system configuration + +Application scope: LiteOS V200R003C00 and later versions + +Usage: The runtime configuration code segment and read-only data segment cannot be modified. + +Description: This feature requires the hardware to support memory protection units such as MMU, MPU, and PMP. + +##### G.C&C++.SEC.10 Enable the compiler macro FORTIFY_SOURCE to enable the FS option. + +**[Type]** Recommendation + +**[Description]** + +**User-mode Linux** + +Application phase: compiler options + +Syntax: -D_FORTIFY_SOURCE=2 -O2 + +Description: + +When a program uses a static buffer with a fixed size, adding this option will allow the compiler or runtime library to check the call of related functions at compile time or run time. + +In principle, the recommended level is -O2, which delivers a better performance optimization effect than O1. If the product is based on O2, -O1 can be used. + +Add the option to a branch version first and conduct performance testing. Then determine whether to add the option to the mainline version based on the test result. + +**LiteOS** + +Application phase: compiler options + +Application scope: LiteOS V200R003C00 and later versions + +Syntax: -D_FORTIFY_SOURCE=2 -O2 + +Description: + +1. The benefits of the option are related to the implementation of the library. + +2. Currently, LiteOS uses the musl library. If the product uses another library that supports related functionalities, enable the option as required. + +Exception: You do not need to enable this option if the library does not support this feature, as described below: + +1. Setting D_FORTIFY_SOURCE=2 for the musl library does not take effect, which may cause misleading. Therefore, you do not need to enable D_FORTIFY_SOURCE. + +##### G.C&C++.SEC.11 Enable the ftrapv option to detect integer overflow. + +**[Type]** Recommendation + +**[Description]** + +User-mode Linux and LiteOS + +Application phase: compiler options + +Syntax: -ftrapv + +After the **-ftrapv** option is used, the addition, subtraction, and multiplication operations on signed integers are performed by using functions contained in a GCC library libgcc.c instead of CPU instructions. + +Using this option greatly affects the performance. You are not advised enabling the option in the release version. + +##### G.C&C++.SEC.13 Enable the stack check option. + +**[Level]** + +Recommendation for user-mode Linux + +Requirement (disabled) for LiteOS + +**[Description]** + +**User-mode Linux** + +Application phase: compiler options + +Application scope: relocatable files, dynamic libraries, and executable programs. + +Syntax: -fstack-check + +Description: + +The **stack-check** option checks the stack space in a program at compile time. If the stack space exceeds the alarm threshold, an alarm is generated. Then, an extra instruction is generated in the program to check whether the stack overflows at run time. The **stack-check** option sets a secure buffer at the lowest bottom of each stack. If the stack space applied in the function enters the security buffer, a Storage_Error exception is triggered. However, the generated code does not process exceptions. If an exception is detected, a message is sent to notify the OS. It ensures that the OS can detect stack extension. + +Using this option greatly affects the performance. You are advised to enable the option in the debug version, but not the release version. + +Implementation suggestion: optional + +**LiteOS** + +Application phase: compiler options + +Application scope: LiteOS V100R003C00 and later versions + +Syntax: -fstack-check + +Description: After the stack check option is enabled, the program may access an invalid address, causing execution exceptions. Therefore, do not enable it on the LiteOS platform. + +### Optimization Options + +#### Options + +##### P.C&C++.01 Select an appropriate optimization level based on the actual test result. + +**[Description]** Based on the actual test result, try different code optimization options to see if they are really faster for the program. + +##### G.C&C++.OPT.01 Preferentially select -O2, -Os, and -O3. + +**[Type]** Recommendation + +##### G.C&C++.OPT.02 Use -fno-strict-aliasing to disable strict alias optimization when many pointers of different types need to be converted. + +**[Type]** Recommendation + +**[Description]** **-O2** of GCC enables **-fstrict-aliasing** for strict alias rule optimization. The compiler assumes that the same memory address will never store different types of data. This optimization option is relatively radical. To avoid optimization issues caused by the conversion between pointers of different types in the code, you can use **-fno-strict-aliasing** to disable the optimization. A good practice is to modify the code to follow strict alias rules. + +Using the **-fno-strict-aliasing** option may affect product performance. For example, in the test of a performance-sensitive component of a product, the performance of **-O2 \-fno-strict-aliasing** decreases by 9% compared with **-O2**. + +##### G.C&C++.OPT.03 In the x86/ARM architecture, use -fno-omit-frame-pointer to disable stack frame pointer (SFP) optimization for DOPRA-based products. + +**[Type]** Recommendation + +**[Description]** **-fno-omit-frame-pointer**: The -O (-O1) option of GCC +enables the **-fomit-frame-pointer** optimization option, that is, removing the frame pointer used during function invoking. This optimization makes the code difficult to debug. You are advised to disable the optimization by using the **-fno-omit-frame-pointer** option. + +You need to balance performance optimization and debugging information retention. + +### Code Generation Options + +#### Options + +##### G.C&C++.CDG.01 Use -fno-common to check for uninitialized global variables in the data segment of the target file. + +**[Type]** Requirement + +**[Description]** With the **-fno-common** option enabled, a warning is generated when an uninitialized global variable placed in the data segment of the target file is declared in two compilation units. Defining multiple temporary global variables increases the difficulty in code maintenance, reduce the linking speed, and consume more space. + +##### G.C&C++.CDG.02: Use -freg-struct-return to return a struct in the register. + +**[Type]** Recommendation + +**[Description]** With the **-freg-struct-return** option, the register returns the struct and union. + +With the **-fpcc-struct-return** option, the memory instead of the register is used to return a struct and union (either short or long). + +You are advised to use the register to return the struct and union. For a small struct, this is more efficient than **-fpcc-struct-return**. + +If neither **-fpcc-struct-return** nor **-freg-struct-return** is used, GNU CC uses the standard rules specified by the target machine. If there is no standard rule, GNU CC uses **-fpcc-struct-return** by default except on the machine where GNU CC is the main compiler. If a standard can be selected, the register return mode is selected. + +Note that this option affects binary compatibility and should be unified for the entire product. + +##### G.C&C++.CDG.03 Use -fvisibility=hidden to set the visibility of symbols in the default ELF image to hidden. + +**[Type]** Recommendation + +**[Description]** The **-fvisibility=hidden** option makes only APIs in the dynamic library externally visible, effectively implementing binary modularization. This option helps increase the speed of dynamic library linking and loading and prevent symbol conflicts. However, after this option is enabled, the cost of patching the module function needs to be considered because the original global symbol now has the LOCAL attribute, the name needs to be changed when the patch is installed (the DOPRA patch specification has detailed naming rules), and the patch building cost will increase. Balance the benefits against the costs before enabling this option. + +##### G.C&C++.CDG.04 Use -fstrong-eval-order to enable the expression calculation sequence rule. + +**[Type]** Recommendation + +**[Description]** The **-fstrong-eval-order** option determines the calculation sequence of subexpressions based on C++17 specifications. For example, when the option is not enabled, +the expression T().m_i = A().B() may generate the evaluation sequence A() T() B(), which is different from that expected. This option is automatically enabled when **-std=c++17** is enabled. However, **-std=c++14** is used in GCC 7.3 by default. You are advised to enable this option explicitly to reduce unexpected behavior. + +### General Options + +#### Options + +##### G.C&C++.OVA.01 Enable the general option -pipe. + +**[Type]** Recommendation + +**[Description]** With the **-pipe** option enabled, multiple pipes are concurrently used during compilation to shorten compilation time. + +### Architecture Options + +#### Options + +##### G.C&C++.MD.01 Explicitly specify the following architecture options for embedded software. + +1. Soft and hard floating points (added or not added based on CPU-supported types) + +2. Instruction set (such as march=armv7-a and march=armv8-a) + +**[Type]** Requirement + +### Link Options + +#### Options + +##### G.C&C++.LNK.01 Enable the link options -Wl,-Bsymbolic, -rdynamic, and -Wl,--no-undefined. + +**[Type]** Recommendation + +**[Description]** With the **-Wl,-Bsymbolic** option enabled, the symbol with the same name preferentially uses the local .so file to reduce GOT redirections. +The **-rdynamic** option resolves the reverse dependency problem of dlopen. The .bin file returns symbol names through addresses. If this option is disabled, backtrace_symbol returns an address that cannot be used for locating. This option increases the size of the .bin file. + +The **-Wl,--no-undefined** option identifies runtime loading errors in the linking period. If this option is enabled, the linking time is prolonged due to dependency verification in the linking period. If dependency libraries specified by **-l** are incomplete, functional errors may occur. You need to balance between performance and functions. + + +### Debugging Options +#### Options + +##### G.C&C++.DBG.01 DO NOT carry debugging information during version release build. + +**[Type]** Requirement + +**[Description]** The debugging information refers to the symbol table and the detailed debugging information table. According to the security regulations, the debugging information is not mandatory for running and should be deleted from the release package. However, the information loss adversely affects maintenance and debugging, such as hot patches, perf analysis, and stack capture. + +If the **-s** link option is used, no debugging information is generated. Note that the build-id of the component generated by this method is different from that of the rebuilt components without the **-s** option, and therefore it cannot be directly used to locate faults in the GDB. You can also use **objcopy --only-keep-debug \ \** and **objcopy objcopy --strip-unneeded \** to separate debugging symbols after linking. In this way, the deliverables do not contain debugging information. + +If **-g** is enabled in the compilation phase to generate a detailed debugging information table, binary differences may occur in different directories due to the absolute path information of the source code. In this case, you can use **-fdebug-prefix-map=old=new** to map the absolute path to a relative path. + +### Compiler Macros +#### Options + +##### G.C&C++.PRE.01 Specify a specific purpose of each -D compiler macro and create a list of -D compiler macros. + +**[Type]** Requirement + +**[Description]** Each time a -D compiler macro is added, additional testing is required. Verify that the code modifications made on each software -D compiler macro are applicable to other -D compiler macros. First, for all -D compiler macros, software build is required to eliminate compilation errors. Second, complete testing is mandatory for all -D compiler macros. + +Delete all unused -D compiler macros. + +### Other +#### Options + +##### G.C&C++.OTH.01 DO NOT use duplicate or inclusion compiler options in a build project. + +**[Type]** Recommendation + +**[Description]** Duplicate compiler options cause redundant information and hinder maintenance. If the compiler options have different parameters, the source file may be compiled in a way different than initially expected. + +Using compiler options with inclusion relationships also causes redundancy. For example, **-Wall** contains more than 40 sub-warning options, and **-O** contains more than 40 sub-optimization options. When they are used together with sub-options, redundancy occurs. + +**[Negative Example]** A component takes the value of the compiler optimization option **-O** for 7055 times, and multiple **-O** options, for example, **-O2...-O6** and **-O2...-O3**, exist in a build project. + +\# The use of **-Wall** and **-Waddress** at the same time causes redundancy. + +gcc -Wall -Waddress -c test.c -o test.o + +\# The use of **-O** and **-fauto-inc-dec** at the same time causes redundancy. + +gcc -O -fauto-inc-dec -c test.c -o test.o + +##### G.C&C++.OTH.02 DO NOT use conflicting options. + +**[Type]** Recommendation + +**[Description]** Most **-f** and **-W** have two opposite options, +such as **-fname** and **-fno-name**, as well as **-Wname** and **-Wno-name**. If they are referenced at the same time, conflicts occur, which is confusing and inconvenient for maintenance. + +**[Negative Example]** + +\# Reference both **-fomit-frame-pointer** and **-fno-omit-frame-pointer**. + +``` +set(CMAKE_C_FLAGS "-MD -MF -Wall -save-temps -fverbose-asm -fsigned-char +\-fomit-frame-pointer -fno-stack-protector \\ + +\-fno-delete-null-pointer-checks -fno-common -freg-struct-return -O2 +\-fno-omit-frame-pointer -fno-strength-reduce" ) +``` + +##### G.C&C++.OTH.03 Compiler options are compiled in the following sequence: optimization levels (such as -O2) + general options + warning options + language options + code generation options + architecture options (MD-dependent options) + optimization options + security options + custom macros. + +**[Type]** Recommendation + +**[Description]** Place compiler option sets prior to specific options. For example, write **-Wall** before **-Wformat=2**. + +**[Positive Example]** + +``` +\# Copyright (c) Huawei Technologies Co., Ltd. 2019. All rights reserved. +\# toolchain for ARMA15(without FPU)HI1381/HI1215 +\# cpu_family = arm +\# bit_width_in_run = 32 +\# cpu_core = a15 +\# compile flags +set(CC_OPT_LEVEL "-O2") +set(CC_OVERALL_FLAGS "-pipe") +set(CC_WARN_FLAGS "-Wall -Wextra -Wdate-time -Wtrampolines -Wfloat-equal +\-Wshadow -Wformat=2") +set(CC_LANGUAGE_FLAGS "-fsigned-char") +set(CC_CDG_FLAGS "-fno-common -freg-struct-return") +set(CC_MD_DEPENDENT_FLAGS "-mfloat-abi=soft -march=armv7-a -mtune=cortex-a15") +set(CC_OPT_FLAGS "-fno-strict-aliasing -fno-omit-frame-pointer") +set(CC_SEC_FLAGS "-fPIC -fstack-protector-strong --param=ssp-buffer-size=4") +set(CC_DEFINE_FLAGS "-DXXXXX") +set(CC_ALL_OPTIONS "\${CC_OPT_LEVEL} \${CC_OVERALL_FLAGS} \${CC_WARN_FLAGS} +\${CC_LANNGUAGE_FLAGS} \\ +\${CC_CDG_FLAGS} \${CC_MD_DEPENDENT_FLAGS} \${CC_OPT_FLAGS} \${CC_SEC_FLAGS} +\${CC_DEFINE_FLAGS}") + +\# public link flags +set(PUBLIC_LNK_FLAGS "-rdynamic -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now") + +\# link flag for module +set(SHARED_LNK_FLAGS "-shared \${PUBLIC_LNK_FLAGS}") +set(PIE_EXE_LNK_FLAGS "-pie \${PUBLIC_LNK_FLAGS}") + +``` + +## Java Compiler Options + +### Language Level +#### Options + +##### G.JAVA.LANG.01 Use the same Java compiler language level for each delivery unit, and use the same language level as that of the Java version in use. + +**[Type]** Requirement + +**[Description]** If the compiler language levels of multiple modules are different, different compiler options need to be configured for these modules. Consequently, the compilation scripts are inconsistent. + +If the compiler language level corresponding to the Java version is used, a warning is displayed during compilation when the code is not recommended by the Java version. For example, when you use a Java 7 API, which is annotated as @Deprecated and replaced with a new API in Java 8, a warning is display during compilation if the compiler language level 8 is used. + +### Maven +#### Options + +##### G.JAVA.MAVEN.01 DO NOT use **-X** during version release to avoid generating a large number of debug logs. + +**[Type]** Requirement + +**[Description]** **-X** is a debug option. If **-X** is enabled, a large number of debug logs will be generated. + +### Javac +#### Options + +##### G.JAVA.JAVAC.01 DO NOT use -nowarn, -Xlint:none, or -Xlint:name to suppress all or some javac compilation warnings, and DO NOT use -g:none or -g:[keyword list] to suppress all or some debugging information. + +**[Type]** Requirement + +**[Description]** Compilation warnings help detect code defects and risks in advance. Suppressing compilation warnings brings potential risks to code quality. If the **-g:none** or **-g:[keywordlist]** option is used, too little or too much debugging information is generated, which adversely affects code maintainability or reduces operating efficiency. + +**[Exception]** -Xlint:all,-processing + +Annotations processed at run time do not require an annotation processor. Such compilation warnings can be suppressed by using the **-processing** parameter of **-Xlint**. + +##### G.JAVA.JAVAC.02 Use -source, -target, and -Xlint:all, and set showWarnings in maven-compiler-plugin to true. + +**[Type]** Requirement + +**[Description]** + +**\-source** specifies the Java source file version accepted by the compiler. + +**\-target** specifies the version of the class file generated by the compiler. + +**\-Xlint:all** enables all recommended compilation warnings. + +If **showWarnings** is left blank or set to **false**, some compilation warnings cannot be detected. + +**[Positive Example]** + +``` +\ + +\org.apache.maven.plugins\ + +\maven-compiler-plugin\ + +\ + +\1.8\ + +\1.8\ + +\true\ + +\ + +\-Xlint:all\ + +\ + +\ + +\ + +``` diff --git a/en/contribute/open-source-compliance-issue-management.md b/en/contribute/open-source-compliance-issue-management.md new file mode 100644 index 0000000000000000000000000000000000000000..49bc5f5d2acbbd73a52843ddeaffd6e10af29ebd --- /dev/null +++ b/en/contribute/open-source-compliance-issue-management.md @@ -0,0 +1,28 @@ +# Open Source Compliance Issue Management Process +## Issue Classification and Reporting Process +Open source compliance issues are issues related to licenses, copyrights, open source fragment reference, and open source obligation fulfillment. They are classified into public compliance issues and repository-dedicated compliance rectification issues. + +- Public compliance issues include but are not limited to the following: + - Community compliance requirements (including processes, rules, and engineering methods) + - Open source compliance consulting (including third-party compliance) + - Community compliance suggestions + - Compliance issues for which the home modules and code repositories cannot be determined + - Issues for which compliance or noncompliance cannot be determined (including repository-dedicated issues for which compliance or noncompliance cannot be determined) + - Other scenarios not included in repository-dedicated issues + +- Repository-dedicated compliance rectification issues are specific issues that have been clearly identified as noncompliance in a given repository and require only rectification tasks. +### Public Compliance Issues +If you find any public compliance issue, submit an issue on the [Issues](https://gitee.com/openharmony/community/issues) tab page in the community repository, start the issue title with **[Compliance]**, and provide a detailed description. +### Repository-dedicated Compliance Rectification Issues +If you find any compliance issue in a specific repository, submit an issue on the **Issues** tab page in that repository, start the issue title with **[Compliance]**, and provide a detailed description. + +## Issue Labels + +Committers of the community repository regularly review public compliance issues, and committers of the respective code repository regularly review repository-dedicated compliance rectification issues. +They will attach the **sig-compliance** label to issues prefixed with **[Compliance]**. + +## Issue Management Process +Routine management is carried out for compliance issues based on the OpenHarmony [Issue Dashboard] (http://ci.openharmony.cn/quality/issueDashboard). (Compliance issues are filtered based on the **[Compliance]** prefix and **sig-compliance** label). The compliance SIG routinely handles public compliance issues based on regular meetings and routinely checks whether the repository-dedicated compliance rectification issues are resolved before version release. + +In principle, public compliance issues should be replied within 14 days after they are submitted. For compliance issues that require urgent handling, send them to the [Compliance SIG leader](https://gitee.com/openharmony/community/blob/8e25fc45b1fa2f51fbfc627f243be415fa31385e/sig/sig-compliance/sig_compliance_cn.md#leader) by email. + \ No newline at end of file diff --git a/en/device-dev/kernel/Readme-EN.md b/en/device-dev/kernel/Readme-EN.md index 243ae9fb87332aa7ba04b381fecc814f610ffb93..c4f235a182ed7c115d943f0f711e2a9bc0ceba8d 100644 --- a/en/device-dev/kernel/Readme-EN.md +++ b/en/device-dev/kernel/Readme-EN.md @@ -135,7 +135,7 @@ - [Magic Key](kernel-small-debug-shell-magickey.md) - [User-Space Exception Information](kernel-small-debug-shell-error.md) - [Trace](kernel-small-debug-trace.md) - - [Perf](kernel-mini-memory-perf.md) + - [Perf](kernel-small-debug-perf.md) - [LMS](kernel-small-memory-lms.md) - [Process Debugging](kernel-small-debug-process-cpu.md) - Kernel-Mode Memory Debugging diff --git a/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md b/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md index 86e96a509e36d8b451fadb2b17543c82c7fe8d70..5429d3174fee9be17d1f66ce41d92b7920bb8eb1 100644 --- a/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md +++ b/en/device-dev/kernel/kernel-small-debug-memory-corrupt.md @@ -1,42 +1,52 @@ # Memory Corruption Check -## Basic Concepts +## Basic Concepts As an optional function of the kernel, memory corruption check is used to check the integrity of a dynamic memory pool. This mechanism can detect memory corruption errors in the memory pool in a timely manner and provide alerts. It helps reduce problem locating costs and increase troubleshooting efficiency. -## Function Configuration -**LOSCFG\_BASE\_MEM\_NODE\_INTEGRITY\_CHECK**: specifies the setting of the memory corruption check. This function is disabled by default. To enable this function, configure it in **Debug-\> Enable integrity check or not**. +## Function Configuration + +**LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** specifies the setting of the memory corruption check. This function is disabled by default. You can enable it in **Debug -> Enable integrity check or not**. If this macro is enabled, the memory pool integrity will be checked in real time upon each memory allocation. -If this macro is not enabled, you can call **LOS\_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS\_MemIntegrityCheck** does not affect the system performance. In addition, the check accuracy decreases because the node header does not contain the magic number \(which is available only when **LOSCFG\_BASE\_MEM\_NODE\_INTEGRITY\_CHECK** is enabled\). +If this macro is not enabled, you can call **LOS_MemIntegrityCheck** to check the memory pool integrity when required. Using **LOS_MemIntegrityCheck** does not affect the system performance. However, the check accuracy decreases because the node header does not contain the magic number (which is available only when **LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK** is enabled). + +This check only detects the corrupted memory node and provides information about the previous node (because memory is contiguous, a node is most likely corrupted by the previous node). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault. + +> **CAUTION**
+> If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS_MemIntegrityCheck** to check the memory pool integrity. + -This check only detects the corrupted memory node and provides information about the previous node \(because memory is contiguous, a node is most likely corrupted by the previous node\). To further determine the location where the previous node is requested, you need to enable the memory leak check and use LRs to locate the fault. +## Development Guidelines ->![](../public_sys-resources/icon-caution.gif) **CAUTION:** ->If memory corruption check is enabled, a magic number is added to the node header, which increases the size of the node header. The real-time integrity check has a great impact on the performance. In performance-sensitive scenarios, you are advised to disable this function and use **LOS\_MemIntegrityCheck** to check the memory pool integrity. -## Development Guidelines +### How to Develop -### How to Develop +Use **LOS_MemIntegrityCheck** to check for memory corruption. If no memory corruption occurs, **0** is returned and no log is output. If memory corruption occurs, the related log is output. For details, see the output of the following example. -Check for memory corruption by calling **LOS\_MemIntegrityCheck**. If no memory corruption occurs, **0** is returned and no log is output. If memory corruption occurs, the related log is output. For details, see the output of the following example. -### Development Example +### Development Example This example implements the following: -1. Requests two physically adjacent memory blocks. -2. Calls **memset** to construct an out-of-bounds access and overwrites the first four bytes of the next node. -3. Calls **LOS\_MemIntegrityCheck** to check whether memory corruption occurs. +1. Request two physically adjacent memory blocks. + +2. Use **memset** to construct an out-of-bounds access and overwrites the first four bytes of the next node. + +3. Call **LOS_MemIntegrityCheck** to check for memory corruption. + **Sample Code** +You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src/osTest.c** for testing. The sample code is as follows: -``` + + +```c #include #include #include "los_memory.h" @@ -44,10 +54,10 @@ The sample code is as follows: void MemIntegrityTest(void) { - /* Request two physically adjacent memory blocks.*/ + /* Request two physically adjacent memory blocks. */ void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - /* Construct an out-of-bounds access to cause memory corruption. The memory block of the first node is 8 bytes. Clearing 12 bytes overwrites the header of the second memory node. */ + /* Construct an out-of-bounds access to cause memory corruption. The memory block of the first node is 8 bytes. Clearing 12 bytes overwrites the header of the second memory node. */ memset(ptr1, 0, 8 + 4); LOS_MemIntegrityCheck(LOSCFG_SYS_HEAP_ADDR); } @@ -55,24 +65,26 @@ void MemIntegrityTest(void) **Verification** + The log is as follows: + + ``` [ERR][OsMemMagicCheckPrint], 2028, memory check error! -memory used but magic num wrong, magic num = 0x00000000 /* Error information, indicating that the first four bytes, that is, the magic number, of the next node are corrupted.*/ +memory used but magic num wrong, magic num = 0x00000000 /* Error information, indicating that the first four bytes, that is, the magic number, of the next node are corrupted. */ - broken node head: 0x20003af0 0x00000000 0x80000020, prev node head: 0x20002ad4 0xabcddcba 0x80000020 + broken node head: 0x20003af0 0x00000000 0x80000020, prev node head: 0x20002ad4 0xabcddcba 0x80000020 /* Key information about the corrupted node and its previous node, including the address of the previous node, magic number of the node, and sizeAndFlag of the node. In this example, the magic number of the corrupted node is cleared. */ - broken node head LR info: /* The node LR information can be output only after the memory leak check is enabled.*/ + broken node head LR info: /* The node LR information can be output only after the memory leak check is enabled. */ LR[0]:0x0800414e LR[1]:0x08000cc2 LR[2]:0x00000000 - pre node head LR info: /* Based on the LR information, you can find where the previous node is requested in the assembly file and then perform further analysis.*/ + pre node head LR info: /* Based on the LR information, you can find where the previous node is requested in the assembly file and then perform further analysis. */ LR[0]:0x08004144 LR[1]:0x08000cc2 LR[2]:0x00000000 -[ERR]Memory interity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node*/ +[ERR]Memory integrity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* Addresses of the corrupted node and its previous node */ ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-memory-info.md b/en/device-dev/kernel/kernel-small-debug-memory-info.md index 7e49011370211aab32ba94e1a578b99f77e857b7..ddfbc57c500d6638f48968860f1e40a34c04e164 100644 --- a/en/device-dev/kernel/kernel-small-debug-memory-info.md +++ b/en/device-dev/kernel/kernel-small-debug-memory-info.md @@ -1,61 +1,67 @@ # Memory Information Statistics -## Basic Concepts + +## Basic Concepts Memory information includes the memory pool size, memory usage, remaining memory size, maximum free memory, memory waterline, number of memory nodes, and fragmentation rate. -- Memory waterline: indicates the maximum memory used in a memory pool. The waterline value is updated upon each memory allocation and release. The memory pool size can be optimized based on this value. +- The memory waterline indicates the maximum memory used in a memory pool. The waterline value is updated each time the memory is allocated or released. The memory pool size can be optimized based on this value. + +- The fragmentation rate indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate:
Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size -- Fragmentation rate: indicates the fragmentation degree of the memory pool. If the fragmentation rate is high, there are a large number of free memory blocks in the memory pool but each block is small. You can use the following formula to calculate the fragmentation rate: +- You can use **LOS_MemInfoGet()** to scan the node information in the memory pool and collect the related statistics. - Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size +## Function Configuration -- Other statistics: When **LOS\_MemInfoGet** is called, the node information in the memory pool is scanned and related statistics are collected. +**LOSCFG_MEM_WATERLINE** specifies the setting of the memory information statistics function. This function is disabled by default. If you want to obtain the memory waterline, enable it in **Debug-> Enable MEM Debug-> Enable memory pool waterline or not**. -## Function Configuration -**LOSCFG\_MEM\_WATERLINE**: specifies the setting of the memory information statistics function. This function is disabled by default. To enable this function, configure it in **Debug-\> Enable memory pool waterline or not in the configuration item**. If you want to obtain the memory waterline, you must enable this macro. +## Development Guidelines -## Development Guidelines -### How to Develop +### How to Develop Key structure: -``` + +```c typedef struct { - UINT32 totalUsedSize; // Memory usage of the memory pool - UINT32 totalFreeSize; // Remaining memory in the memory pool - UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool - UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool - UINT32 freeNodeNum; // Number of free memory blocks in the memory pool -#if (LOSCFG_MEM_WATERLINE == 1) // This function is disabled by default and can be enabled using the menuconfig tool. - UINT32 usageWaterLine; // Waterline of the memory pool + UINT32 totalUsedSize; // Memory usage of the memory pool. + UINT32 totalFreeSize; // Remaining size of the memory pool. + UINT32 maxFreeNodeSize; // Maximum size of the free memory block in the memory pool. + UINT32 usedNodeNum; // Number of non-free memory blocks in the memory pool. + UINT32 freeNodeNum; // Number of free memory blocks in the memory pool. +#if (LOSCFG_MEM_WATERLINE == 1) // This function is disabled by default and can be enabled using the **menuconfig** tool. + UINT32 usageWaterLine; // Waterline of the memory pool. #endif } LOS_MEM_POOL_STATUS; ``` -- To obtain the memory waterline, call **LOS\_MemInfoGet**. The first parameter in the API is the start address of the memory pool, and the second parameter is the handle of the **LOS\_MEM\_POOL\_STATUS** type. The **usageWaterLine** field indicates the waterline. +To obtain the memory waterline, call **LOS_MemInfoGet(VOID *pool, LOS_MEM_POOL_STATUS *poolStatus)**. The first parameter specifies the start address of the memory pool, and the second parameter specifies the handle of the **LOS_MEM_POOL_STATUS** type. The **usageWaterLine** field indicates the waterline. -- To calculate the memory fragmentation rate, call **LOS\_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows: +To calculate the memory fragmentation rate, call **LOS_MemInfoGet** to obtain the remaining memory size and the maximum free memory block size in the memory pool, and then calculate the fragmentation rate of the dynamic memory pool as follows: - Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size +Fragmentation rate = 100 – 100 x Maximum free memory block size/Remaining memory size -### Development Example +### Development Example This example implements the following: -1. Creates a monitoring task to obtain information about the memory pool. -2. Calls **LOS\_MemInfoGet** to obtain the basic information about the memory pool. -3. Calculates the memory usage and fragmentation rate. +1. Create a monitoring task to obtain information about the memory pool. + +2. Call **LOS_MemInfoGet** to obtain the basic information about the memory pool. + +3. Calculate the memory usage and fragmentation rate. **Sample Code** +You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **MemTest()** function is called in **TestTaskEntry**. + The sample code is as follows: -``` +```c #include #include #include "los_task.h" @@ -66,15 +72,14 @@ void MemInfoTaskFunc(void) { LOS_MEM_POOL_STATUS poolStatus = {0}; - /* pool is the memory address of the information to be collected. OS_SYS_MEM_ADDR is used as an example.*/ + /* pool is the memory address of the information to be collected. OS_SYS_MEM_ADDR is used as an example. */ void *pool = OS_SYS_MEM_ADDR; LOS_MemInfoGet(pool, &poolStatus); /* Calculate the fragmentation rate of the memory pool. */ unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize; /* Calculate the memory usage of the memory pool. */ unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool); - printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, - poolStatus.totalFreeSize, poolStatus.usageWaterLine); + dprintf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, poolStatus.totalFreeSize, poolStatus.usageWaterLine); } int MemTest(void) @@ -88,18 +93,20 @@ int MemTest(void) taskStatus.usTaskPrio = 10; ret = LOS_TaskCreate(&taskID, &taskStatus); if (ret != LOS_OK) { - printf("task create failed\n"); - return -1; + dprintf("task create failed\n"); + return LOS_NOK; } - return 0; + return LOS_OK; } ``` **Verification** + The result is as follows: +The data may vary depending on the running environment. + ``` usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414 ``` - diff --git a/en/device-dev/kernel/kernel-small-debug-memory-leak.md b/en/device-dev/kernel/kernel-small-debug-memory-leak.md index d67b32bff12085d5f85c831aef31cae9a5f76491..df901f9b1140d19783b8c4e1c4b1a19457fd39af 100644 --- a/en/device-dev/kernel/kernel-small-debug-memory-leak.md +++ b/en/device-dev/kernel/kernel-small-debug-memory-leak.md @@ -1,127 +1,151 @@ # Memory Leak Check -## Basic Concepts +## Basic Concepts -As an optional function of the kernel, memory leak check is used to locate dynamic memory leak problems. After this function is enabled, the dynamic memory mechanism automatically records the link registers \(LRs\) used when memory is allocated. If a memory leak occurs, the recorded information helps locate the memory allocated for further analysis. +As an optional function of the kernel, memory leak check is used to locate dynamic memory leak problems. After this function is enabled, the dynamic memory mechanism automatically records the link registers (LRs) used when memory is allocated. If a memory leak occurs, the recorded information helps locate the memory allocated for further analysis. -## Function Configuration -1. **LOSCFG\_MEM\_LEAKCHECK**: specifies the setting of the memory leak check. This function is disabled by default. To enable this function, configure it in **Debug-\> Enable Function call stack of Mem operation recorded**. -2. **LOS\_RECORD\_LR\_CNT**: number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof\(void \*\)** bytes. -3. **LOS\_OMIT\_LR\_CNT**: number of ignored LRs. The default value is **2**, which indicates that LRs are recorded from the time when **LOS\_MemAlloc** is called. You can change the value based on actual requirements. This macro is configured because: - - **LOS\_MemAlloc** is also called internally. - - **LOS\_MemAlloc** may be encapsulated externally. - - The number of LRs configured by **LOS\_RECORD\_LR\_CNT** is limited. +## Function Configuration +**LOSCFG_MEM_LEAKCHECK** specifies the setting of the memory leak check. This function is disabled by default. You can enable it in **Debug-> Enable MEM Debug-> Enable Function call stack of Mem operation recorded**. + +**LOS_RECORD_LR_CNT** specifies the number of LRs recorded. The default value is **3**. Each LR consumes the memory of **sizeof(void *)** bytes. + +**LOS_OMIT_LR_CNT** specifies the number of ignored LRs. The default value is **2**, which indicates that LRs are recorded from the time when **LOS_MemAlloc** is called. You can change the value based on actual requirements. The reasons for this configuration are as follows: + +- **LOS_MemAlloc** is also called internally. +- **LOS_MemAlloc** may be encapsulated externally. +- The number of LRs configured by **LOS_RECORD_LR_CNT** is limited. Correctly setting this macro can ignore invalid LRs and reduce memory consumption. -## Development Guidelines -### How to Develop +## Development Guidelines -Memory leak check provides a method to check for memory leak in key code logic. If this function is enabled, LR information is recorded each time when memory is allocated. When **LOS\_MemUsedNodeShow** is called before and after the code snippet is checked, information about all nodes that have been used in the specified memory pool is printed. You can compare the node information. The newly added node information indicates the node where the memory leak may occur. You can locate the code based on the LR and further check whether a memory leak occurs. -The node information output by calling **LOS\_MemUsedNodeShow** is in the following format: +### How to Develop -- Each line contains information about a node. -- The first column indicates the node address, based on which you can obtain complete node information using a tool such as a GNU Debugger \(GDB\). -- The second column indicates the node size, which is equal to the node header size plus the data field size. -- Columns 3 to 5 list the LR addresses. +Memory leak check provides a method to check for memory leak in key code logic. If this function is enabled, LR information is recorded each time when memory is allocated. When **LOS_MemUsedNodeShow** is called before and after the code snippet is checked, information about all nodes that have been used in the specified memory pool is printed. You can compare the node information. The newly added node information indicates the node where the memory leak may occur. You can locate the code based on the LR and further check whether a memory leak occurs. + +The node information output by calling **LOS_MemUsedNodeShow** is in the following format:
Each line contains information about a node. The first column indicates the node address, based on which you can obtain complete node information using a tool such as a GNU Debugger (GDB). The second column indicates the node size, which is equal to the node header size plus the data field size. Columns 3 to 5 list the LR addresses. You can determine the specific memory location of the node based on the LR addresses and the assembly file. -You can determine the specific memory location of the node based on the LR addresses and the assembly file. ``` -node size LR[0] LR[1] LR[2] -0x10017320: 0x528 0x9b004eba 0x9b004f60 0x9b005002 -0x10017848: 0xe0 0x9b02c24e 0x9b02c246 0x9b008ef0 -0x10017928: 0x50 0x9b008ed0 0x9b068902 0x9b0687c4 +node size LR[0] LR[1] LR[2] +0x10017320: 0x528 0x9b004eba 0x9b004f60 0x9b005002 +0x10017848: 0xe0 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x10017928: 0x50 0x9b008ed0 0x9b068902 0x9b0687c4 0x10017978: 0x24 0x9b008ed0 0x9b068924 0x9b0687c4 -0x1001799c: 0x30 0x9b02c24e 0x9b02c246 0x9b008ef0 -0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x1001799c: 0x30 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0 ``` ->![](../public_sys-resources/icon-caution.gif) **CAUTION:** ->Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead. +> **CAUTION** +> Enabling memory leak check affects memory application performance. LR addresses will be recorded for each memory node, increasing memory overhead. + -### Development Example +### Development Example This example implements the following: -1. Call **OsMemUsedNodeShow** to print information about all nodes. -2. Simulate a memory leak by requesting memory without releasing it. -3. Call **OsMemUsedNodeShow** to print information about all nodes. -4. Compare the logs to obtain information about the node where a memory leak occurred. -5. Locate the code based on the LR address. +1. Call **OsMemUsedNodeShow** to print information about all nodes. + +2. Simulate a memory leak by requesting memory without releasing it. + +3. Call **OsMemUsedNodeShow** to print information about all nodes. + +4. Compare the logs to obtain information about the node where a memory leak occurred. + +5. Locate the code based on the LR address. + **Sample Code** +You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **MemLeakTest()** function is called in **TestTaskEntry**. + +In this example, a memory pool is created. To achieve this purpose, you need to define **LOSCFG_MEM_MUL_POOL** in **target_config.h**. + The sample code is as follows: -``` +```c #include #include #include "los_memory.h" #include "los_config.h" +#define TEST_NEW_POOL_SIZE 2000 +#define TEST_MALLOC_SIZE 8 + void MemLeakTest(void) { - OsMemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); - void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); - OsMemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); + VOID *pool = NULL; + + /* Create a memory pool. */ + pool = LOS_MemAlloc(OS_SYS_MEM_ADDR, TEST_NEW_POOL_SIZE); + (VOID)LOS_MemInit(pool, TEST_NEW_POOL_SIZE); + + OsMemUsedNodeShow(pool); + void *ptr1 = LOS_MemAlloc(pool, TEST_MALLOC_SIZE); + void *ptr2 = LOS_MemAlloc(pool, TEST_MALLOC_SIZE); + OsMemUsedNodeShow(pool); + + /* Release the memory pool. */ + (VOID)LOS_MemDeInit(pool); } ``` + **Verification** + The log is as follows: ``` -node size LR[0] LR[1] LR[2] -0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc -0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc -0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e -0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a -0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 - -node size LR[0] LR[1] LR[2] -0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc -0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc -0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e -0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a -0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 -0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +/* Log for the first OsMemUsedNodeShow. Because the memory pool is not allocated, there is no memory node. */ +node LR[0] LR[1] LR[2] + + +/* Log for the second OsMemUsedNodeShow. There are two memory nodes. */ +node LR[0] LR[1] LR[2] +0x00402e0d90: 0x004009f040 0x0040037614 0x0040005480 +0x00402e0db0: 0x004009f04c 0x0040037614 0x0040005480 + ``` + The difference between the two logs is as follows. The following memory nodes are suspected to have blocks with a memory leak. ``` -0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 -0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +0x00402e0d90: 0x004009f040 0x0040037614 0x0040005480 +0x00402e0db0: 0x004009f04c 0x0040037614 0x0040005480 ``` + The following is part of the assembly file: ``` - MemLeakTest: - 0x80041d4: 0xb510 PUSH {R4, LR} - 0x80041d6: 0x4ca8 LDR.N R4, [PC, #0x2a0] ; g_memStart - 0x80041d8: 0x0020 MOVS R0, R4 - 0x80041da: 0xf7fd 0xf93e BL LOS_MemUsedNodeShow ; 0x800145a - 0x80041de: 0x2108 MOVS R1, #8 - 0x80041e0: 0x0020 MOVS R0, R4 - 0x80041e2: 0xf7fd 0xfbd9 BL LOS_MemAlloc ; 0x8001998 - 0x80041e6: 0x2108 MOVS R1, #8 - 0x80041e8: 0x0020 MOVS R0, R4 - 0x80041ea: 0xf7fd 0xfbd5 BL LOS_MemAlloc ; 0x8001998 - 0x80041ee: 0x0020 MOVS R0, R4 - 0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a - 0x80041f4: 0xbd10 POP {R4, PC} - 0x80041f6: 0x0000 MOVS R0, R0 +4009f014: 7d 1e a0 e3 mov r1, #2000 +4009f018: 00 00 90 e5 ldr r0, [r0] +4009f01c: 67 7a fe eb bl #-398948 +4009f020: 7d 1e a0 e3 mov r1, #2000 +4009f024: 00 40 a0 e1 mov r4, r0 +4009f028: c7 79 fe eb bl #-399588 +4009f02c: 04 00 a0 e1 mov r0, r4 +4009f030: 43 78 fe eb bl #-401140 +4009f034: 04 00 a0 e1 mov r0, r4 +4009f038: 08 10 a0 e3 mov r1, #8 +4009f03c: 5f 7a fe eb bl #-398980 +4009f040: 04 00 a0 e1 mov r0, r4 +4009f044: 08 10 a0 e3 mov r1, #8 +4009f048: 5c 7a fe eb bl #-398992 +4009f04c: 04 00 a0 e1 mov r0, r4 +4009f050: 3b 78 fe eb bl #-401172 +4009f054: 3c 00 9f e5 ldr r0, [pc, #60] +4009f058: 40 b8 fe eb bl #-335616 +4009f05c: 04 00 a0 e1 mov r0, r4 +4009f060: 2c 7a fe eb bl #-399184 ``` -The memory node addressed by **0x080041ee** is not released after being requested in **MemLeakTest**. +The memory node addressed by **0x4009f040** is not released after being allocated in **MemLeakTest**. diff --git a/en/device-dev/kernel/kernel-small-debug-perf.md b/en/device-dev/kernel/kernel-small-debug-perf.md new file mode 100644 index 0000000000000000000000000000000000000000..819365eb087c7e13d0853ce1149447981f785a22 --- /dev/null +++ b/en/device-dev/kernel/kernel-small-debug-perf.md @@ -0,0 +1,267 @@ +# perf + + +## Basic Concepts + +perf is a performance analysis tool. It uses the performance monitoring unit (PMU) to count sampling events and collect context information and provides hot spot distribution and hot paths. + + +## Working Principles + +When a performance event occurs, the corresponding event counter overflows and triggers an interrupt. The interrupt handler records the event information, including the current PC, task ID, and call stack. + +perf provides two working modes: counting mode and sampling mode. + +In counting mode, perf collects only the number of event occurrences and duration. In sampling mode, perf also collects context data and stores the data in a circular buffer. The IDE then analyzes the data and provides information about hotspot functions and paths. + + +## Available APIs + +The Perf module of the OpenHarmony LiteOS-A kernel provides the following APIs. For details, see the [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h). + + **Table 1** APIs of the perf module + +| Category| Description| +| -------- | -------- | +| Starting or stopping sampling| **LOS_PerfInit**: initializes perf.
**LOS_PerfStart**: starts sampling.
**LOS_PerfStop**: stops sampling. | +| Configuring perf sampling events| **LOS_PerfConfig**: sets the event type and sampling period. | +| Reading sampling data| **LOS_PerfDataRead**: reads the sampling data. | +| Registering a hook for the sampling data buffer| **LOS_PerfNotifyHookReg**: registers the hook to be called when the buffer waterline is reached.
**LOS_PerfFlushHookReg**: registers the hook for flushing the cache in the buffer. | + +**PerfConfigAttr** is the structure of the perf sampling event. For details, see [kernel\include\los_perf.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h). + +The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten. + +The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size. The code snippet is as follows: + +```c +VOID Example_PerfNotifyHook(VOID) +{ + CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0}; + UINT32 len; + PRINT_DEBUG("perf buffer reach the waterline!\n"); + len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE); + OsPrintBuff(buf, len); /* print data */ +} +LOS_PerfNotifyHookReg(Example_PerfNotifyHook); +``` + +If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency. The code snippet is as follows: + +```c +VOID Example_PerfFlushHook(VOID *addr, UINT32 size) +{ + OsCacheFlush(addr, size); /* platform interface */ +} +LOS_PerfNotifyHookReg(Example_PerfFlushHook); +``` + +The API for flushing the cache is configured based on the platform. + + +## Development Guidelines + + +### Kernel-Mode Development Process + +The typical process of enabling perf is as follows: + +1. Configure the macros related to the perf module. + Configure the perf control macro **LOSCFG_KERNEL_PERF**, which is disabled by default. In the **kernel/liteos_a** directory, run the **make update_config** command, choose **Kernel**, and select **Enable Perf Feature**. + + | Configuration Item| menuconfig Option| Description| Value| + | -------- | -------- | -------- | -------- | + | LOSCFG_KERNEL_PERF | Enable Perf Feature | Whether to enable perf.| YES/NO | + | LOSCFG_PERF_CALC_TIME_BY_TICK | Time-consuming Calc Methods->By Tick | Whether to use tick as the perf timing unit.| YES/NO | + | LOSCFG_PERF_CALC_TIME_BY_CYCLE | Time-consuming Calc Methods->By Cpu Cycle | Whether to use cycle as the perf timing unit.| YES/NO | + | LOSCFG_PERF_BUFFER_SIZE | Perf Sampling Buffer Size | Size of the buffer used for perf sampling.| INT | + | LOSCFG_PERF_HW_PMU | Enable Hardware Pmu Events for Sampling | Whether to enable hardware PMU events. The target platform must support the hardware PMU.| YES/NO | + | LOSCFG_PERF_TIMED_PMU | Enable Hrtimer Period Events for Sampling | Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).| YES/NO | + | LOSCFG_PERF_SW_PMU | Enable Software Events for Sampling | Whether to enable software events. **LOSCFG_KERNEL_HOOK** must also be enabled.| YES/NO | + +2. Call **LOS_PerfConfig** to configure the events to be sampled. + perf provides two working modes and three types of events. + + - Working modes: counting mode (counts only the number of event occurrences) and sampling mode (collects context information such as task IDs, PC, and backtrace) + - Event types: CPU hardware events (such as cycle, branch, icache, and dcache), high-precision periodical events (such as CPU clock), and OS software events (such as task switch, mux pend, and IRQ) +3. Call **LOS_PerfStart(UINT32 sectionId)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs. + +4. Call **LOS_PerfStop** at the end of the code to be sampled. + +5. Call **LOS_PerfDataRead** to read the sampling data and use IDE to analyze the collected data. + + +#### Development Example + +This example implements the following: + +1. Create a perf task. + +2. Configure sampling events. + +3. Start perf. + +4. Execute algorithms for statistics. + +5. Stop perf. + +6. Export the result. + + +#### Sample Code + +Prerequisites: **Enable Hook Feature** and **Enable Software Events for Sampling** are selected for the perf module in **menuconfig**. + +You can compile and verify the sample code in **kernel/liteos_a/testsuites/kernel/src/osTest.c**. + +The code is as follows: + +```c +#include "los_perf.h" +#define TEST_MALLOC_SIZE 200 +#define TEST_TIME 5 + +/* Add malloc() and free() in the test() function. */ +VOID test(VOID) +{ + VOID *p = NULL; + int i; + for (i = 0; i < TEST_TIME; i++) { + p = LOS_MemAlloc(m_aucSysMem1, TEST_MALLOC_SIZE); + if (p == NULL) { + PRINT_ERR("test alloc failed\n"); + return; + } + + (VOID)LOS_MemFree(m_aucSysMem1, p); + } +} + +STATIC VOID OsPrintBuff(const CHAR *buf, UINT32 num) +{ + UINT32 i = 0; + PRINTK("num: "); + for (i = 0; i < num; i++) { + PRINTK(" %02d", i); + } + PRINTK("\n"); + PRINTK("hex: "); + for (i = 0; i < num; i++) { + PRINTK(" %02x", buf[i]); + } + PRINTK("\n"); +} +STATIC VOID perfTestHwEvent(VOID) +{ + UINT32 ret; + CHAR *buf = NULL; + UINT32 len; + + //LOS_PerfInit(NULL, 0); + + + PerfConfigAttr attr = { + .eventsCfg = { + .type = PERF_EVENT_TYPE_SW, + .events = { + [0] = {PERF_COUNT_SW_TASK_SWITCH, 0xff}, /* Collect task scheduling information. */ + [1] = {PERF_COUNT_SW_MEM_ALLOC, 0xff}, /* Collect memory allocation information. */ + + PERF_COUNT_SW_TASK_SWITCH + }, + .eventsNr = 2, + .predivided = 1, /* cycle counter increase every 64 cycles */ + }, + .taskIds = {0}, + .taskIdsNr = 0, + .needSample = 0, + .sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN, + }; + ret = LOS_PerfConfig(&attr); + if (ret != LOS_OK) { + PRINT_ERR("perf config error %u\n", ret); + return; + } + PRINTK("------count mode------\n"); + LOS_PerfStart(0); + test(); /* this is any test function*/ + LOS_PerfStop(); + PRINTK("--------sample mode------ \n"); + attr.needSample = 1; + LOS_PerfConfig(&attr); + LOS_PerfStart(2); // 2: set the section id to 2. + test(); /* this is any test function*/ + LOS_PerfStop(); + buf = LOS_MemAlloc(m_aucSysMem1, LOSCFG_PERF_BUFFER_SIZE); + if (buf == NULL) { + PRINT_ERR("buffer alloc failed\n"); + return; + } + /* get sample data */ + len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE); + OsPrintBuff(buf, len); /* print data */ + (VOID)LOS_MemFree(m_aucSysMem1, buf); +} + +UINT32 Example_Perf_test(VOID) +{ + UINT32 ret; + TSK_INIT_PARAM_S perfTestTask = {0}; + UINT32 taskID; + /* Create a perf task. */ + perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent; + perfTestTask.pcName = "TestPerfTsk"; /* Test task name. */ + perfTestTask.uwStackSize = 0x1000; // 0x8000: perf test task stack size + perfTestTask.usTaskPrio = 5; // 5: perf test task priority + ret = LOS_TaskCreate(&taskID, &perfTestTask); + if (ret != LOS_OK) { + PRINT_ERR("PerfTestTask create failed. 0x%x\n", ret); + return LOS_NOK; + } + return LOS_OK; +} +LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED); +``` + + +#### Verification + + The output is as follows: + +``` +type: 2 +events[0]: 1, 0xff +events[1]: 3, 0xff +predivided: 1 +sampleType: 0x60 +needSample: 0 +------count mode------ +[task switch] eventType: 0x1 [core 0]: 0 +[mem alloc] eventType: 0x3 [core 0]: 5 +time used: 0.005000(s) +--------sample mode------ +type: 2 +events[0]: 1, 0xff +events[1]: 3, 0xff +predivided: 1 +sampleType: 0x60 +needSample: 1 +dump perf data, addr: 0x402c3e6c length: 0x5000 +time used: 0.000000(s) +num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 +hex: 00 ffffffef ffffffef ffffffef 02 00 00 00 14 00 00 00 60 00 00 00 02 00 00 00 + +The print information may vary depending on the running environment. +``` + +- For the counting mode, the following information is displayed after perf is stopped: + Event name (cycles), event type (0xff), and number of event occurrences (5466989440) + + For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**. + +- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped: + dump section data, addr: (0x8000000) length: (0x5000) + + You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data. + + You can also call **LOS_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte. diff --git a/en/device-dev/kernel/kernel-small-debug-process-cpu.md b/en/device-dev/kernel/kernel-small-debug-process-cpu.md index 5801bb007bc9edc1b075363a34ba57eb67e3c498..00946584c794a9c2a4258131846da9ec32b0dabb 100644 --- a/en/device-dev/kernel/kernel-small-debug-process-cpu.md +++ b/en/device-dev/kernel/kernel-small-debug-process-cpu.md @@ -3,35 +3,34 @@ ## Basic Concepts -The central processing unit percent \(CPUP\) includes the system CPUP, process CPUP, task CPUP, and interrupt CPUP. With the system CPUP, you can determine whether the current system load exceeds the designed specifications. With the CPUP of each task/process/interrupt, you can determine whether their CPU usage meets expectations of the design. +The central processing unit percent (CPUP) includes the system CPUP, process CPUP, task CPUP, and interrupt CPUP. With the system CPUP, you can determine whether the current system load exceeds the designed specifications. With the CPUP of each task/process/interrupt, you can determine whether their CPU usage meets expectations of the design. -- System CPUP +- System CPUP + System CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status (idle or busy) in the given period of time. The valid range of the system CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the system runs with full load. - System CPUP is the CPU usage of the system within a period of time. It reflects the CPU load and the system running status \(idle or busy\) in the given period of time. The valid range of the system CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the system runs with full load. +- Process CPUP + Process CPUP refers to the CPU usage of a single process. It reflects the process status, busy or idle, in a period of time. The valid range of the process CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the process is being executed for a period of time. -- Process CPUP +- Task CPUP + Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The valid range of task CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the task is being executed for the given period of time. - Process CPUP refers to the CPU usage of a single process. It reflects the process status, busy or idle, in a period of time. The valid range of the process CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the process is being executed for a period of time. +- Interrupt CPUP + Interrupt CPUP refers to the CPU usage of a single interrupt. It reflects the interrupt status, busy or idle, in a period of time. The valid range of the interrupt CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the interrupt is being executed for a period of time. -- Task CPUP - Task CPUP refers to the CPU usage of a single task. It reflects the task status, busy or idle, in a period of time. The valid range of task CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the task is being executed for the given period of time. +## Working Principles -- Interrupt CPUP +The OpenHarmony LiteOS-A kernel CPUP module records the CPU usage by process, task, and interrupt. When a process or task is switched, the start time of the process or task is recorded. When the process or task is switched out or exits, the system accumulates the CPU time of the entire process or task. When an interrupt is executed, the system accumulates and records the execution time of each interrupt. - Interrupt CPUP refers to the CPU usage of a single interrupt. It reflects the interrupt status, busy or idle, in a period of time. The valid range of the interrupt CPUP is 0 to 100 in percentage. The precision can be adjusted through configuration. The value **100** indicates that the interrupt is being executed for a period of time. +OpenHarmony provides the following types of CPUP information: +- System CPUP -## Working Principles +- Process CPUP -The OpenHarmony LiteOS-A kernel CPUP module records the CPU usage by process, task, and interrupt. When a process or task is switched, the start time of the process or task is recorded. When the process or task is switched out or exits, the system accumulates the CPU time of the entire process or task. When an interrupt is executed, the system accumulates and records the execution time of each interrupt. +- Task CPUP -OpenHarmony provides the following types of CPUP information: - -- System CPUP -- Process CPUP -- Task CPUP -- Interrupt CPUP +- Interrupt CPUP The CPUP is calculated as follows: @@ -43,136 +42,111 @@ Task CPUP = Total running time of the task/Total running time of the system Interrupt CPUP = Total running time of the interrupt/Total running time of the system -## Development Guidelines - -### Available APIs - -**Table 1** CPUP module APIs - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Function

-

API

-

Description

-

System CPUP

-

LOS_HistorySysCpuUsage

-

Obtains the historical CPUP of the system.

-

Process CPUP

-

LOS_HistoryProcessCpuUsage

-

Obtains the historical CPUP of a specified process.

-

LOS_GetAllProcessCpuUsage

-

Obtains the historical CPUP of all processes in the system.

-

Task CPUP

-

LOS_HistoryTaskCpuUsage

-

Obtains the historical CPUP of a specified task.

-

Interrupt CPUP

-

LOS_GetAllIrqCpuUsage

-

Obtains the historical CPUP of all interrupts in the system.

-
- -### How to Develop - -The typical CPUP development process is as follows. - -1. Call **LOS\_HistorySysCpuUsage** to obtain the historical CPUP of the system. -2. Call **LOS\_HistoryProcessCpuUsage** to obtain the historical CPUP of a specified process. - - If the process has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. - - If the process is not created, return an error code. - -3. Call **LOS\_GetAllProcessCpuUsage** to obtain the CPUP of all processes. - - If the CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. - - If CPUP is not initialized or has invalid input parameters, return an error code. - -4. Call **LOS\_HistoryTaskCpuUsage** to obtain the historical CPUP of a specified task. - - If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. - - If the task is not created, return an error code. - -5. Call **LOS\_GetAllIrqCpuUsage** to obtain the CPUP of all interrupts. - - If the CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. - - If CPUP has not been initialized or has invalid input parameters, return an error code. - - -### Development Example + +## Development Guidelines + + +### Available APIs + + **Table 1** CPUP module APIs + +| Category| API| Description| +| -------- | -------- | -------- | +| System CPUP| LOS_HistorySysCpuUsage | Obtains the historical CPUP of the system.| +| Process CPUP| LOS_HistoryProcessCpuUsage | Obtains the historical CPUP of a specified process.| +| Process CPUP| LOS_GetAllProcessCpuUsage | Obtains the historical CPUP of all processes in the system.| +| Task CPUP| LOS_HistoryTaskCpuUsage | Obtains the historical CPUP of a specified task.| +| Interrupt CPUP| LOS_GetAllIrqCpuUsage | Obtains the historical CPUP of all interrupts in the system.| +| Reset| LOS_CpupReset | Resets CPUP data.| + + +### How to Develop + +The typical CPUP development process is as follows: + +1. Call **LOS_HistorySysCpuUsage** to obtain the historical CPUP of the system. + +2. Call **LOS_HistoryProcessCpuUsage** to obtain the historical CPUP of a specified process. + - If the process has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. + - If the process is not created, return an error code. + +3. Call **LOS_GetAllProcessCpuUsage** to obtain the CPUP of all processes. + - If the CPUP is initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. + - If CPUP is not initialized or has invalid input parameters, return an error code. + +4. Call **LOS_HistoryTaskCpuUsage** to obtain the historical CPUP of a specified task. + - If the task has been created, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. + - If the task is not created, return an error code. + +5. Call **LOS_GetAllIrqCpuUsage** to obtain the CPUP of all interrupts. + - If the CPUP has been initialized, disable interrupt, obtain the CPUP in different modes, and then enable interrupt. + - If CPUP is not initialized or has invalid input parameters, return an error code. + + +### Development Example This example implements the following: -1. Create a task for the CPUP test. -2. Obtain the CPUP of the current system. -3. Obtain the historical system CPUP in different modes. -4. Obtain the CPUP of the created test task. -5. Obtain the CPUP of the created test task in different modes. +1. Create a task for the CPUP test. + +2. Obtain the CPUP of the current system. -Prerequisites +3. Obtain the historical system CPUP in different modes. -The CPUP control is enabled in the **menuconfig** configuration. +4. Obtain the CPUP of the created test task. + +5. Obtain the CPUP of the created test task in different modes. + +Prerequisites: + +The CPUP control is enabled in the **menuconfig** configuration. **Sample Code** +You can compile and verify the sample code in **kernel/liteos_a/testsuites /kernel/src /osTest.c**. The **CpupTest** function is called in **TestTaskEntry**. The sample code is as follows: -``` + +```c #include "los_task.h" -#include "los_cpup.h" +#include "los_cpup.h" #define MODE 4 -UINT32 g_cpuTestTaskID; -VOID ExampleCpup(VOID) -{ - printf("entry cpup test example\n"); - while(1) { - usleep(100); +UINT32 g_cpuTestTaskID; +VOID ExampleCpup(VOID) +{ + int i = 0; + dprintf("entry cpup test example\n"); + for (i = 0; i < 10; i++) { + usleep(100); // 100: delay for 100ms } } -UINT32 ItCpupTest(VOID) -{ +UINT32 CpupTest(VOID) +{ UINT32 ret; UINT32 cpupUse; - TSK_INIT_PARAM_S cpupTestTask = { 0 }; + TSK_INIT_PARAM_S cpupTestTask = {0}; memset(&cpupTestTask, 0, sizeof(TSK_INIT_PARAM_S)); cpupTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleCpup; - cpupTestTask.pcName = "TestCpupTsk"; - cpupTestTask.uwStackSize = 0x800; - cpupTestTask.usTaskPrio = 5; + cpupTestTask.pcName = "TestCpupTsk"; + cpupTestTask.uwStackSize = 0x800; // 0x800: cpup test task stack size + cpupTestTask.usTaskPrio = 5; // 5: cpup test task priority ret = LOS_TaskCreate(&g_cpuTestTaskID, &cpupTestTask); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("cpupTestTask create failed .\n"); return LOS_NOK; } - usleep(100); + usleep(100); // 100: delay for 100ms - /* Obtain the historical CPUP of the system. */ - cpupUse = LOS_HistorySysCpuUsage(CPU_LESS_THAN_1S); - printf("the history system cpu usage in all time: %u.%u\n", + /* Obtain the historical CPUP of the system. */ + cpupUse = LOS_HistorySysCpuUsage(CPUP_LAST_ONE_SECONDS); + dprintf("the history system cpu usage in all time: %u.%u\n", cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - /* Obtain the CPUP of the specified task (cpupTestTask in this example).*/ - cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPU_LESS_THAN_1S); - printf("cpu usage of the cpupTestTask in all time:\n TaskID: %d\n usage: %u.%u\n", - g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); - return LOS_OK; + /* Obtain the CPUP of the specified task (cpupTestTask in this example). */ + cpupUse = LOS_HistoryTaskCpuUsage(g_cpuTestTaskID, CPUP_LAST_ONE_SECONDS); + dprintf("cpu usage of the cpupTestTask in all time:\n TaskID: %d\n usage: %u.%u\n", + g_cpuTestTaskID, cpupUse / LOS_CPUP_PRECISION_MULT, cpupUse % LOS_CPUP_PRECISION_MULT); + return LOS_OK; } ``` @@ -180,9 +154,12 @@ UINT32 ItCpupTest(VOID) The development is successful if the return result is as follows: + ``` entry cpup test example the history system cpu usage in all time: 3.0 cpu usage of the cpupTestTask in all time: TaskID:10 usage: 0.0 + +The print information may vary depending on the running environment. ``` diff --git a/en/device-dev/kernel/kernel-small-debug-trace.md b/en/device-dev/kernel/kernel-small-debug-trace.md index df41fd67f3d7d2ddc196e1ea4ddc3c10e701aa95..16831db5798ed777d5394c0fe61176dcdccf04b4 100644 --- a/en/device-dev/kernel/kernel-small-debug-trace.md +++ b/en/device-dev/kernel/kernel-small-debug-trace.md @@ -28,92 +28,89 @@ The online mode must be used with the integrated development environment (IDE). The trace module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h). - **Table 1** APIs of the trace module +**Table 1** APIs of the trace module | Category| Description| | -------- | -------- | -| Starting/Stopping trace| **LOS_TraceStart**: starts trace.
**LOS_TraceStop**: stops trace. | -| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.
**LOS_TraceRecordGet**: obtains the start address of the trace buffer.
**LOS_TraceReset**: clears events in the trace buffer. | +| Starting/Stopping trace| **LOS_TraceStart**: starts trace.
**LOS_TraceStop**: stops trace.| +| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.
**LOS_TraceRecordGet**: obtains the start address of the trace buffer.
**LOS_TraceReset**: clears events in the trace buffer.| | Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.| | Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.| -| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.
**LOS_TRACE**: performs standard instrumentation. | - -You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation: - -- **LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation - - - You only need to insert this API into the source code. - - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined. - - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type. - - **Params** specifies the event parameters. The value is of the **UIntPtr** type. - Example: - - ``` - Perform simple instrumentation for reading and writing files fd1 and fd2. - Set TYPE to 1 for read operations and 2 for write operations. - Insert the following to the position where the fd1 file is read: - LOS_TRACE_EASY(1, fd1, flag, size); - Insert the following to the position where the fd2 file is read: - LOS_TRACE_EASY(1, fd2, flag, size); - Insert the following to the position where the fd1 file is written: - LOS_TRACE_EASY(2, fd1, flag, size); - Insert the following in the position where the fd2 file is written: - LOS_TRACE_EASY(2, fd2, flag, size); - ``` -- **LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation. - - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules. - - **TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types. - - The **IDENTITY** and **Params** are the same as those of simple instrumentation. - Example: - - ``` - 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK. - Format: TRACE_#MOD#_FLAG (MOD indicates the module name) +| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.
**LOS_TRACE**: performs standard instrumentation.| + +- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation: + - **LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation + - You only need to insert this API into the source code. + - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined. + - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type. + - **Params** specifies the event parameters. The value is of the **UIntPtr** type. Example: - TRACE_FS_FLAG = 0x4000 - 2. Define the event type in **enum LOS_TRACE_TYPE**. - Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER - Example: - FS_READ = TRACE_FS_FLAG | 0; // Read files. - FS_WRITE = TRACE_FS_FLAG | 1; // Write files. - 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format. - #TYPE# is the #TYPE# defined in step 2. - Example: - #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size - The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required. - If no parameter is specified, events of this type are not traced. - #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced. - 4. Insert a code stub in a proper position. - Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) - LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files. - The parameters following #TYPE# are the input parameter of the **FS_READ_PARAMS** function in step 3. - ``` - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
- > The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\include\los_trace.h**. - -For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**. -To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**. - -The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**. - -The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**. - -You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules. - -Example: + ``` + Perform simple instrumentation for reading and writing files fd1 and fd2. + Set TYPE to 1 for read operations and 2 for write operations. + Insert the following to the position where the fd1 file is read: + LOS_TRACE_EASY(1, fd1, flag, size); + Insert the following to the position where the fd2 file is read: + LOS_TRACE_EASY(1, fd2, flag, size); + Insert the following to the position where the fd1 file is written: + LOS_TRACE_EASY(2, fd1, flag, size); + Insert the following in the position where the fd2 file is written: + LOS_TRACE_EASY(2, fd2, flag, size); + ``` + - **LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation. + - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules. + - **TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types. + - The **IDENTITY** and **Params** are the same as those of simple instrumentation. + Example: -``` -BOOL Example_HwiNumFilter(UINT32 hwiNum) -{ - if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { - return TRUE; - } - return FALSE; -} -LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); -``` + ``` + 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK. + Format: TRACE_#MOD#_FLAG (MOD indicates the module name) + Example: + TRACE_FS_FLAG = 0x4000 + 2. Define the event type in **enum LOS_TRACE_TYPE**. + Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER + Example: + FS_READ = TRACE_FS_FLAG | 0; // Read files. + FS_WRITE = TRACE_FS_FLAG | 1; // Write files. + 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format. + #TYPE# is the #TYPE# defined in step 2. + Example: + #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size + The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required. + If no parameter is specified, events of this type are not traced. + #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced. + 4. Insert a code stub in a proper position. + Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...)) + LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files. + #The parameters following #TYPE# are the input parameter of the **FS_READ_PARAMS** function in step 3. + ``` + + > **NOTE**
+ > The preset trace events and parameters can be tailored in the same way. For details about the parameters, see [kernel\include\los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h). + +- For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**. + +- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**. + +- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**. + +- The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**. + +- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules. + Example: + + ```c + BOOL Example_HwiNumFilter(UINT32 hwiNum) + { + if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) { + return TRUE; + } + return FALSE; + } + LOS_TraceHwiFilterHookReg(Example_HwiNumFilter); + ``` The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced. @@ -128,8 +125,8 @@ The trace character device is added in **/dev/trace**. You can use **read()**, * - **ioctl()**: performs user-mode trace operations, including: - -``` + +```c #define TRACE_IOC_MAGIC 'T' #define TRACE_START _IO(TRACE_IOC_MAGIC, 1) #define TRACE_STOP _IO(TRACE_IOC_MAGIC, 2) @@ -151,25 +148,24 @@ For details, see [User-Mode Development Example](kernel-small-debug-trace.md#use The typical trace process is as follows: 1. Configure the macro related to the trace module. - Configure the macro **LOSCFG_KERNEL_TRACE**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel** > **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**. - -| Configuration Item | menuconfig Option| Description| Value| -| -------- | -------- | -------- | -------- | -| LOSCFG_KERNEL_TRACE | Enable Trace Feature | Specifies whether to enable the trace feature.| YES/NO | -| LOSCFG_RECORDER_MODE_OFFLINE | Trace work mode ->Offline mode | Specifies whether to enable the online trace mode.| YES/NO | -| LOSCFG_RECORDER_MODE_ONLINE | Trace work mode ->Online mode | Specifies whether to enable the offline trace mode.| YES/NO | -| LOSCFG_TRACE_CLIENT_INTERACT | Enable Trace Client Visualization and Control | Enables interaction with Trace IDE (dev tools), including data visualization and process control.| YES/NO | -| LOSCFG_TRACE_FRAME_CORE_MSG | Enable Record more extended content -
>Record cpuid, hardware interrupt
 status, task lock status | Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.| YES/NO | -| LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable Record more extended content
 ->Record event count,
 which indicate the sequence of happend events | Specifies whether to enables recording of the event sequence number.| YES/NO | -| LOSCFG_TRACE_FRAME_MAX_PARAMS | Record max params | Specifies the maximum number of parameters for event recording.| INT | -| LOSCFG_TRACE_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT | + + | Item| menuconfig Option| Description| Value| + | -------- | -------- | -------- | -------- | + | LOSCFG_KERNEL_TRACE | Enable Trace Feature | Specifies whether to enable the trace feature.| YES/NO | + | LOSCFG_RECORDER_MODE_OFFLINE | Trace work mode -> Offline mode | Specifies whether to enable the online trace mode.| YES/NO | + | LOSCFG_RECORDER_MODE_ONLINE | Trace work mode -> Online mode | Specifies whether to enable the offline trace mode.| YES/NO | + | LOSCFG_TRACE_CLIENT_INTERACT | Enable Trace Client Visualization and Control | Enables interaction with Trace IDE (dev tools), including data visualization and process control.| YES/NO | + | LOSCFG_TRACE_FRAME_CORE_MSG | Enable Record more extended content -> Record cpuid, hardware interrupt status, task lock status | Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.| YES/NO | + | LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable Record more extended content -> Record event count, which indicate the sequence of happend events | Specifies whether to enables recording of the event sequence number.| YES/NO | + | LOSCFG_TRACE_FRAME_MAX_PARAMS | Record max params | Specifies the maximum number of parameters for event recording.| INT | + | LOSCFG_TRACE_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT | 2. (Optional) Preset event parameters and stubs (or use the default event parameter settings and event stubs). 3. (Optional) Call **LOS_TraceStop** to stop trace and call **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.) -4. (Optional) Call **LOS_TraceEventMaskSet** to set the event mask for trace (only the interrupts and task events are enabled by default). For details about the event mask, see **LOS_TRACE_MASK** in **los_trace.h**. +4. (Optional) Call **LOS_TraceEventMaskSet** to set the mask of the events to be traced. The default event mask enables only trace of interrupts and task events. For details about the event masks, see **LOS_TRACE_MASK** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h). 5. Call **LOS_TraceStart** at the start of the code where the event needs to be traced. @@ -177,7 +173,7 @@ The typical trace process is as follows: 7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.) -The methods in steps 3 to 7 are encapsulated with shell commands. You can run these commands on shell. The mappings between the functions and commands are as follows: +The methods in steps 3 to 7 are encapsulated with shell commands. You can run these commands on shell. The mappings between the methods and commands are as follows: - LOS_TraceReset —— trace_reset @@ -207,50 +203,53 @@ This example implements the following: ### Kernel-Mode Sample Code +You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites /kernel /src/osTest.c** for testing. + The sample code is as follows: -``` +```c #include "los_trace.h" UINT32 g_traceTestTaskId; VOID Example_Trace(VOID) -{ - UINT32 ret; +{ + UINT32 ret; LOS_TaskDelay(10); /* Start trace. */ - ret = LOS_TraceStart(); - if (ret != LOS_OK) { - dprintf("trace start error\n"); - return; - } - /* Trigger a task switching event. */ - LOS_TaskDelay(1); - LOS_TaskDelay(1); - LOS_TaskDelay(1); - /* Stop trace. */ - LOS_TraceStop(); + ret = LOS_TraceStart(); + if (ret != LOS_OK) { + dprintf("trace start error\n"); + return; + } + /* Trigger a task switching event. */ + LOS_TaskDelay(1); + LOS_TaskDelay(1); + LOS_TaskDelay(1); + /* Stop trace. */ + LOS_TraceStop(); LOS_TraceRecordDump(FALSE); } -UINT32 Example_Trace_test(VOID){ - UINT32 ret; - TSK_INIT_PARAM_S traceTestTask; - /* Create a trace task. */ - memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); - traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; - traceTestTask.pcName = "TestTraceTsk"; /* Test task name. */ - traceTestTask.uwStackSize = 0x800; - traceTestTask.usTaskPrio = 5; - traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; - ret = LOS_TaskCreate(&g_traceTestTaskId, &traceTestTask); - if(ret != LOS_OK){ - dprintf("TraceTestTask create failed .\n"); - return LOS_NOK; - } +UINT32 Example_Trace_test(VOID) +{ + UINT32 ret; + TSK_INIT_PARAM_S traceTestTask; + /* Create a trace task. */ + memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S)); + traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace; + traceTestTask.pcName = "TestTraceTsk"; /* Test task name. */ + traceTestTask.uwStackSize = 0x800; // 0x800: trace test task stack size + traceTestTask.usTaskPrio = 5; // 5: trace test task priority + traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED; + ret = LOS_TaskCreate(&g_traceTestTaskId, &traceTestTask); + if (ret != LOS_OK) { + dprintf("TraceTestTask create failed .\n"); + return LOS_NOK; + } /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then start trace. */ - LOS_TraceStop(); - LOS_TraceReset(); - /* Enable trace of the Task module events. */ - LOS_TraceEventMaskSet(TRACE_TASK_FLAG); + LOS_TraceStop(); + LOS_TraceReset(); + /* Enable trace of the Task module events. */ + LOS_TraceEventMaskSet(TRACE_TASK_FLAG); return LOS_OK; } LOS_MODULE_INIT(Example_Trace_test, LOS_INIT_LEVEL_KMOD_EXTENDED); @@ -266,7 +265,7 @@ The output is as follows: ***TraceInfo begin*** clockFreq = 50000000 CurEvtIndex = 7 -Index Time(cycles) EventType CurTask Identity params +Index Time(cycles) EventType CurTask Identity params 0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4 0x0 1 0x366d74ae 0x45 0x0 0x1 0x0 0x8 0x1f 2 0x36940da6 0x45 0x1 0xc 0x1f 0x4 0x9 @@ -280,13 +279,13 @@ Index Time(cycles) EventType CurTask Identity params The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event. -- **EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. +- **EventType**: type of the event. For details, see **enum LOS_TRACE_TYPE** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h). - **CurrentTask**: ID of the running task. -- **Identity**: object of the event operation. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**. +- **Identity**: object of the event operation. For details, see **\#TYPE\#_PARAMS** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h). -- **params**: event parameters. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**. +- **params**: event parameters. For details, see **\#TYPE\#_PARAMS** in [los_trace.h](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h). The following uses output No. 0 as an example. @@ -302,14 +301,15 @@ Index Time(cycles) EventType CurTask Identity params - For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro. -``` +```c #define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \ taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus ``` Because of **#TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ...**, **Identity** is **taskId (0x0)** and the first parameter is **oldPriority (0x1f)**. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements. Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**. diff --git a/en/device-dev/kernel/kernel-small-debug-user.md b/en/device-dev/kernel/kernel-small-debug-user.md index 3a852dae6af647df07ad01dacf12d4cd6dcd92f1..fbdfc0d131f8018f3ceeac1fd9764e99ca5db79f 100644 --- a/en/device-dev/kernel/kernel-small-debug-user.md +++ b/en/device-dev/kernel/kernel-small-debug-user.md @@ -1,11 +1,10 @@ # User-Mode Memory Debugging ## Basic Concepts +The musl libc library of the debug version provides mechanisms, such as memory leak check, heap memory statistics, memory corruption check, and backtrace, to improve the efficiency in locating memory problems in user space. -The musl libc library of the debug version provides maintenance and test methods, such as memory leak check, heap memory statistics, memory corruption check, and backtrace, to improve the efficiency of locating memory problems in user space. - -Instrumentation is performed on the **malloc** and **free** APIs to log key node information. When memory is requested and released by a program, the memory node integrity is checked. When the program ends, memory statistics are provided for identifying memory leaks. +Instrumentation is performed in the **malloc** and **free** APIs to log key node information. The memory node integrity is checked when memory is requested and released by an application. When the application ends, memory statistics are provided to help identifying memory leaks. ## Working Principles @@ -18,15 +17,15 @@ When memory is requested, key information is saved to the memory node control bl When memory is released, the system matches the memory node control block based on the memory address to be released and deletes the control block. - **Figure 1** Heap memory node linked list +**Figure 1** Heap memory node linked list - ![](figures/heap-memory-node-linked-list.png "heap-memory-node-linked-list") +![](figures/heap-memory-node-linked-list.png "heap-memory-node-linked-list") -When memory is allocated, the returned address is saved in a link register (LR). During the process running, the system adds information, such as the LR corresponding to the suspected leak, to the memory node control block. shows the heap memory node information. +When memory is allocated, the returned address is saved in a link register (LR). During the process running, the system adds information, such as the LR corresponding to the suspected leak, to the memory node control block. The following figure shows the heap memory node information. - **Figure 2** Heap memory node information +**Figure 2** Heap memory node information - ![](figures/heap-memory-node-information.png "heap-memory-node-information") +![](figures/heap-memory-node-information.png "heap-memory-node-information") **TID** indicates the thread ID; **PID** indicates the process ID; **ptr** indicates the address of the memory requested; **size** indicates the size of the requested memory; **lr[*n*]** indicates the address of the call stack, and *n* is configurable. @@ -34,9 +33,9 @@ When memory is released, the input parameter pointer in the **free** API is used You can export the memory debugging information of each process through the serial port or file, and use the addr2line tool to convert the exported information into the code lines that cause memory leaks. In this way, the memory leakage problem can be solved. - **Figure 3** Process of locating the code line for a memory leak +**Figure 3** Process of locating the code line for a memory leak - ![](figures/process-of-locating-the-code-lines-for-a-memory-leak.png "process-of-locating-the-code-lines-for-a-memory-leak") +![](figures/process-of-locating-the-code-lines-for-a-memory-leak.png "process-of-locating-the-code-lines-for-a-memory-leak") ### Heap Memory Statistics @@ -46,25 +45,33 @@ You can collect statistics on the percentage of heap memory requested by each th ### Memory Integrity Check -- If the memory requested by using **malloc** is less than or equal to 0x1c000 bytes, the heap allocation algorithm is used to allocate memory. +- Requested memory less than or equal to 0x1c000 bytes + + When the requested memory is less than or equal to 0x1c000 bytes, **malloc** uses the heap allocation algorithm to allocate memory. + When a user program requests heap memory, information such as the check value is added to the heap memory node. If the check value is abnormal, it is probably that the previous heap memory block is overwritten. Currently, the scenario where the check value is damaged by a wild pointer cannot be identified. When memory is allocated or released, the memory node check value is verified. If the memory node is corrupted and the verification fails, the following information is output: TID, PID, and call stack information saved when the previous heap memory block of the corrupted node is allocated. You can use the addr2line tool to obtain the specific code line and rectify the fault. + + **Figure 4** Adding a check value to the node header information + + ![](figures/adding-a-check-value-to-the-node-header-information.png "adding-a-check-value-to-the-node-header-information") + + When heap memory is released by **free**, the memory block is not released immediately. Instead, the magic number 0xFE is written into the memory block, which is then placed in the free queue to prevent the memory block from being allocated by **malloc** within a certain period of time. When a wild pointer or **use-after-free** operation is performed to read the memory, an exception can be detected. However, this mechanism does not apply to write operations. + + **Figure 5** Process of releasing memory + + ![](figures/process-of-releasing-memory.png "process-of-releasing-memory") + + + +- Requested memory greater than 0x1c000 bytes - **Figure 4** Adding a check value to the node header information - - ![](figures/adding-a-check-value-to-the-node-header-information.png "adding-a-check-value-to-the-node-header-information") - - When heap memory is released by using **free**, the memory block is not released immediately. Instead, the magic number 0xFE is written into the memory block, which is then placed in the free queue to prevent the memory block from being allocated by **malloc** within a certain period of time. When a wild pointer or **use-after-free** operation is performed to read the memory, an exception can be detected. However, this mechanism does not apply to write operations. - - **Figure 5** Process of releasing memory - - ![](figures/process-of-releasing-memory.png "process-of-releasing-memory") + When the requested memory is greater than 0x1c000 bytes, **malloc** uses **mmap** to allocate memory. -- If the memory requested by using **malloc** is greater than 0x1c000 bytes, **mmap** is used to allocate memory. - When **mmap** is used to request a large memory block, one more page is allocated at the start and end of the memory region. The current **PAGE_SIZE** of each page is **0x1000**. The permissions of the two pages are set to **PROT_NONE** (no read or write permission) by using the **mprotect** API to prevent out-of-bounds read and write of memory. If out-of-bounds read and write of memory occurs, the user program becomes abnormal because the user does not have the read or write permission. The code logic can be identified based on the abnormal call stack information. + When **mmap** is used to allocate a large memory block, one more page is allocated at the start and end of the memory region. The current **PAGE_SIZE** of each page is **0x1000**. The permissions of the two pages are set to **PROT_NONE** (no read or write permission) by using the **mprotect** API to prevent out-of-bounds read and write of memory. If out-of-bounds read and write of memory occurs, the user program becomes abnormal because the user does not have the read or write permission. The code logic can be identified based on the abnormal call stack information. - **Figure 6** Layout of the memory allocated by using the **mmap** mechanism of **malloc** + **Figure 6** Layout of the memory allocated by using the **mmap** mechanism of **malloc** - ![](figures/layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc.png "layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc") + ![](figures/layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc.png "layout-of-the-memory-allocated-by-using-the-mmap-mechanism-of-malloc") ### Usage Guide #### Available APIs @@ -105,7 +112,7 @@ You can perform heap memory debugging by using either of the following: - CLI: By using the CLI, you do not need to modify user code. However, you cannot accurately check the heap memory information of a specific logic segment. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> After memory debugging is enabled, a heap memory leak check and a heap memory integrity check will be performed by default when a process exits. If memory debugging is disabled, the heap memory statistics, heap memory leak check, and heap memory integrity check cannot be enabled, and there is no response to the calling of any debug API. @@ -119,7 +126,7 @@ You can perform heap memory debugging by using either of the following: The sample code explicitly calls the related APIs of the memory debugging module to check the memory. -``` +```c #include #include #include @@ -127,7 +134,8 @@ The sample code explicitly calls the related APIs of the memory debugging module #define MALLOC_LEAK_SIZE 0x300 -void func(void) { +void func(void) +{ char *ptr = malloc(MALLOC_LEAK_SIZE); memset(ptr, '3', MALLOC_LEAK_SIZE); } @@ -156,17 +164,18 @@ $ clang -o mem_check mem_check.c -funwind-tables -rdynamic -g -mfloat-abi=softfp ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - In this example, the compiler path is written into an environment variable in the **.bashrc** file. -> +> > - When compiling user programs and required libraries, add the option **-funwind-tables -rdynamic -g** for stack backtracking. -> +> > - The **-mfloat-abi=softfp**, **-mcpu=cortex-a7**, and **-mfpu=neon-vfpv4** options specify the floating-point calculation optimization, chip architecture, and FPU, which must be the same as the compilation options used by the libc library. Otherwise, the libc library file cannot be found during the link time. -> +> > - **-target arm-liteos** specifies the path of the library files related to the compiler. -> +> > - **--sysroot=/home//harmony/out/hispark_taurus/ipcamera_hispark_taurus/sysroot** specifies the root directory of the compiler library files. In this example, the OpenHarmony project code is stored in **/home//harmony**. The **out/hispark_taurus/ipcamera_hispark_taurus** directory indicates the product specified by the **hb set** command during compilation. In this example, **ipcamera_hispark_taurus** is the product specified. -> +> > - **$(clang -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos -print-file-name=libunwind.a)** specifies the path of the unwind library. @@ -175,7 +184,7 @@ $ clang -o mem_check mem_check.c -funwind-tables -rdynamic -g -mfloat-abi=softfp ``` OHOS # ./mem_check -OHOS # +OHOS # ==PID:4== Heap memory statistics(bytes): // Heap memory statistics [Check point]: // Call stack of the check point #00: [0x86c] -> mem_check @@ -293,14 +302,15 @@ kill -37 # Check whether the head node of the heap memory is complete. The sample code constructs a memory problem and uses the command line to perform memory debugging. -``` +```c #include #include #include #define MALLOC_LEAK_SIZE 0x300 -void func(void) { +void func(void) +{ char *ptr = malloc(MALLOC_LEAK_SIZE); memset(ptr, '3', MALLOC_LEAK_SIZE); } @@ -317,7 +327,7 @@ int main() ##### Compilation -For details, see [Compilation](kernel-small-debug-user.md#compilation). +For details, see [Compilation](#compilation). ##### Running the mwatch Command @@ -325,9 +335,9 @@ For details, see [Compilation](kernel-small-debug-user.md#compilation). ``` OHOS # ./mem_check --mwatch // Run the task command to obtain the mem_check process PID, which is 4. -OHOS # +OHOS # OHOS # kill -35 4 // Check heap memory statistics. -OHOS # +OHOS # ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x58dfc] -> /lib/libc.so @@ -337,7 +347,7 @@ OHOS # ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) OHOS # kill -36 4 // Check for heap memory leaks. -OHOS # +OHOS # ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2da4c] -> /lib/libc.so @@ -355,7 +365,7 @@ OHOS # ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). OHOS # kill -37 4 // Check the integrity of the head node of the heap memory. -OHOS # +OHOS # Check heap integrity ok! ``` @@ -391,131 +401,132 @@ Now using addr2line ... ##### Running the mrecord Command 1. Run the user program and specify the path of the file that stores the memory debugging information. - + ``` OHOS # ./mem_check --mrecord /storage/check.txt ``` 2. Run the **kill -35 <*pid*>** command to collect statistics on the memory information. The information is exported to a file. Run the **cat** command to view the information. - + ``` OHOS # kill -35 4 OHOS # Memory statistics information saved in /storage/pid(4)_check.txt - + OHOS # cat /storage/pid(4)_check.txt - + ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x5973c] -> /lib/libc.so - + [TID: 18, Used: 0x640] - + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) ``` 3. Run the **kill -36 <*pid*>** command to check memory integrity. The information is exported to a file. Run the **cat** command to view the information. - + ``` OHOS # kill -36 4 OHOS # Leak check information saved in /storage/pid(4)_check.txt - + OHOS # cat /storage/pid(4)_check.txt - + ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x5973c] -> /lib/libc.so - + [TID: 18, Used: 0x640] - + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) - + ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2e38c] -> /lib/libc.so #01: [0x5973c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x724] -> mem_check #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x6ec] -> mem_check #01: [0x740] -> mem_check #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). ``` 4. Run the **kill -9 <*pid*>** command to kill the current process. After the process exits, a memory integrity check is performed by default. The check result is output to a file. You can run the **cat** command to view it. - + ``` OHOS # kill -9 4 OHOS # Leak check information saved in /storage/pid(4)_check.txt - + Check heap integrity ok! - + OHOS # cat /storage/pid(4)_check.txt - OHOS # + OHOS # ==PID:4== Heap memory statistics(bytes): [Check point]: #00: [0x5973c] -> /lib/libc.so - + [TID: 18, Used: 0x640] - + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) - + ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2e38c] -> /lib/libc.so #01: [0x5973c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x724] -> mem_check #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x6ec] -> mem_check #01: [0x740] -> mem_check #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). - + ==PID:4== Detected memory leak(s): [Check point]: #00: [0x2e38c] -> /lib/libc.so #01: [0x11b2c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x724] -> mem_check #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + [TID:18 Leak:0x320 byte(s)] Allocated from: #00: [0x6ec] -> mem_check #01: [0x740] -> mem_check #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so - + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> The preceding information recorded gradually is added to the file specified during initialization. Therefore, running the **cat** command can also display the historical information in the file. ## Common Problems ### Use After Free (UAF) -- Requested memory block less than or equal to 0x1c000 bytes: - After the memory is released: - +- Requested memory less than or equal to 0x1c000 bytes: + Read operation: If the magic number (0xFEFEFEFE) is read from the memory block released, UAF occurs. - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+ + > **NOTE** + > > After **free** is called, the heap memory will not be released to the heap memory pool immediately. Instead, the heap memory is placed in a queue with a fixed length and filled with the magic number 0xFE. When the queue is full, the memory block first placed in the queue is released to the heap memory pool first. - + Write operation: The memory debugging module cannot detect UAF errors from write operations. - Requested memory block greater than 0x1c000 bytes: + The heap memory greater than 0x1c000 bytes must be requested by calling the **mmap** API via **malloc**. If the heap memory is accessed after being released, the user program will become abnormal (because the memory region has been unmapped). @@ -527,16 +538,17 @@ Double free errors occur when **free()** is called more than once with the same ### Heap Memory Node Corrupted - Requested memory block less than or equal to 0x1c000 bytes: + When a heap memory node is corrupted, the user program exits unexpectedly, and the call stack that requests the heap memory of the node corrupted is output. The memory debugging module, however, cannot debug the memory corrupted by a wild pointer. For example, if the user program mem_check has heap memory overwriting, you can use the command line to obtain the possible location of the memory corruption. - + ``` - OHOS # ./mem_check --mwatch - OHOS # + OHOS # ./mem_check --mwatch + OHOS # ==PID:6== Memory integrity information: [TID:28 allocated addr: 0x272e1ea0, size: 0x120] The possible attacker was allocated from: #00: [0x640e8] -> /lib/libc.so - #01: [0x21d0] -> mem_check + #01: [0x21d0] -> mem_check ``` You can use the call stack parsing script to parse the call stack information. diff --git a/en/device-dev/kernel/kernel-small-memory-lms.md b/en/device-dev/kernel/kernel-small-memory-lms.md index 277cbea8a28268a9c4597be980a22bb69f8f85f8..937f088a803a8058ad045e27a231b5f662ceacbc 100644 --- a/en/device-dev/kernel/kernel-small-memory-lms.md +++ b/en/device-dev/kernel/kernel-small-memory-lms.md @@ -59,23 +59,20 @@ The user mode provides only the LMS check library. It does not provide external The typical process for enabling LMS is as follows: 1. Configure the macros related to the LMS module. - Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**. - - | Macro| menuconfig Option| Description| Value:| + + | Macro| menuconfig Option| Description| Value | | -------- | -------- | -------- | -------- | | LOSCFG_KERNEL_LMS | Enable Lms Feature | Whether to enable LMS.| YES/NO | | LOSCFG_LMS_MAX_RECORD_POOL_NUM | Lms check pool max num | Maximum number of memory pools that can be checked by LMS.| INT | | LOSCFG_LMS_LOAD_CHECK | Enable lms read check | Whether to enable LMS read check.| YES/NO | | LOSCFG_LMS_STORE_CHECK | Enable lms write check | Whether to enable LMS write check.| YES/NO | | LOSCFG_LMS_CHECK_STRICT | Enable lms strict check, byte-by-byte | Whether to enable LMS byte-by-byte check.| YES/NO | - - -2. Modify the build script of the target module. +2. Modify the build script of the target module. Add **-fsanitize=kernel-address** to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler. - The modifications vary depending on the compiler (GCC or Clang) used. The following is an example: + The modifications vary depending on the compiler (GCC or Clang) used. The following is an example: ``` if ("$ohos_build_compiler_specified" == "gcc") { @@ -113,9 +110,10 @@ This example implements the following: #### Kernel-Mode Sample Code - The sample code is as follows: +The functions of the sample code can be added to **TestTaskEntry** in **kernel /liteos_a/testsuites /kernel /src /osTest.c** for testing. +The sample code is as follows: -``` +```c #define PAGE_SIZE (0x1000U) #define INDEX_MAX 20 UINT32 g_lmsTestTaskId; @@ -141,31 +139,32 @@ static VOID LmsTestUseAfterFree(VOID) PRINTK("\n######%s start ######\n", __FUNCTION__); UINT32 i; CHAR *str = (CHAR *)LOS_MemAlloc(g_testLmsPool, INDEX_MAX); - LOS_MemFree(g_testLmsPool, str); + (VOID)LOS_MemFree(g_testLmsPool, str); PRINTK("str[%2d]=0x%2x ", 0, str[0]); /* trigger use after free at str[0] */ PRINTK("\n######%s stop ######\n", __FUNCTION__); } VOID LmsTestCaseTask(VOID) -{ +{ testPoolInit(); LmsTestOsmallocOverflow(); LmsTestUseAfterFree(); } -UINT32 Example_Lms_test(VOID){ - UINT32 ret; - TSK_INIT_PARAM_S lmsTestTask; - /* Create a task for LMS. */ - memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); +UINT32 Example_Lms_test(VOID) +{ + UINT32 ret; + TSK_INIT_PARAM_S lmsTestTask; + /* Create a task for LMS. */ + memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S)); lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask; - lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */ - lmsTestTask.uwStackSize = 0x800; - lmsTestTask.usTaskPrio = 5; - lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; - ret = LOS_TaskCreate(&g_lmsTestTaskId, &lmsTestTask); - if(ret != LOS_OK){ - PRINT_ERR("LmsTestTask create failed .\n"); - return LOS_NOK; - } + lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */ + lmsTestTask.uwStackSize = 0x800; // 0x800: LMS test task stack size + lmsTestTask.usTaskPrio = 5; // 5: LMS test task priority + lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED; + ret = LOS_TaskCreate(&g_lmsTestTaskId, &lmsTestTask); + if (ret != LOS_OK) { + PRINT_ERR("LmsTestTask create failed .\n"); + return LOS_NOK; + } return LOS_OK; } LOS_MODULE_INIT(Example_Lms_test, LOS_INIT_LEVEL_KMOD_EXTENDED); @@ -260,7 +259,7 @@ The key output information is as follows: ### User-Mode Development Process -Add the following to the build script of the app to be checked. For details about the complete code, see **/kernel/liteos_a/apps/lms/BUILD.gn**. +Add the following to the app build script to be checked. For details about the sample code, see [/kernel/liteos_a/apps/lms/BUILD.gn](https://gitee.com/openharmony/kernel_liteos_a/blob/master/apps/lms/BUILD.gn). ``` @@ -318,7 +317,7 @@ This example implements the following: The code is as follows: -``` +```c static void BufWriteTest(void *buf, int start, int end) { for (int i = start; i <= end; i++) { @@ -335,7 +334,7 @@ static void BufReadTest(void *buf, int start, int end) static void LmsMallocTest(void) { printf("\n-------- LmsMallocTest Start --------\n"); - char *buf = (char *)malloc(16); + char *buf = (char *)malloc(16); // 16: buffer size for test BufReadTest(buf, -1, 16); free(buf); printf("\n-------- LmsMallocTest End --------\n"); @@ -343,7 +342,7 @@ static void LmsMallocTest(void) static void LmsFreeTest(void) { printf("\n-------- LmsFreeTest Start --------\n"); - char *buf = (char *)malloc(16); + char *buf = (char *)malloc(16); // 16: buffer size for test free(buf); BufReadTest(buf, 1, 1); free(buf); @@ -352,7 +351,7 @@ static void LmsFreeTest(void) int main(int argc, char * const * argv) { printf("\n############### Lms Test start ###############\n"); - char *tmp = (char *)malloc(5000); + char *tmp = (char *)malloc(5000); // 5000: temp buffer size LmsMallocTest(); LmsFreeTest(); printf("\n############### Lms Test End ###############\n"); diff --git a/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md b/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md index 7deeec6316d5750a5615740fb25dade24fe23fb9..88eb7f5a3a015cf03a57b20bf861963cf93c9e24 100644 --- a/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md +++ b/en/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md @@ -3,7 +3,7 @@ ## Overview ### Kconfig Visual Configuration -Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html#introduction). It allows customized configuration of OpenHarmony subsystem components. +Kconfig visual configuration is implemented on [Kconfiglib](https://github.com/ulfalizer/Kconfiglib) and [Kconfig](https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html). It allows customized configuration of OpenHarmony subsystem components. Kconfig visual configuration has the following advantages: @@ -44,7 +44,7 @@ Kconfig visual configuration has the following advantages: 4. Set parameters. - For details about the parameters, see [productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json). + For details about the parameters, see productdefine/common/base/base_product.json. ![Setting parameters](./figure/kconfig_set_parameters.gif) @@ -99,7 +99,7 @@ Kconfig visual configuration has the following advantages: ### Latest Components Not Displayed in the Menu List -The component list [productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json) is updated with product updates and iterations. The Kconfig menu does not contain the latest components. +The component list productdefine/common/base/base_product.json is updated with product updates and iterations. The Kconfig menu does not contain the latest components. **Solution** diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md index cb0f8cead65cd1faed98c723d30f557b4302bbab..1369bb7bc6f4fe3c5aeb24693c72b550a387b60c 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @@ -9,7 +9,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** - Command for subscribing to real-time system events: - ``` + ```shell hisysevent -r ``` @@ -21,7 +21,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** - Command for enabling the debugging mode: - ``` + ```shell hisysevent -r -d ``` @@ -29,11 +29,11 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | Option| Description| | -------- | -------- | - | -d | Subscription to real-time system events in debugging mode.| + | -d | Subscribes to real-time system events in debugging mode.| - Command for subscribing to real-time system events by event tag: - ``` + ```shell hisysevent -r -t [-c [WHOLE_WORD|PREFIX|REGULAR]] ``` @@ -42,12 +42,12 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | Option| Description| | -------- | -------- | | -t | Event tag used to filter subscribed real-time system events.| - | -c | Matching rule for event tags. The option can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| + | -c | Matching rule for event tags. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| Example: - ``` - # hisysevent -r -t "STA" -c PREFIX + ```shell + # hisysevent -r -t "STA" -c PREFIX {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963670809,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200750","HAPPEN_TIME":1501963670809,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"4973863135535405472","info_":""} # hisysevent -r -t "STAw{0,6}" -c REGULAR {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963793206,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200953","HAPPEN_TIME":1501963793206,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} @@ -57,7 +57,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** - Command for subscribing to real-time system events by event domain and event name: - ``` + ```shell hisysevent -r -o -n [-c [WHOLE_WORD|PREFIX|REGULAR]] ``` @@ -67,11 +67,11 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | -------- | -------- | | -o | Event domain used to filter subscribed real-time system events.| | -n | Event name used to filter subscribed real-time system events.| - | -c | Matching rule for event domains and event names. The option can be **WHOLE_WORD**, PREFIX, or **REGULAR**.| + | -c | Matching rule for event domains and event names. The options can be **WHOLE_WORD**, PREFIX, or **REGULAR**.| Example: - ``` + ```shell # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} # hisysevent -r -o "RELIABI\w{0,8}" -n "APP_FREEZE" -c REGULAR @@ -85,7 +85,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** - Command for subscribing to real-time system events by event type: - ``` + ```shell hisysevent -r -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] ``` @@ -97,7 +97,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Example: - ``` + ```shell # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -g FAULT {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} # hisysevent -r -o "POWER\w{0,8}" -n "POWER_RUNNINGLOCK" -c REGULAR -g STATISTIC @@ -108,11 +108,12 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} ``` + ## Querying Historical System Events - Command for querying historical system events: - ``` + ```shell hisysevent -l ``` @@ -124,7 +125,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** - Command for querying historical system events within the specified period of time: - ``` + ```shell hisysevent -l -s -e ``` @@ -132,21 +133,46 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | Option| Description| | -------- | -------- | - | -s | Start time for querying historical system events. Only system events generated after the start time are returned.| - | -e | End time for querying historical system events. Only system events generated before the end time are returned.| + | -s | Original start timestamp for querying historical system events. Only system events generated after the start time are returned.| + | -e | Original end timestamp for querying historical system events. Only system events generated before the end time are returned.| Example: - ``` + ```shell # hisysevent -l -s 1501964222980 -e 1501964222996 {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} {"domain_":"GRAPHIC","name_":"NO_DRAW","type_":1,"time_":1501964222980,"tz_":"+0000","pid_":1505,"tid_":1585,"uid_":10002,"PID":1505,"UID":10002,"ABILITY_NAME":"","MSG":"It took 1957104259905ns to draw, UI took 0ns to draw, RSRenderThread took 8962625ns to draw, RSRenderThread dropped 0 UI Frames","level_":"MINOR","id_":"1708287249901948387","info_":"isResolved,eventId:0"} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222994,"tz_":"+0000","pid_":623,"tid_":1445,"uid_":1201,"SUB_EVENT_TYPE":"NO_DRAW","EVENT_TIME":"20170805201702","MODULE":"NO_DRAW","PNAME":"NO_DRAW","REASON":"NO_DRAW","DIAG_INFO":"","STACK":"SUMMARY:\n","HIVIEW_LOG_FILE_PATHS":["/data/log/faultlog/faultlogger/appfreeze-NO_DRAW-10002-20170805201702"],"DOMAIN":"GRAPHIC","STRING_ID":"NO_DRAW","PID":1505,"UID":10002,"PACKAGE_NAME":"NO_DRAW","PROCESS_NAME":"","MSG":"It took 1956945826265ns to draw, UI took 0ns to draw, RSRenderThread took 9863293ns to draw, RSRenderThread dropped 0 UI Frames\n","level_":"CRITICAL","tag_":"STABILITY","id_":"10448522101019619655","info_":""} ``` -- Command for setting the maximum number of historical events that can be queried: +- Command for querying historical system events within the specified period of time: + ```shell + hisysevent -l -S -E ``` + + Description of command options: + + | Option| Description| + | -------- | -------- | + | -S | Original start timestamp for querying historical system events. Only system events generated after the start time are returned.| + | -E | Original end timestamp for querying historical system events. Only system events generated after the start time are returned.| + + Example: + + ```shell + # hisysevent -l -S "2023-01-05 14:12:50" -E "2023-01-05 14:12:51" + {"domain_":"GRAPHIC","name_":"JANK_FRAME_SKIP","type_":1,"time_":1672899170022,"tz_":"+0800","pid_":1499,"tid_":1573,"uid_":20010037,"PID":1499,"UID":20010037,"ABILITY_NAME":"com.ohos.launcher","MSG":"It took 587948726ns to draw, UI took 483016382ns to draw, RSRenderThread took 96616051ns to draw, RSRenderThread dropped 0 UI Frames","level_":"MINOR","id_":"11351278822867091090","info_":"","seq_":307} + {"domain_":"AAFWK","name_":"START_ABILITY_ERROR","type_":1,"time_":1672899170108,"tz_":"+0800","pid_":550,"tid_":1127,"uid_":5523,"USER_ID":-1,"BUNDLE_NAME":"com.ohos.wallpaper","MODULE_NAME":"","ABILITY_NAME":"WallpaperExtAbility","ERROR_CODE":2097152,"level_":"MINOR","tag_":"ability","id_":"53589395004188308060","info_":"","seq_":313} + {"domain_":"GRAPHIC","name_":"JANK_FRAME_SKIP","type_":1,"time_":1672899170305,"tz_":"+0800","pid_":1293,"tid_":1632,"uid_":10006,"PID":1293,"UID":10006,"ABILITY_NAME":"com.ohos.systemui","MSG":"It took 309597490ns to draw, UI took 92364718ns to draw, RSRenderThread took 205874105ns to draw, RSRenderThread dropped 1 UI Frames","level_":"MINOR","id_":"14843220972178010722","info_":"","seq_":314} + {"domain_":"GRAPHIC","name_":"JANK_FRAME_SKIP","type_":1,"time_":1672899170350,"tz_":"+0800","pid_":1293,"tid_":1632,"uid_":10006,"PID":1293,"UID":10006,"ABILITY_NAME":"com.ohos.systemui","MSG":"It took 259782859ns to draw, UI took 33909753ns to draw, RSRenderThread took 44849879ns to draw, RSRenderThread dropped 5 UI Frames","level_":"MINOR","id_":"66610006717219916560","info_":"","seq_":315} + {"domain_":"AAFWK","name_":"CONNECT_SERVICE_ERROR","type_":1,"time_":1672899170733,"tz_":"+0800","pid_":550,"tid_":1127,"uid_":5523,"USER_ID":100,"BUNDLE_NAME":"com.ohos.wallpaper","MODULE_NAME":"","ABILITY_NAME":"WallpaperExtAbility","ERROR_CODE":2097152,"level_":"MINOR","tag_":"ability","id_":"10040008376311927188","info_":"","seq_":317} + {"domain_":"COMMONEVENT","name_":"PUBLISH","type_":2,"time_":1672899170063,"tz_":"+0800","pid_":550,"tid_":937,"uid_":5523,"USER_ID":-1,"PUBLISHER_BUNDLE_NAME":"","PID":0,"UID":1101,"EVENT_NAME":"usual.event.SCREEN_ON","level_":"MINOR","id_":"80996758983032931610","info_":"","seq_":308} + ``` + +- Command for setting the maximum number of historical events that can be queried: + + ```shell hisysevent -l -m ``` @@ -158,14 +184,14 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Example: - ``` + ```shell # hisysevent -l -s 1501964222980 -e 1501964222996 -m 1 {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} ``` - Command for querying historical system events by event domain and event name: - ``` + ```shell hisysevent -l -o -n [-c WHOLE_WORD] ``` @@ -173,24 +199,24 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | Option| Description| | -------- | -------- | - | -o | Domain based on which historical system events are queried.| - | -n | Name based on which historical system events are queried.| + | -o | Event domain based on which historical system events are queried.| + | -n | Event name based on which historical system events are queried.| | -c | Rule for matching the domain and name of historical system events. The option can only be **WHOLE_WORD**.| Example: - ``` + ```shell # hisysevent -l -n "APP_FREEZE" {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} - # hisysevent -r -o "RELIABILITY" + # hisysevent -l -o "RELIABILITY" {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""} - # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -c WHOLE_WORD + # hisysevent -l -o "RELIABILITY" -n "APP_FREEZE" -c WHOLE_WORD {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""} ``` - Command for querying historical system events by event type: - ``` + ```shell hisysevent -l -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] ``` @@ -202,7 +228,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Example: - ``` + ```shell # hisysevent -l -o "RELIABILITY" -g FAULT {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} # hisysevent -l -n "POWER_RUNNINGLOCK" -c WHOLE_WORD -g STATISTIC @@ -217,7 +243,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** - Enabling system event validity check - ``` + ```shell hisysevent -v ``` @@ -229,7 +255,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** Example: - ``` + ```shell # hisysevent -v -l -s 1501964222980 -e 1501964222996 # The **HAPPEN_TIME** and **VERSION** fields are not configured in the YAML file for the **APP_FREEZE** event that belongs to the **RELIABILITY** domain. Therefore, the two fields are highlighted in red. {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md index 655d5f1348b234110937883f1a8d7899ef0e3ca8..76b0bf08104a53dfb2d943ae3a860bfc76111dc1 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.1/changelogs-url.md @@ -1,28 +1,28 @@ -# ChangeLog of JS API Changes in the URL Subsystem +# Utils Subsystem Changelog -Compared with OpenHarmony 3.2 Beta4, OpenHarmony 3.2.10.1(Mr) has the following API changes in the URL subsystem: +Compared with OpenHarmony 3.2 Beta4, OpenHarmony 3.2.10.1(MR) has the following API changes in the URL module of the utils subsystem. -## cl.url.1 URLParams Class API Changes -APIs in the **URLParams** class in the URL subsystem are changed: +## cl.commonlibrary.1 URLParams Class Changes +The constructor function of the **URLParams** class in the URL module of the utils subsystem is changed. -**constructor(init?: string[][] | Record | string | URLSearchParams)** is changed to **constructor(init?: string[][] | Record | string | URLParams)**, and the parameter type is changed from URLSearchParams to URLParams. +Specifically, **constructor(init?: string[][] | Record | string | URLSearchParams)** is changed to **constructor(init?: string[][] | Record | string | URLParams)**, and the parameter type is changed from **URLSearchParams** to **URLParams**. -You need to adapt your application based on the following information. +You need to adapt your application. **Change Impacts** -JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement functions in the SDK environment of the new version. +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. **Key API/Component Changes** -| Module | Class | Method/Attribute/Enumeration/Constant | Change Type| -| :-------- | --------- | ------------------------------------------------------------ | -------- | -| @ohos.url | URLParams | constructor(string[][] \| Record<string, string> \| string \| URLSearchParams) | Deleted | -| @ohos.url | URLParams | constructor(string[][] \| Record<string, string> \| string \| URLParams)| Changed| +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| :------------------------ | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.url | URLParams | constructor(string[][] \| Record<string, string> \| string \| URLSearchParams) | Deleted | +| @ohos.url | URLParams | constructor(string[][] \| Record<string, string> \| string \| URLParams)| Changed **Adaptation Guide** -The following illustrates how to create a **URLParams** object in your application: +The following illustrates how to create a **URLParams** object in your application. Example: @@ -37,27 +37,27 @@ try { console.error(`Fail to ceate URLParams.codeis${err.code},message is ${err.message}`); } ``` -## cl.url.2 URL Attribute Changes of URLParams Class APIs -URL attributes in the URL subsystem are changed: +## cl.commonlibrary.2 URL Attribute Changes of URLParams Class APIs +The URL attributes of the URL module in the utils subsystem are changed. -The **searchParams: URLSearchParams** attribute is deprecated, and the **params: URLParams** attribute is added. +Specifically, the **searchParams: URLSearchParams** attribute is deprecated, and the **params: URLParams** attribute is added. -You need to adapt your application based on the following information. +You need to adapt your application. **Change Impacts** -JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement functions in the SDK environment of the new version. +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. **Key API/Component Changes** -| Module | Class| Method/Attribute/Enumeration/Constant | Change Type | -| :-------- | ---- | ------------------------------ | --------------- | -| @ohos.url | URL | searchParams: URLSearchParams; | Deprecated (in API version 9)
| -| @ohos.url | URL | params: URLParams; | Added | +| Module | Class | Method/Attribute/Enum/Constant | Change Type| +| :------------------------ | ------------------- | ------------------------------------------------------------ | -------- | +| @ohos.url | URL | searchParams: URLSearchParams; |Deprecated (in API version 9)
| +| @ohos.url | URL | params: URLParams; | Added | **Adaptation Guide** -The following illustrates how to create a **URLParams** object in your application: +The following illustrates how to create a **URLParams** object in your application. Example: diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.2/changelogs-bundlemanager.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.2/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..4542c0a871e0f6474220756a2528a514dbfa2f71 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.2/changelogs-bundlemanager.md @@ -0,0 +1,42 @@ +# Bundle Manager Subsystem ChangeLog + +## cl.bundlemanager.1 Field Change of the ApplicationInfo Structure in API Version 9 + +The **ApplicationInfo** structure [[bundleManager/applicationInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/applicationInfo.d.ts)] in API version 9 has field changes, with the **systemApp** field being added and the **entryDir** field being deleted. + +**Change Impacts** + +There is no impact on applications that use the APIs of versions earlier than 9. The applications that use the APIs of version 9 need to adapt new modules and APIs. + +**Key API/Component Changes** + +The following table describes the changed fields in the **ApplicationInfo** structure. + +| Deleted Field | Added or Changed Field in API Version 9| Type | +| -------- | -------------- | ------- | +| None | systemApp | boolean | +| entryDir | None | string | + +**Adaptation Guide** + +Import the bundle manager query module and use the **systemApp** field in the **ApplicationInfo** structure of API version 9. If the **entryDir** field is used, change the field because it is redundant in features where HAP decompression is not required. + +## cl.bundlemanager.2 Field Change of the HapModuleInfo Structure in API Version 9 + +The **moduleSourceDir** field is deleted from the **HapModuleInfo** structure [[bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts)] in API version 9. + +**Change Impacts** + +There is no impact on applications that use the APIs of versions earlier than 9. The applications that use the APIs of version 9 need to adapt new modules and APIs. + +**Key API/Component Changes** + +The following table describes the changed fields in the **HapModuleInfo** structure. + +| Deleted Field | Added or Changed Field in API Version 9| Type | +| --------------- | -------------- | ------ | +| moduleSourceDir | None | string | + +**Adaptation Guide** + +Import the bundle manager query module and do not use the **moduleSourceDir** field in the **HapModuleInfo** structure of API version 9. If the **moduleSourceDir** field is used, change the field because it is redundant in features where HAP decompression is not required. diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-bundlemanager.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..ed95a11140efc969e38d2ba50ad6ec1ed4d08b96 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-bundlemanager.md @@ -0,0 +1,21 @@ +# Bundle Manager Subsystem ChangeLog + +## cl.bundlemanager.1 Name Change of the Bundle Manager Distributed Query Module + +The name of the bundle manager distributed query module in API version 9 is changed from **ohos.bundle.distributedBundle** to **[ohos.bundle.distributedBundleManager](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.bundle.distributedBundleManager.d.ts)**. The APIs remain unchanged. + +**Change Impacts** + +There is no impact on applications that use the APIs of versions earlier than 9. The applications that use the APIs of version 9 need to adapt the new module. + +**Key API/Component Changes** + +The name of the bundle manager distributed query module is changed from **ohos.bundle.distributedBundle** to **ohos.bundle.distributedBundleManager**. The APIs remain unchanged. + +**Adaptation Guide** + +Change the module to import from **@ohos.bundle.distributedBundle** to **@ohos.bundle.distributedBundleManager**. + +```ts +import distributedBundle form '@ohos.bundle.distributedBundleManager'; +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-camera-sync.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-camera-sync.md new file mode 100644 index 0000000000000000000000000000000000000000..c20c9e4c50f8de7ba2c8a0323f19d2000e4007ad --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-camera-sync.md @@ -0,0 +1,522 @@ +# Multimedia Subsystem ChangeLog + +Compared with OpenHarmony 3.2 Beta4, OpenHarmony3.2.10.3 has the following changes in APIs of the camera component in the multimedia subsystem. + +## cl.subsystemname.1 Camera API Changed +1. All the APIs of the camera component are changed to system APIs in the API version 9. +2. Some functional APIs are added and some others are deprecated to: + +- Improve the usability of camera APIs. +- Help you quickly understand camera APIs and use them for development. +- Facilitate expansion of framework functions in later versions, and reduce coupling between framework modules. + +You need to refer to the following change description to adapt your application. + +**Change Impacts** + +JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version. + +**Key API/Component Changes** + +| Module | Class | Method/Attribute/Enum/Constant | Is System API| Change Type| +| ---------------------- | ----------------------- | ------------------------------------------------------------ | --------------- | -------- | +| ohos.multimedia.camera | camera | function getCameraManager(context: Context): CameraManager; | Yes | Added | +| ohos.multimedia.camera | camera | function getCameraManager(context: Context, callback: AsyncCallback): void;
function getCameraManager(context: Context): Promise; | Yes | Deprecated | +| ohos.multimedia.camera | CameraErrorCode | INVALID_ARGUMENT = 7400101,
OPERATION_NOT_ALLOWED = 7400102,
SESSION_NOT_CONFIG = 7400103,
SESSION_NOT_RUNNING = 7400104,
SESSION_CONFIG_LOCKED = 7400105,
DEVICE_SETTING_LOCKED = 7400106,
CONFILICT_CAMERA = 7400107,
DEVICE_DISABLED = 7400108,
SERVICE_FATAL_ERROR = 7400201 | Yes | Added | +| ohos.multimedia.camera | CameraManager | getSupportedCameras(): Array;
getSupportedOutputCapability(camera: CameraDevice): CameraOutputCapability;
createCameraInput(camera: CameraDevice): CameraInput;
createCameraInput(position: CameraPosition, type: CameraType): CameraInput;
createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput;
createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput;
createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput;
createMetadataOutput(metadataObjectTypes: Array): MetadataOutput;
createCaptureSession(): CaptureSession; | Yes | Added | +| ohos.multimedia.camera | CameraManager | getSupportedCameras(callback: AsyncCallback>): void;
getSupportedCameras(): Promise>;
getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback): void;
getSupportedOutputCapability(camera: CameraDevice): Promise;
createCameraInput(camera: CameraDevice, callback: AsyncCallback): void;
createCameraInput(camera: CameraDevice): Promise;
createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void;
createCameraInput(position: CameraPosition, type: CameraType): Promise;
createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void;
createPreviewOutput(profile: Profile, surfaceId: string): Promise;
createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void;
createPhotoOutput(profile: Profile, surfaceId: string): Promise;
createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void;
createVideoOutput(profile: VideoProfile, surfaceId: string): Promise;
createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void;
createMetadataOutput(metadataObjectTypes: Array): Promise;
createCaptureSession(callback: AsyncCallback): void;
createCaptureSession(): Promise; | Yes | Deprecated | +| ohos.multimedia.camera | CameraType | CAMERA_TYPE_DEFAULT = 0 | Yes | Added | +| ohos.multimedia.camera | CameraType | CAMERA_TYPE_UNSPECIFIED = 0 | Yes | Deprecated | +| ohos.multimedia.camera | CameraInput | on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void; | Yes | Added | +| ohos.multimedia.camera | CameraInput | release(callback: AsyncCallback): void;
release(): Promise;
on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void; | Yes | Deprecated | +| ohos.multimedia.camera | CameraInputErrorCode | ERROR_UNKNOWN = -1
ERROR_NO_PERMISSION = 0
ERROR_DEVICE_PREEMPTED = 1
ERROR_DEVICE_DISCONNECTED = 2
ERROR_DEVICE_IN_USE = 3
ERROR_DRIVER_ERROR = 4 | Yes | Deprecated | +| ohos.multimedia.camera | CameraInputError | code: CameraInputErrorCode | Yes | Deprecated | +| ohos.multimedia.camera | CaptureSession | beginConfig(): void;
addInput(cameraInput: CameraInput): void;
removeInput(cameraInput: CameraInput): void;
addOutput(cameraOutput: CameraOutput): void;
removeOutput(cameraOutput: CameraOutput): void;
hasFlash(): boolean;
isFlashModeSupported(flashMode: FlashMode): boolean;
getFlashMode(): FlashMode;
setFlashMode(flashMode: FlashMode): void;
isExposureModeSupported(aeMode: ExposureMode): boolean;
getExposureMode(): ExposureMode;
setExposureMode(aeMode: ExposureMode): void;
getMeteringPoint(): Point;
setMeteringPoint(point: Point): void;
getExposureBiasRange(): Array;
setExposureBias(exposureBias: number): void;
getExposureValue(): number;
isFocusModeSupported(afMode: FocusMode): boolean;
getFocusMode(): FocusMode;
setFocusMode(afMode: FocusMode): void;
setFocusPoint(point: Point): void;
getFocusPoint(): Point;
getFocalLength(): number;
getZoomRatioRange(): Array;
getZoomRatio(): number;
setZoomRatio(zoomRatio: number): void;
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean;
getActiveVideoStabilizationMode(): VideoStabilizationMode;
setVideoStabilizationMode(mode: VideoStabilizationMode): void;
on(type: 'error', callback: ErrorCallback): void; | Yes | Added | +| ohos.multimedia.camera | CaptureSession | beginConfig(callback: AsyncCallback): void;
beginConfig(): Promise;
addInput(cameraInput: CameraInput, callback: AsyncCallback): void;
addInput(cameraInput: CameraInput): Promise;
removeInput(cameraInput: CameraInput, callback: AsyncCallback): void;
removeInput(cameraInput: CameraInput): Promise;
addOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void;
addOutput(cameraOutput: CameraOutput): Promise;
removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void;
removeOutput(cameraOutput: CameraOutput): Promise;
hasFlash(callback: AsyncCallback): void;
hasFlash(): Promise;
isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void;
isFlashModeSupported(flashMode: FlashMode): Promise;
getFlashMode(callback: AsyncCallback): void;
getFlashMode(): Promise;
setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void;
setFlashMode(flashMode: FlashMode): Promise;
isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void;
isExposureModeSupported(aeMode: ExposureMode): Promise;
getExposureMode(callback: AsyncCallback): void;
getExposureMode(): Promise;
setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void;
setExposureMode(aeMode: ExposureMode): Promise;
getMeteringPoint(callback: AsyncCallback): void;
getMeteringPoint(): Promise;
setMeteringPoint(point: Point, callback: AsyncCallback): void;
setMeteringPoint(point: Point): Promise;
getExposureBiasRange(callback: AsyncCallback>): void;
getExposureBiasRange(): Promise>;
setExposureBias(exposureBias: number, callback: AsyncCallback): void;
setExposureBias(exposureBias: number): Promise;
getExposureValue(callback: AsyncCallback): void;
getExposureValue(): Promise;
isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void;
isFocusModeSupported(afMode: FocusMode): Promise;
getFocusMode(callback: AsyncCallback): void;
getFocusMode(): Promise;
setFocusMode(afMode: FocusMode, callback: AsyncCallback): void;
setFocusMode(afMode: FocusMode): Promise;
setFocusPoint(point: Point, callback: AsyncCallback): void;
setFocusPoint(point: Point): Promise;
getFocusPoint(callback: AsyncCallback): void;
getFocusPoint(): Promise;
getFocalLength(callback: AsyncCallback): void;
getFocalLength(): Promise;
getZoomRatioRange(callback: AsyncCallback>): void;
getZoomRatioRange(): Promise>;
getZoomRatio(callback: AsyncCallback): void;
getZoomRatio(): Promise;
setZoomRatio(zoomRatio: number, callback: AsyncCallback): void;
setZoomRatio(zoomRatio: number): Promise;
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void;
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise;
getActiveVideoStabilizationMode(callback: AsyncCallback): void;
getActiveVideoStabilizationMode(): Promise;
setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void;
setVideoStabilizationMode(mode: VideoStabilizationMode): Promise;
on(type: 'error', callback: ErrorCallback): void; | Yes | Deprecated | +| ohos.multimedia.camera | CaptureSessionErrorCode | ERROR_UNKNOWN = -1
ERROR_INSUFFICIENT_RESOURCES = 0
ERROR_TIMEOUT = 1 | Yes | Deprecated | +| ohos.multimedia.camera | CaptureSessionError | code: CaptureSessionErrorCode | Yes | Deprecated | +| ohos.multimedia.camera | PreviewOutput | on(type: 'error', callback: ErrorCallback): void; | Yes | Added | +| ohos.multimedia.camera | PreviewOutput | on(type: 'error', callback: ErrorCallback): void; | Yes | Deprecated | +| ohos.multimedia.camera | PreviewOutputErrorCode | ERROR_UNKNOWN = -1 | Yes | Deprecated | +| ohos.multimedia.camera | PreviewOutputError | code: PreviewOutputErrorCode | Yes | Deprecated | +| ohos.multimedia.camera | PhotoOutput | capture(): Promise;
isMirrorSupported(): boolean;
on(type: 'error', callback: ErrorCallback): void; | Yes | Added | +| ohos.multimedia.camera | PhotoOutput | isMirrorSupported(callback: AsyncCallback): void;
isMirrorSupported(): Promise;
on(type: 'error', callback: ErrorCallback): void; | Yes | Deprecated | +| ohos.multimedia.camera | PhotoOutputErrorCode | ERROR_UNKNOWN = -1
ERROR_DRIVER_ERROR = 0
ERROR_INSUFFICIENT_RESOURCES = 1
ERROR_TIMEOUT = 2 | Yes | Deprecated | +| ohos.multimedia.camera | PhotoOutputError | code: PhotoOutputErrorCode | Yes | Deprecated | +| ohos.multimedia.camera | VideoOutput | on(type: 'error', callback: ErrorCallback): void; | Yes | Added | +| ohos.multimedia.camera | VideoOutput | on(type: 'error', callback: ErrorCallback): void; | Yes | Deprecated | +| ohos.multimedia.camera | VideoOutputErrorCode | ERROR_UNKNOWN = -1
ERROR_DRIVER_ERROR = 0 | Yes | Deprecated | +| ohos.multimedia.camera | VideoOutputError | code: VideoOutputErrorCode | Yes | Deprecated | +| ohos.multimedia.camera | MetadataObject | readonly type: MetadataObjectType;
readonly timestamp: number; | Yes | Added | +| ohos.multimedia.camera | MetadataObject | getType(callback: AsyncCallback): void;
getType(): Promise;
getTimestamp(callback: AsyncCallback): void;
getTimestamp(): Promise;
getBoundingBox(callback: AsyncCallback): void;
getBoundingBox(): Promise; | Yes | Deprecated | +| ohos.multimedia.camera | MetadataFaceObject | readonly boundingBox: Rect | Yes | Added | +| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback): void; | Yes | Added | +| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback): void; | Yes | Deprecated | +| ohos.multimedia.camera | MetadataOutputErrorCode | ERROR_UNKNOWN = -1
ERROR_INSUFFICIENT_RESOURCES = 0 | Yes | Deprecated | +| ohos.multimedia.camera | MetadataOutputError | code: MetadataOutputErrorCode | Yes | Deprecated | + +**Adaptation Guide** + +In addition to the new APIs and deprecated APIs, you need to adapt your application to the changed APIs. + +In Beta4 and later versions, the following APIs are changed. + +**New APIs** + +1. **CameraErrorCode** enums + + Enum: INVALID_ARGUMENT; value: 7400101 + + Enum: OPERATION_NOT_ALLOWED; value: 7400102 + + Enum: SESSION_NOT_CONFIG; value: 7400103 + + Enum: SESSION_NOT_RUNNING; value: 7400104 + + Enum: SESSION_CONFIG_LOCKED; value: 7400105 + + Enum: DEVICE_SETTING_LOCKED; value: 7400106 + + Enum: CONFILICT_CAMERA; value: 7400107 + + Enum: DEVICE_DISABLED; value: 7400108 + + Enum: SERVICE_FATAL_ERROR; value: 7400201 + +2. Added **capture(): Promise** to the **PhotoOutput** API. + +3. Added the readonly type **MetadataObjectType** to the **MetadataObject** API. + +4. Added **readonly timestamp: number** to the **MetadataObject** API. + +5. Added **readonly boundingBox: Rect** to the **MetadataObject** API. + +**Deprecated APIs** + +1. Deprecated the **release(callback: AsyncCallback): void** and **release(): Promise** APIs in **CameraInput**. + +2. Deprecated the **CameraInputErrorCode** enums and all their values: **ERROR_UNKNOWN** = **-1**, **ERROR_NO_PERMISSION** = **0**, **ERROR_DEVICE_PREEMPTED** = **1**, **ERROR_DEVICE_DISCONNECTED** = **2**, **ERROR_DEVICE_IN_USE** = **3**, **ERROR_DRIVER_ERROR** = **4** + +3. Deprecated the **CameraInputError** API and its attribute **CameraInputErrorCode**. + +4. Deprecated the **CaptureSessionErrorCode** enums and all their values: **ERROR_UNKNOWN** = **-1**, **ERROR_INSUFFICIENT_RESOURCES** = **0**, **ERROR_TIMEOUT** = **1** + +5. Deprecated the **CaptureSessionError** API and its attribute **CaptureSessionErrorCode**. + +6. Deprecated the **PreviewOutputErrorCode** enum and its value: **ERROR_UNKNOWN** = **-1** + +7. Deprecated the **PreviewOutputError** API and its attribute **PreviewOutputErrorCode**. + +8. Deprecated the **PhotoOutputErrorCode** enums and all their values: **ERROR_UNKNOWN** = **-1**, **ERROR_DRIVER_ERROR** = **0**, **ERROR_INSUFFICIENT_RESOURCES** = **1**, **ERROR_TIMEOUT** = **2** + +9. Deprecated the **PhotoOutputError** API and its attribute **PhotoOutputErrorCode**. + +10. Deprecated the **VideoOutputErrorCode** enums and all their values: **ERROR_UNKNOWN** = **-1**, **ERROR_DRIVER_ERROR** = **0** + +11. Deprecated the **VideoOutputError** API and its attribute **VideoOutputErrorCode**. + +12. Deprecated **getType(callback: AsyncCallback): void** in the **MetadataObject** API. + +13. Deprecated **getType(): Promise** in the **MetadataObject** API. + +14. Deprecated **getTimestamp(callback: AsyncCallback): void** in the **MetadataObject** API. + +15. Deprecated **getTimestamp(): Promise** in the **MetadataObject** API. + +16. Deprecated **getBoundingBox(callback: AsyncCallback): void** in the **MetadataObject** API. + +17. Deprecated **getBoundingBox(): Promise** in the **MetadataObject** API. + +18. Deprecated the **MetadataOutputErrorCode** enums and all their values: **ERROR_UNKNOWN** = **-1**, **ERROR_INSUFFICIENT_RESOURCES** = **0** + +19. Deprecated the **MetadataOutputError** API and its attribute **MetadataOutputErrorCode**. + +**Changed APIs** + +1. Changed the return modes of the **getCameraManager** API in the camera module from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getCameraManager(context: Context, callback: AsyncCallback): void** and **getCameraManager(context: Context): Promise** are changed to **getCameraManager(context: Context): CameraManager**. + + The sample code is as follows: + + ``` + let cameraManager = camera.getCameraManager(context); + ``` + +2. Changed the return modes of the **getSupportedCameras** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getSupportedCameras(callback: AsyncCallback>): void** and **getSupportedCameras(): Promise>** are changed to **getSupportedCameras(): Array**. + + The sample code is as follows: + + ``` + let cameras = cameraManager.getSupportedCameras(); + ``` + +3. Changed the return modes of the **getSupportedOutputCapability** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback): void** and **getSupportedOutputCapability(camera: CameraDevice): Promise** are changed to **getSupportedOutputCapability(camera: CameraDevice): CameraOutputCapability**. + + The sample code is as follows: + + ``` + let cameraDevice = cameras[0]; + let CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice); + ``` + +4. Changed the return modes of the **createCameraInput(camera: CameraDevice)** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createCameraInput(camera: CameraDevice, callback: AsyncCallback): void** and **createCameraInput(camera: CameraDevice): Promise** are changed to **createCameraInput(camera: CameraDevice): CameraInput**. + + The sample code is as follows: + + ``` + let cameraDevice = cameras[0]; + let cameraInput = cameraManager.createCameraInput(cameraDevice); + ``` + +5. Changed the return modes of the **createCameraInput(position: CameraPosition, type: CameraType)** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void** and **createCameraInput(position: CameraPosition, type: CameraType): Promise** are changed to **createCameraInput(position: CameraPosition, type: CameraType): CameraInput**. + + The sample code is as follows: + + ``` + let cameraDevice = cameras[0]; + let position = cameraDevice.cameraPosition; + let type = cameraDevice.cameraType; + let cameraInput = cameraManager.createCameraInput(position, type); + ``` + +6. Changed the return modes of the **createPreviewOutput** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void** and **createPreviewOutput(profile: Profile, surfaceId: string): Promise** are changed to **createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput**. + + The sample code is as follows: + + ``` + let profile = cameraoutputcapability.previewProfiles[0]; + let previewOutput = cameraManager.createPreviewOutput(profile, surfaceId); + ``` + +7. Changed the return modes of the **createPhotoOutput** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void** and **createPhotoOutput(profile: Profile, surfaceId: string): Promise** are changed to **createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput**. + + The sample code is as follows: + + ``` + let profile = cameraoutputcapability.photoProfiles[0]; + let photoOutput = cameraManager.createPhotoOutput(profile, surfaceId); + ``` + +8. Changed the return modes of the **createVideoOutput** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void** and **createVideoOutput(profile: VideoProfile, surfaceId: string): Promise** are changed to **createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput**. + + The sample code is as follows: + + ``` + let profile = cameraoutputcapability.videoProfiles[0]; + let videoOutput = cameraManager.createVideoOutput(profile, surfaceId); + ``` + +9. Changed the return modes of the **createMetadataOutput** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void** and **createMetadataOutput(metadataObjectTypes: Array): Promise** are changed to **createMetadataOutput(metadataObjectTypes: Array): MetadataOutput**. + + The sample code is as follows: + + ``` + let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes; + let metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes); + ``` + +10. Changed the return modes of the **createCaptureSession** API in CameraManager from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **createCaptureSession(callback: AsyncCallback): void** and **createCaptureSession(): Promise** are changed to **createCaptureSession(): CaptureSession**. + + The sample code is as follows: + + ``` + let captureSession = cameraManager.createCaptureSession(); + ``` + +11. Changed the enum **CAMERA_TYPE_UNSPECIFIED** of **CameraType** to **CAMERA_TYPE_DEFAULT**. + +12. Changed the return value type of the **on** API in CameraInput from **CameraInputError** to **BusinessError**. Therefore, the original API **on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void** is changed to **on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void**. + + The sample code is as follows: + + ``` + let cameraDevice = cameras[0]; + cameraInput.on('error', cameraDevice, (BusinessError) => { + + }) + ``` + +13. Changed the return modes of the **beginConfig** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **beginConfig(callback: AsyncCallback): void** and **beginConfig(): Promise** are changed to **beginConfig(): void**. + + The sample code is as follows: + + ``` + captureSession.beginConfig(); + ``` + +14. Changed the return modes of the **addInput** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **addInput(cameraInput: CameraInput, callback: AsyncCallback): void** and **addInput(cameraInput: CameraInput): Promise** are changed to **addInput(cameraInput: CameraInput): void**. + + The sample code is as follows: + + ``` + captureSession.addInput(cameraInput); + ``` + +15. Changed the return modes of the **removeInput** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **removeInput(cameraInput: CameraInput, callback: AsyncCallback): void** and **removeInput(cameraInput: CameraInput): Promise** are changed to **removeInput(cameraInput: CameraInput): void**. + + The sample code is as follows: + + ``` + captureSession.removeInput(cameraInput); + ``` + +16. Changed the return modes of the **addOutput** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **addOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void** and **addOutput(cameraOutput: CameraOutput): Promise** are changed to **addOutput(cameraOutput: CameraOutput): void**. + + The sample code is as follows: + + ``` + captureSession.addOutput(previewOutput); + ``` + +17. Changed the return modes of the **removeOutput** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void** and **removeOutput(cameraOutput: CameraOutput): Promise** are changed to **removeOutput(cameraOutput: CameraOutput): void**. + + The sample code is as follows: + + ``` + captureSession.removeOutput(previewOutput); + ``` + +18. Changed the return modes of the **hasFlash** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **hasFlash(callback: AsyncCallback): void** and **hasFlash(): Promise** are changed to **hasFlash(): boolean**. + + The sample code is as follows: + + ``` + let status = captureSession.hasFlash(); + ``` + +19. Changed the return modes of the **isFlashModeSupported** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void** and **isFlashModeSupported(flashMode: FlashMode): Promise** are changed to **isFlashModeSupported(flashMode: FlashMode): boolean**. + + The sample code is as follows: + + ``` + let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); + ``` + +20. Changed the return modes of the **getFlashMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getFlashMode(callback: AsyncCallback): void** and **getFlashMode(): Promise** are changed to **getFlashMode(): FlashMode**. + + The sample code is as follows: + + ``` + let flashMode = captureSession.getFlashMode(); + ``` + +21. Changed the return modes of the **isExposureModeSupported** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void** and **isExposureModeSupported(aeMode: ExposureMode): Promise** are changed to **isExposureModeSupported(aeMode: ExposureMode): boolean**. + + The sample code is as follows: + + ``` + let isSupported = captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED); + ``` + +22. Changed the return modes of the **getExposureMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getExposureMode(callback: AsyncCallback): void** and **getExposureMode(): Promise** are changed to **getExposureMode(): ExposureMode**. + + The sample code is as follows: + + ``` + let exposureMode = captureSession.getExposureMode(); + ``` + +23. Changed the return modes of the **setExposureMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void** and **setExposureMode(aeMode: ExposureMode): Promise** are changed to **setExposureMode(aeMode: ExposureMode): void**. + + The sample code is as follows: + + ``` + captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED); + ``` + +24. Changed the return modes of the **getMeteringPoint** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getMeteringPoint(callback: AsyncCallback): void** and **getMeteringPoint(): Promise** are changed to **getMeteringPoint(): Point**. + + The sample code is as follows: + + ``` + let exposurePoint = captureSession.getMeteringPoint(); + ``` + +25. Changed the return modes of the **setMeteringPoint** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setMeteringPoint(point: Point, callback: AsyncCallback): void** and **setMeteringPoint(point: Point): Promise** are changed to **setMeteringPoint(point: Point): void**. + + The sample code is as follows: + + ``` + let Point2 = {x: 2, y: 2}; + captureSession.setMeteringPoint(Point2); + ``` + +26. Changed the return modes of the **getExposureBiasRange** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getExposureBiasRange(callback: AsyncCallback>): void** and **getExposureBiasRange(): Promise>** are changed to **getExposureBiasRange(): Array**. + + The sample code is as follows: + + ``` + let biasRangeArray = captureSession.getExposureBiasRange(); + ``` + +27. Changed the return modes of the **setExposureBias** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setExposureBias(exposureBias: number, callback: AsyncCallback): void** and **setExposureBias(exposureBias: number): Promise** are changed to **setExposureBias(exposureBias: number): void**. + + The sample code is as follows: + + ``` + let exposureBias = biasRangeArray[0]; + captureSession.setExposureBias(exposureBias); + ``` + +28. Changed the return modes of the **getExposureValue** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getExposureValue(callback: AsyncCallback): void** and **getExposureValue(): Promise** are changed to **getExposureValue(): number**. + + The sample code is as follows: + + ``` + let exposureValue = captureSession.getExposureValue(); + ``` + +29. Changed the return modes of the **isFocusModeSupported** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void** and **isFocusModeSupported(afMode: FocusMode): Promise** are changed to **isFocusModeSupported(afMode: FocusMode): boolean**. + + The sample code is as follows: + + ``` + let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO); + ``` + +30. Changed the return modes of the **getFocusMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getFocusMode(callback: AsyncCallback): void** and **getFocusMode(): Promise** are changed to **getFocusMode(): FocusMode**. + + The sample code is as follows: + + ``` + let afMode = captureSession.getFocusMode(); + ``` + +31. Changed the return modes of the **setFocusMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setFocusMode(afMode: FocusMode, callback: AsyncCallback): void** and **setFocusMode(afMode: FocusMode): Promise** are changed to **setFocusMode(afMode: FocusMode): void**. + + The sample code is as follows: + + ``` + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO); + ``` + +32. Changed the return modes of the **setFocusPoint** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setFocusPoint(point: Point, callback: AsyncCallback): void** and **setFocusPoint(point: Point): Promise** are changed to **setFocusPoint(point: Point): void**. + + The sample code is as follows: + + ``` + let Point2 = {x: 2, y: 2}; + captureSession.setFocusPoint(Point2); + ``` + +33. Changed the return modes of the **getFocusPoint** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getFocusPoint(callback: AsyncCallback): void** and **getFocusPoint(): Promise** are changed to **getFocusPoint(): Point**. + + The sample code is as follows: + + ``` + let point = captureSession.getFocusPoint(); + ``` + +34. Changed the return modes of the **getFocalLength** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getFocalLength(callback: AsyncCallback): void** and **getFocalLength(): Promise** are changed to **getFocalLength(): number**. + + The sample code is as follows: + + ``` + let focalLength = captureSession.getFocalLength(); + ``` + +35. Changed the return modes of the **getZoomRatioRange** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getZoomRatioRange(callback: AsyncCallback>): void** and **getZoomRatioRange(): Promise>** are changed to **getZoomRatioRange(): Array**. + + The sample code is as follows: + + ``` + let zoomRatioRange = captureSession.getZoomRatioRange(); + ``` + +36. Changed the return modes of the **getZoomRatio** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getZoomRatio(callback: AsyncCallback): void** and **getZoomRatio(): Promise** are changed to **getZoomRatio(): number**. + + The sample code is as follows: + + ``` + let zoomRatio = captureSession.getZoomRatio(); + ``` + +37. Changed the return modes of the **setZoomRatio** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setZoomRatio(zoomRatio: number, callback: AsyncCallback): void** and **setZoomRatio(zoomRatio: number): Promise** are changed to **setZoomRatio(zoomRatio: number): void**. + + The sample code is as follows: + + ``` + let zoomRatio = zoomRatioRange[0]; + captureSession.setZoomRatio(zoomRatio); + ``` + +38. Changed the return modes of the **isVideoStabilizationModeSupported** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void** and **isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise** are changed to **isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean**. + + The sample code is as follows: + + ``` + let isSupported = captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF); + ``` + +39. Changed the return modes of the **getActiveVideoStabilizationMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **getActiveVideoStabilizationMode(callback: AsyncCallback): void** and **getActiveVideoStabilizationMode(): Promise** are changed to **getActiveVideoStabilizationMode(): VideoStabilizationMode**. + + The sample code is as follows: + + ``` + let vsMode = captureSession.getActiveVideoStabilizationMode(); + ``` + +40. Changed the return modes of the **setVideoStabilizationMode** API in CaptureSession from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void** and **setVideoStabilizationMode(mode: VideoStabilizationMode): Promise** are changed to **setVideoStabilizationMode(mode: VideoStabilizationMode): void**. + + The sample code is as follows: + + ``` + captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF); + ``` + +41. Changed the **on(type:'error') callback** type in CaptureSession from **ErrorCallback** to **ErrorCallback**. Therefore, the original API **on(type: 'error', callback: ErrorCallback): void** is changed to **on(type: 'error', callback: ErrorCallback): void**. + + The sample code is as follows: + + ``` + captureSession.on('error', (BusinessError) => { + + }) + ``` + +42. Changed the **on(type:'error') callback** type in PreviewOutput, from **ErrorCallback** to **ErrorCallback**. Therefore, the original API **on(type: 'error', callback: ErrorCallback): void** is changed to **on(type: 'error', callback: ErrorCallback): void**. + + The sample code is as follows: + + ``` + previewOutput.on('error', (BusinessError) => { + + }) + ``` + +43. Changed the return modes of the **isMirrorSupported** API in PhotoOutput from asynchronous callback and asynchronous promise to the synchronous mode. Therefore, the original APIs **isMirrorSupported(callback: AsyncCallback): void** and **isMirrorSupported(): Promise** are changed to **isMirrorSupported(): boolean**. + + The sample code is as follows: + + ``` + let isSupported = photoOutput.isMirrorSupported(); + ``` + +44. Changed the **on(type:'error') callback** type in PhotoOutput, from **ErrorCallback** to **ErrorCallback**. Therefore, the original API **on(type: 'error', callback: ErrorCallback): void** is changed to **on(type: 'error', callback: ErrorCallback): void**. + + The sample code is as follows: + + ``` + PhotoOutput.on('error', (BusinessError) => { + + }) + ``` + +45. Changed the **on(type:'error') callback** type in VideoOutput, from **ErrorCallback** to **ErrorCallback**. Therefore, the original API **on(type: 'error', callback: ErrorCallback): void** is changed to **on(type: 'error', callback: ErrorCallback): void**. + + The sample code is as follows: + + ``` + VideoOutput.on('error', (BusinessError) => { + + }) + ``` + +46. Changed the **on(type:'error') callback** type in MetadataOutput, from **ErrorCallback** to **ErrorCallback**. Therefore, the original API **on(type: 'error', callback: ErrorCallback): void** is changed to **on(type: 'error', callback: ErrorCallback): void**. + + The sample code is as follows: + + ``` + MetadataOutput.on('error', (BusinessError) => { + + }) + ``` \ No newline at end of file diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelog-resourceschedule.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelog-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..48da92c6fc824d0d4f799c21bf28906a1a784040 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelog-resourceschedule.md @@ -0,0 +1,111 @@ +# Resource Scheduler Subsystem ChangeLog + +## cl.resourceschedule.backgroundTaskManager +Rectified the original APIs of **backgroundTaskManager** of the resource scheduler subsystem. All APIs of API version 9 in the **@ohos.backgroundTaskManager.d.ts** file are deleted, and the APIs of API version 9 in the **@ohos.resourceschedule.backgroundTaskManager.d.ts** file are used. The new APIs in API version 9 comply with the error code specifications. + +**Change Impacts** + +If your application is developed based on the SDK versions of OpenHarmony 3.2.10.5 and later, adapt to the modules and APIs in API version 9 and the pattern for returning error codes. Otherwise, the service logic will be affected. + +**Key API/Component Changes** + +The following methods, attributes, enums, and constants are changed in API version 9 and later versions. All the APIs in the **@ohos.backgroundTaskManager.d.ts** file are migrated to the **@ohos.resourceschedule.backgroundTaskManager.d.ts** file. + +| Class| API Type| Declaration| Description| +| -- | -- | -- | -- | +| backgroundTaskManager | method | function resetAllEfficiencyResources(): void; | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function applyEfficiencyResources(request: EfficiencyResourcesRequest): bool; | Changed in API version 9 to **function applyEfficiencyResources(request: EfficiencyResourcesRequest): void;** and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | export enum ResourceType | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | CPU = 1 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | COMMON_EVENT = 1 << 1 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | TIMER = 1 << 2 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | WORK_SCHEDULER = 1 << 3 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | BLUETOOTH = 1 << 4 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | GPS = 1 << 5 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | AUDIO = 1 << 6 | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | interface | export interface EfficiencyResourcesRequest | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | reason: string | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | isProcess?: bool | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | isPersist?: bool | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | timeOut: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | isApply: bool | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | resourceTypes: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| + + +**Adaptation Guide** + +Import the **backgroundTaskManager** module. +``` +import bundle form '@ohos.resourceschedule.backgroundTaskManager' +``` +Exception handling also needs to be adapted. For details, see the [backgroundTaskManager API reference](../../../application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md). + +## c2.resourceschedule.workScheduler +Rectified the original APIs of **workScheduler** of the resource scheduler subsystem. All APIs of API version 9 in the **@ohos.workScheduler.d.ts** file are deleted, and the APIs of API version 9 in the **@ohos.resourceschedule.workScheduler.d.ts** file are used. The new APIs in API version 9 comply with the error code specifications. + +**Change Impacts** + +If your application is developed based on the SDK versions of OpenHarmony 3.2.10.5 and later, adapt to the modules and APIs in API version 9 and the pattern for returning error codes. Otherwise, the service logic will be affected. + +**Key API/Component Changes** + +The following methods, attributes, enums, and constants are changed in API version 9 and later versions. The **@ohos.workScheduler.d.ts** file is deleted, and all the APIs in it are moved to the **@ohos.resourceschedule.workScheduler.d.ts** file. + +| Class| API Type| Declaration| Change Type| +| -- | -- | -- | -- | +| workScheduler | namespace | declare namespace workScheduler | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | interface | export interface WorkInfo | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | parameters?: {[key: string]: any} | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | idleWaitTime?: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | isDeepIdle?: boolean | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | repeatCount?: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | isRepeat?: boolean | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | repeatCycleTime?: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | storageRequest?: StorageRequest | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | batteryStatus?: BatteryStatus | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | batteryLevel?: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | chargerType?: ChargingType | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | isCharging?: boolean | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | networkType?: NetworkType | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | isPersisted?: boolean | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | abilityName: string | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | bundleName: string | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.WorkInfo | field | workId: number | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function isLastWorkTimeOut(workId: number): Promise; | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function isLastWorkTimeOut(workId: number, callback: AsyncCallback): boolean; | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function stopAndClearWorks(): boolean; | Changed in API version 8 to **function stopAndClearWorks(): boolean;** and moved to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function obtainAllWorks(): Promise>; | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function obtainAllWorks(callback: AsyncCallback): Array; | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function getWorkStatus(workId: number): Promise; | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function getWorkStatus(workId: number, callback: AsyncCallback): void; | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function stopWork(work: WorkInfo, needCancel?: boolean): boolean; | Changed in API version 8 to **function stopWork(work: WorkInfo, needCancel?: boolean): void;** and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler | method | function startWork(work: WorkInfo): boolean; | Changed in API version 9 to **function startWork(work: WorkInfo): void;** and moved to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | export enum NetworkType | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.NetworkType | enum | NETWORK_TYPE_ANY = 0 | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.NetworkType | enum | NETWORK_TYPE_MOBILE | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.NetworkType | enum | NETWORK_TYPE_WIFI | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.NetworkType | enum | NETWORK_TYPE_BLUETOOTH | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.NetworkType | enum | NETWORK_TYPE_WIFI_P2P | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.NetworkType | enum | NETWORK_TYPE_ETHERNET | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.ChargingType | enum | export enum ChargingType | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_ANY = 0 | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_AC | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_USB | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_WIRELESS | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | export enum BatteryStatus | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | BATTERY_STATUS_LOW = 0 | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | BATTERY_STATUS_OKAY | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | BATTERY_STATUS_LOW_OR_OKAY | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.StorageRequest | enum | export enum StorageRequest | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | STORAGE_LEVEL_LOW = 0 | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | STORAGE_LEVEL_OKAY | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| +| workScheduler.BatteryStatus | enum | STORAGE_LEVEL_LOW_OR_OKAY | Deleted in API version 9 and moved to the **ohos.resourceschedule.workScheduler.d.ts** file.| + + +**Adaptation Guide** + +Import the **workScheduler** module. +``` +import bundle form '@ohos.resourceschedule.workScheduler' +``` +Exception handling also needs to be adapted. For details, see the [workScheduler API reference](../../../application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md). diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-bundlemanager.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..5836d257282f062f61f1ff54f4b6c3c8322cf04a --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-bundlemanager.md @@ -0,0 +1,106 @@ +# Bundle Manager Subsystem ChangeLog + +## cl.bundlemanager.1 Changed Underlying Capability by Adding Verification to bundle-name in the Signing Certification During Application Installation + +During application installation, the **bundle-name** field in the [signing certificate profile](../../../application-dev/security/app-provision-structure.md) is verified against the bundle name of the application. + +If the value of **bundle-name** is different from the value of **bundleName** in the application configuration file, the installation fails and the following error information is displayed: +``` +error: verify signature failed. +``` + +**Change Impacts** + +For applications using system images of 3.2.10.5 or later, if the **bundle-name** field in the signing certificate profile is different from the bundle name of the application, application installation fails. This change has no impact on applications using system images earlier than 3.2.10.5. + +**Key API/Component Changes** + +No API or component change is involved. + +**Adaptation Guide** + +If "error: verify signature failed" is displayed, change **bundle-name** in the signing certificate profile to the bundle name of the application, generate a new signing certificate (with the file name extension .p7b), and sign the application again. For details about how to use the signing tool and generate a signing certificate, see [hapsigner Guide](../../../application-dev/security/hapsigntool-guidelines.md). + +## cl.bundlemanager.2 Changed Underlying Capability by Adding Control over Applications Without Entry Icons + +If no entry icon is configured for an application that has not requested the **AllowHideDesktopIcon** privilege, a default icon is displayed on the home screen. Any click on the icon redirects to the application details page. An application is determined to have no entry icon in either of the following scenarios: +1. The **abilities** field is not configured for the application. +2. The **abilities** field is configured for the application, but the **skills** field under the ability of any page type does not contain both **action.system.home** and **entity.system.home**, as follows: + ```json + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + ``` +If the application installation mode is **hdc_std install** or **bm install**, a default icon is displayed for the application on the home screen. + +If your application does not need an icon to be displayed on the home screen, request the **AllowHideDesktopIcon** privilege and configure it in the signing certificate or trustlist (**install_list_capability.json**). For details, see [Application Privilege Configuration Guide](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md). + +If your application needs an icon to be displayed on the home screen, select an ability from **abilities** and configure its **skills** field to contain both **action.system.home** and **entity.system.home**. + +**Change Impacts** + +For applications using system images of 3.2.10.5 and later versions, if no entry icon is configured for an application, the default icon is displayed on the home screen when the application is installed using the CLI. This change has no impact on applications using system images earlier than 3.2.10.5. + +**Key API/Component Changes** + +No API or component change is involved. + +**Adaptation Guide** + +If your application does not need an icon to be displayed on the home screen, request the **AllowHideDesktopIcon** privilege and configure it in the signing certificate or trustlist (**install_list_capability.json**). For details, see [Application Privilege Configuration Guide](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md). + +If your application needs an icon to be displayed on the home screen, select an ability from **abilities** and configure its **skills** field to contain both **action.system.home** and **entity.system.home**. + +## cl.bundlemanager.3 Changed Underlying Capability by Restricting AllowAppUsePrivilegeExtension, AllowAppMultiProcess, and AllowFormVisibleNotify from Being Configured in the Signing Certificate + +The **AllowAppUsePrivilegeExtension**, **AllowAppMultiProcess**, and **AllowFormVisibleNotify** privileges can no longer be configured in the signing certificate. They can be requested only through the trustlist (**install_list_capability.json**). If your application requests these privileges in the signing certificate, the installation may fail or the privileges may be invalid. + +If the following error information is displayed, adapt to the new privilege configuration method. For details, see [Application Privilege Configuration Guide](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md). +``` +error: install parse profile prop check error. +``` + +For the XTS or local debugging demo, if the **install_list_capability.json** file on the development board cannot be modified, you can change the bundle name of the application to start with **com.acts.** and request the privileges in the signing certificate. + +The **AllowAppUsePrivilegeExtension** privilege is requested by configuring it under the **extensionAbilities** field, with the **type** attribute set to **dataShare** or **service**, in the application configuration file. If this privilege is not configured, the installation fails. + +**Change Impacts** + +For applications using system images of 3.2.10.5 or later, if the required privileges are not requested using the trustlist (**install_list_capability.json**), application installation may fail. This change has no impact on applications using system images earlier than 3.2.10.5. + +**Key API/Component Changes** + +No API or component change is involved. + +**Adaptation Guide** + +If the following error information is displayed, adapt to the new privilege configuration method. For details, see [Application Privilege Configuration Guide](../../../device-dev/subsystems/subsys-app-privilege-config-guide.md). + +``` +error: install parse profile prop check error. +``` + +For the XTS or local debugging demo, if the **install_list_capability.json** file on the development board cannot be modified, you can change the bundle name of the application to start with **com.acts.** and request the privileges in the signing certificate. + +## cl.bundlemanager.4 Changed Underlying Capability by Not Decompressing the HAP During HAP Installation + +The HAP will no longer be decompressed during installation. After the installation is complete, only the HAP file exists in the installation directory. As a result, the application must use the standard resource management interface, rather than a combined path, to access a resource file. + +**Change Impacts** + +If the application uses a combined path to access a resource file, the access fails. It must use the resource management interface. + +**Key API/Component Changes** + +No API or component change is involved. + +**Adaptation Guide** + +The resource management subsystem provides the JS interface for accessing resource files. Reference: [Accessing Resource Files](../../../application-dev/reference/apis/js-apis-resource-manager.md#getrawfilecontent9) \ No newline at end of file diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md new file mode 100644 index 0000000000000000000000000000000000000000..d67dc521bfdb10aff1beee5453a9381ef39d4dc6 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md @@ -0,0 +1,145 @@ +# File Management Subsystem ChangeLog + +## cl.filemanagement.1 Changed environment + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **environment** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **environment** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **environment** was imported using **@ohos.environment**: + +```js +import environment from '@ohos.environment'; +``` + +But now, **environment** is imported using **@ohos.file.environment**: + +```js +import environment from '@ohos.file.environment'; +``` + +## cl.filemanagement.2 Changed securityLabel + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **securityLabel** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **securityLabel** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **securityLabel** was imported using **@ohos.securityLabel**: + +```js +import securityLabel from '@ohos.securityLabel'; +``` + +But now, **securityLabel** is imported using **@ohos.file.securityLabel**: + +```js +import securityLabel from '@ohos.file.securityLabel'; +``` + +## cl.filemanagement.3 Changed fs + +The **ino** attribute type of the **Stat** API under the **fs** module is changed. + +**Change Impacts** + +The **ino** attribute type is changed from number to BigInt, to adapt to the inode range of all types of files in the file system. + +**Key API/Component Changes** + +The type of the **ino** attribute of the **Stat** API is changed from number to BigInt. + +## cl.filemanagement.4 Changed fileAccess + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileAccess** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **fileAccess** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **fileAccess** was imported using **@ohos.data.fileAccess**: + +```js +import fileAccess from '@ohos.data.fileAccess'; +``` + +But now, **fileAccess** is imported using **@ohos.file.fileAccess**: + +```js +import fileAccess from '@ohos.file.fileAccess'; +``` + +## cl.filemanagement.5 Changed fileExtensionInfo + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **fileExtensionInfo** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **fileExtensionInfo** was imported using **@ohos.fileExtensionInfo**: + +```js +import fileExtensionInfo from '@ohos.fileExtensionInfo'; +``` + +But now, **fileExtensionInfo** is imported using **@ohos.file.fileExtensionInfo**: + +```js +import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; +``` + +## cl.filemanagement.6 Changed storageStatistics + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **storageStatistics** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **storageStatistics** was imported using **@ohos.storageStatistics**: + +```js +import storageStatistics from '@ohos.storageStatistics'; +``` + +But now, **storageStatistics** is imported using **@ohos.file.storageStatistics**: + +```js +import storageStatistics from '@ohos.file.storageStatistics'; +``` + +## cl.filemanagement.7 Changed volumeManager + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **volumeManager** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **volumeManager** was imported using **@ohos.volumeManager**: + +```js +import volumeManager from '@ohos.volumeManager'; +``` + +But now, **volumeManager** is imported using **@ohos.file.volumeManager**: + +```js +import volumeManager from '@ohos.file.volumeManager'; +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-window.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-window.md new file mode 100644 index 0000000000000000000000000000000000000000..b3514e82cca44c154a70b999e6cc62a54d47ff92 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-window.md @@ -0,0 +1,63 @@ +# Window Subsystem ChangeLog + +## cl.window.1 Change of Window Stage Lifecycle Listener Types + +Changed the enumerated listener types of the window stage lifecycle in version 3.2.10.5 and later. + +**Change Impacts** + +Application lifecycle listeners developed using **FOREGROUND** and **BACKGROUND** in versions earlier than 3.2.10.5 will be invalidated in version 3.2.10.5 and later. + +**Key API/Component Changes** + +## WindowStageEventType9+ + +Before change + +| Name | Value | Description | +| ---------- | ---- | ---------- | +| FOREGROUND | 1 | The window stage is running in the foreground.| +| BACKGROUND | 4 | The window stage is running in the background.| + +After change +| Name | Value | Description | +| ------ | ---- | ---------- | +| SHOWN | 1 | The window stage is running in the foreground.| +| HIDDEN | 4 | The window stage is running in the background.| + +**Adaptation Guide** + +When registering lifecycle listeners, change the foreground and background event types to **SHOWN** and **HIDDEN**, respectively. + +``` +import Ability from '@ohos.application.Ability'; + +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + try { + windowStage.on('windowStageEvent', (stageEventType) => { + switch (stageEventType) { + case window.WindowStageEventType.SHOWN: + console.log("windowStage shown"); + break; + case window.WindowStageEventType.ACTIVE: + console.log("windowStage active"); + break; + case window.WindowStageEventType.INACTIVE: + console.log("windowStage inActive"); + break; + case window.WindowStageEventType.HIDDEN: + console.log("windowStage hidden"); + break; + default: + break; + } + } ) + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; + } +}; +``` diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md b/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md index 8643663fa245f33dcf5866a767327ff83b2ffb92..24146a66cd76375d49e1bad764b474bf59317a20 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-bundlemanager.md @@ -273,6 +273,7 @@ Use the **HapModuleInfo** structure of API version 9 for modules imported for bu ## cl.bundlemanager.7 ModuleInfo Structure Changes The original **bundle/hapModuleInfo.d.ts** and **moduleInfo.d.ts** fields in the bundle manager are deprecated, and the files are changed to [bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts), involving field changes. + The **ModuleInfo** structure is deprecated and replaced by **HapModuleInfo** in [bundleManager/hapModuleInfo.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/bundleManager/hapModuleInfo.d.ts). **Change Impacts** @@ -759,3 +760,5 @@ The import module does not change. The new API is directly used to adapt excepti ``` import zlib form '@ohos.zlib' ``` + + \ No newline at end of file diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-resourceschedule.md b/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-resourceschedule.md new file mode 100644 index 0000000000000000000000000000000000000000..f109d28cec55335f3422fd063532aad1cafe310f --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.8.2/changelog-resourceschedule.md @@ -0,0 +1,318 @@ +# Resource Scheduler Subsystem ChangeLog + +## cl.resourceschedule.backgroundTaskManager + +Rectified original APIs of **backgroundTaskManager** of the resource scheduler subsystem. All APIs in API version 8 and earlier versions are deprecated, and original APIs in API version 9 are deleted. New APIs in API version 9 need to be used. The new APIs in API version 9 comply with the error code specifications. + +**Change Impacts** + +The application developed based on the SDK versions of OpenHarmony 3.2.8.2 and later needs to adapt the modules and APIs in API version 9 and their methods for returning API error information. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + +The following methods, attributes, enumerations, and constants are changed in API version 9 and later versions. The **@ohos.backgroundTaskManager.d.ts** file is deprecated and related APIs are migrated to the newly added **@ohos.resourceschedule.backgroundTaskManager.d.ts** file. + +| Class| API Type| Declaration| Description| +| -- | -- | -- | -- | +| backgroundTaskManager | namespace | declare namespace backgroundTaskManager | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function resetAllEfficiencyResources(): void; | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function applyEfficiencyResources(request: EfficiencyResourcesRequest): bool; | This API is changed in API version 9 to **function applyEfficiencyResources(request: EfficiencyResourcesRequest): void;** and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function stopBackgroundRunning(context: Context): Promise; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function stopBackgroundRunning(context: Context, callback: AsyncCallback): void; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function requestSuspendDelay(reason: string, callback: Callback): DelaySuspendInfo; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function getRemainingDelayTime(requestId: number): Promise; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function getRemainingDelayTime(requestId: number, callback: AsyncCallback): void; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager | method | function cancelSuspendDelay(requestId: number): void; | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | export enum BackgroundMode | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | DATA_TRANSFER = 1 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | AUDIO_PLAYBACK = 2 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | AUDIO_RECORDING = 3 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | LOCATION = 4 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | BLUETOOTH_INTERACTION = 5 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | MULTI_DEVICE_CONNECTION = 6 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | WIFI_INTERACTION = 7 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | VOIP = 8 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.BackgroundMode | enum | TASK_KEEPING = 9 | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.DelaySuspendInfo | interface | interface DelaySuspendInfo | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.DelaySuspendInfo | field | requestId: number | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.DelaySuspendInfo | field | actualDelayTime: number | This API is deprecated in API version 9 and later versions and is migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | export enum ResourceType | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | CPU = 1 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | COMMON_EVENT = 1 << 1 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | TIMER = 1 << 2 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | WORK_SCHEDULER = 1 << 3 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | BLUETOOTH = 1 << 4 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | GPS = 1 << 5 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.ResourceType | enum | AUDIO = 1 << 6 | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | interface | export interface EfficiencyResourcesRequest | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | reason: string | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | isProcess?: bool | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | isPersist?: bool | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | timeOut: number | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | isApply: bool | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| +| backgroundTaskManager.EfficiencyResourcesRequest | field | resourceTypes: number | This API is changed in API version 9 and migrated to the **ohos.resourceschedule.backgroundTaskManager.d.ts** file.| + + +**Adaptation Guide**
+ +Import the **backgroundTaskManager** module. +``` +import bundle form '@ohos.resourceschedule.backgroundTaskManager' +``` +Exception handling also needs to be adapted. For details, see the [backgroundTaskManager API reference](../../../application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md). + +## c2.resourceschedule.usageStatistics + +Rectified original APIs of **deviceUsageStatistics** of the resource scheduler subsystem. All APIs in API version 8 and earlier versions are deprecated, and original APIs in API version 9 are deleted. New APIs in API version 9 need to be used. The new APIs in API version 9 comply with the error code specifications. + +**Change Impacts** + +The application developed based on the SDK versions of OpenHarmony 3.2.8.2 and later needs to adapt the modules and APIs in API version 9 and their methods for returning API error information. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + +The following methods, attributes, enumerations, and constants are changed in API version 9 and later versions. The **@ohos.bundleState.d.ts** file is deprecated, the **@ohos.resourceschedule.usageStatistics.d.ts** file is added, and the class name is changed from **bundleState** to **usageStatistics**. + +| Class | API Type | Method/Attribute/Enumeration/Constant | Change Type | +| ----------------------------------------- | --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| bundleState | method | function isIdleState(bundleName: string, callback: AsyncCallback): void; | Deprecated and migrated to **usageStatistics.isIdleState** | +| bundleState | method | function isIdleState(bundleName: string): Promise; | Deprecated and migrated to **usageStatistics.isIdleState** | +| bundleState | method | function queryAppUsagePriorityGroup(callback: AsyncCallback): void; | Deprecated and changed to **function queryAppGroup(callback: AsyncCallback): void;**| +| bundleState | method | function queryAppUsagePriorityGroup(): Promise; | Deprecated and changed to **function queryAppGroup(): Promise;** | +| bundleState | method | function queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback): void; | Deprecated and changed to **function queryBundleStatsInfos(begin: number, end: number, callback: AsyncCallback): void;**| +| bundleState | method | function queryBundleStateInfos(begin: number, end: number): Promise; | Deprecated and changed to **function queryBundleStatsInfos(begin: number, end: number): Promise;**| +| bundleState | method | function queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise>; | Deprecated and changed to **function queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise>;**| +| bundleState | method | function queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback>): void; | Deprecated and changed to **function queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback>): void;**| +| bundleState | method | function queryBundleActiveStates(begin: number, end: number): Promise>; | Deprecated and changed to **function queryBundleEvents(begin: number, end: number): Promise>;**| +| bundleState | method | function queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback>): void; | Deprecated and changed to **function queryBundleEvents(begin: number, end: number, callback: AsyncCallback>): void;**| +| bundleState | method | function queryCurrentBundleActiveStates(begin: number, end: number): Promise>; | Deprecated and changed to **function queryCurrentBundleEvents(begin: number, end: number): Promise>;**| +| bundleState | method | function queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback>): void; | Deprecated and changed to **function queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback>): void;**| +| bundleState | method | function getRecentlyUsedModules(maxNum?: number): Promise>; | Deprecated and changed to the following two APIs: **function QueryModuleUsageRecords(maxNum: number): Promise>;** and **function QueryModuleUsageRecords(): Promise>;**| +| bundleState | method | function getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback>): void; | Deprecated and changed to the following two APIs: **function QueryModuleUsageRecords(maxNum: number, callback: AsyncCallback>): void;** and **function QueryModuleUsageRecords(callback: AsyncCallback>): void;**| +| bundleState | method | function queryAppUsagePriorityGroup(bundleName? : string): Promise; | Deprecated and changed to **function queryAppGroup(bundleName: string): Promise;**| +| bundleState | method | function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback): void; | Deprecated and changed to **function queryAppGroup(bundleName: string, callback: AsyncCallback): void;**| +| bundleState | method | function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void; | Deprecated and changed to **function setAppGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void;**| +| bundleState | method | function setBundleGroup(bundleName: string, newGroup: GroupType): Promise; | Deprecated and changed to **function setAppGroup(bundleName: string, newGroup: GroupType): Promise;**| +| bundleState | method | function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void; | Deprecated and changed to **function registerAppGroupCallBack(callback: Callback, callback: AsyncCallback): void;**| +| bundleState | method | function registerGroupCallBack(callback: Callback): Promise; | Deprecated and changed to **function registerAppGroupCallBack(callback: Callback): Promise;**| +| bundleState | method | function unRegisterGroupCallBack(callback: AsyncCallback): void; | Deprecated and changed to **function unregisterAppGroupCallBack(): Promise;**| +| bundleState | method | function unRegisterGroupCallBack(): Promise; | Deprecated and changed to **function unregisterAppGroupCallBack(): Promise;**| +| bundleState | method | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback>): void; | Changed to **function queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback>): void;**| +| bundleState | method | function queryBundleActiveEventStates(begin: number, end: number): Promise>; | Changed in API version 9 and later versions to **function queryDeviceEventStats(begin: number, end: number): Promise>;**| +| bundleState | method | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback>): void; | Changed in API version 9 and later versions to **function queryNotificationEventStats(begin: number, end: number, callback: AsyncCallback>): void;**| +| bundleState | method | function queryAppNotificationNumber(begin: number, end: number): Promise>; | Changed in API version 9 and later versions to **function queryNotificationEventStats(begin: number, end: number): Promise>;**| +| bundleState.BundleActiveGroupCallbackInfo | interface | interface BundleActiveGroupCallbackInfo | Changed to **usageStatistics.AppGroupCallbackInfo** | +| bundleState.BundleActiveGroupCallbackInfo | field | bundleName: string | Changed and migrated to **usageStatistics.AppGroupCallbackInfo** | +| bundleState.BundleActiveGroupCallbackInfo | field | changeReason: number | Changed and migrated to **usageStatistics.AppGroupCallbackInfo** | +| bundleState.BundleActiveGroupCallbackInfo | field | userId: number | Changed and migrated to **usageStatistics.AppGroupCallbackInfo** | +| bundleState.BundleActiveGroupCallbackInfo | field | appUsageNewGroup: number | Deprecated and changed to **appNewGroup** | +| bundleState.BundleActiveGroupCallbackInfo | field | appUsageOldGroup: number | Deprecated and changed to **appOldGroup** | +| bundleState.BundleActiveEventState | interface | interface BundleActiveEventState | Deprecated and changed to **usageStatistics.DeviceEventStats** | +| bundleState.BundleActiveEventState | field | count: number | Changed and migrated to **usageStatistics.DeviceEventStats** | +| bundleState.BundleActiveEventState | field | eventId: number | Changed and migrated to **usageStatistics.DeviceEventStats** | +| bundleState.BundleActiveEventState | field | name: string | Changed and migrated to **usageStatistics.DeviceEventStats** | +| bundleState.BundleActiveModuleInfo | interface | interface BundleActiveModuleInfo | Changed in API version 9 and later versions to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | formRecords: Array | Changed to **formRecords: Array** | +| bundleState.BundleActiveModuleInfo | field | lastModuleUsedTime: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | launchedCount: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | abilityIconId?: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | abilityDescriptionId?: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | abilityLableId?: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | descriptionId?: number; | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | labelId?: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | appLabelId?: number | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | abilityName?: string | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | moduleName: string | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | bundleName: string | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.BundleActiveModuleInfo | field | deviceId?: string | Changed and migrated to **usageStatistics.HapModuleInfo** | +| bundleState.GroupType | enum | enum GroupType | Changed and migrated to **usageStatistics.GroupType** | +| bundleState.GroupType | enum | ACTIVE_GROUP_ALIVE | Deprecated and changed to **ALIVE_GROUP** | +| bundleState.GroupType | enum | ACTIVE_GROUP_DAILY | Deprecated and changed to **DAILY_GROUP** | +| bundleState.GroupType | enum | ACTIVE_GROUP_FIXED | Deprecated and changed to **FIXED_GROUP** | +| bundleState.GroupType | enum | ACTIVE_GROUP_RARE | Deprecated and changed to **RARE_GROUP** | +| bundleState.GroupType | enum | ACTIVE_GROUP_LIMIT | Deprecated and changed to **LIMITED_GROUP** | +| bundleState.GroupType | enum | ACTIVE_GROUP_NEVER | Deprecated and changed to **NEVER_GROUP** | +| bundleState.IntervalType | enum | enum IntervalType | Deprecated and migrated to **usageStatistics.IntervalType** | +| bundleState.IntervalType | enum | BY_OPTIMIZED | Deprecated and migrated to **usageStatistics.IntervalType** | +| bundleState.IntervalType | enum | BY_DAILY | Deprecated and migrated to **usageStatistics.IntervalType** | +| bundleState.IntervalType | enum | BY_WEEKLY | Deprecated and migrated to **usageStatistics.IntervalType** | +| bundleState.IntervalType | enum | BY_MONTHLY | Deprecated and migrated to **usageStatistics.IntervalType** | +| bundleState.IntervalType | enum | BY_ANNUALLY | Deprecated and migrated to **usageStatistics.IntervalType** | +| bundleState.BundleActiveInfoResponse | interface | interface BundleActiveInfoResponse | Deprecated and changed to **usageStatistics.BundleStatsMap** | +| bundleState.BundleActiveState | interface | interface BundleActiveState | Deprecated and changed to **usageStatistics.BundleEvents** | +| bundleState.BundleActiveState | field | stateType?: number | Deprecated and changed to **eventId** | +| bundleState.BundleActiveState | field | stateOccurredTime?: number | Deprecated and changed to **eventOccurredTime** | +| bundleState.BundleActiveState | field | nameOfClass?: string | Deprecated and migrated to **usageStatistics.BundleEvents** | +| bundleState.BundleActiveState | field | indexOfLink?: string | Deprecated and migrated to **usageStatistics.BundleEvents** | +| bundleState.BundleActiveState | field | bundleName?: string | Deprecated and migrated to **usageStatistics.BundleEvents** | +| bundleState.BundleActiveState | field | appUsagePriorityGroup?: number | Deprecated and changed to **appGroup** | +| bundleState.BundleStateInfo | interface | interface BundleStateInfo | Deprecated and changed to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | method | merge(toMerge: BundleStateInfo): void | Deprecated | +| bundleState.BundleStateInfo | field | infosEndTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | infosBeginTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | fgAbilityPrevAccessTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | fgAbilityAccessTotalTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | bundleName?: string | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | abilitySeenTotalTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | abilityPrevSeenTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | abilityPrevAccessTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | abilityInFgTotalTime?: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState.BundleStateInfo | field | id: number | Deprecated and migrated to **usageStatistics.BundleStatsInfo** | +| bundleState | namespace | declare namespace bundleState | Deprecated and changed to **usageStatistics**, and migrated to **ohos.resourceschedule.usageStatistics.d.ts**| + + +**Adaptation Guide**
+ +Import the **usageStatistics** module. +``` +import bundle form '@ohos.resourceschedule.usageStatistics' +``` +Exception handling also needs to be adapted. For details, see the [usageStatistics API reference](../../../application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md). + + +## c3.resourceschedule.workScheduler + +Rectified original APIs of **workScheduler** of the resource scheduler subsystem. The original APIs in API version 9 are changed to new APIs in API version 9. The new APIs in API version 9 comply with the error code specifications. + +**Change Impacts** + +The application developed based on the SDK versions of OpenHarmony 3.2.8.2 and later needs to adapt the modules and APIs in API version 9 and their methods for returning API error information. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + +The following methods, attributes, enumerations, and constants are changed in API version 9 and later versions. The **@ohos.workScheduler.d.ts** file is deprecated and related APIs are migrated to the newly added **@ohos.resourceschedule.workScheduler.d.ts** file. + +| Class| API Type| Declaration| Change Type| +| -- | -- | -- | -- | +| workScheduler | namespace | declare namespace workScheduler | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | interface | export interface WorkInfo | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | parameters?: {[key: string]: any} | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | idleWaitTime?: number | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | isDeepIdle?: boolean | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | repeatCount?: number | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | isRepeat?: boolean | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | repeatCycleTime?: number | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | storageRequest?: StorageRequest | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | batteryStatus?: BatteryStatus | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | batteryLevel?: number | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | chargerType?: ChargingType | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | isCharging?: boolean | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | networkType?: NetworkType | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | isPersisted?: boolean | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | abilityName: string | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | bundleName: string | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.WorkInfo | field | workId: number | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function isLastWorkTimeOut(workId: number): Promise; | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function isLastWorkTimeOut(workId: number, callback: AsyncCallback): boolean; | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function stopAndClearWorks(): boolean; | Changed in API version 8 to **function stopAndClearWorks(): boolean;** and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function obtainAllWorks(): Promise>; | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function obtainAllWorks(callback: AsyncCallback): Array; | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function getWorkStatus(workId: number): Promise; | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function getWorkStatus(workId: number, callback: AsyncCallback): void; | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function stopWork(work: WorkInfo, needCancel?: boolean): boolean; | Changed in API version 8 to **function stopWork(work: WorkInfo, needCancel?: boolean): void;** and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler | method | function startWork(work: WorkInfo): boolean; | Changed in API version 9 to **function startWork(work: WorkInfo): void;** and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | export enum NetworkType | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | NETWORK_TYPE_ANY = 0 | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | NETWORK_TYPE_MOBILE | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | NETWORK_TYPE_WIFI | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | NETWORK_TYPE_BLUETOOTH | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | NETWORK_TYPE_WIFI_P2P | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.NetworkType | enum | NETWORK_TYPE_ETHERNET | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.ChargingType | enum | export enum ChargingType | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_ANY = 0 | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_AC | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_USB | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.ChargingType | enum | CHARGING_PLUGGED_WIRELESS | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | export enum BatteryStatus | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | BATTERY_STATUS_LOW = 0 | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | BATTERY_STATUS_OKAY | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | BATTERY_STATUS_LOW_OR_OKAY | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.StorageRequest | enum | export enum StorageRequest | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | STORAGE_LEVEL_LOW = 0 | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | STORAGE_LEVEL_OKAY | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| +| workScheduler.BatteryStatus | enum | STORAGE_LEVEL_LOW_OR_OKAY | Changed in API version 9 and migrated to the **ohos.resourceschedule.workScheduler.d.ts** file| + + +**Adaptation Guide**
+ +Import the **workScheduler** module. +``` +import bundle form '@ohos.resourceschedule.workScheduler' +``` +Exception handling also needs to be adapted. For details, see the [workScheduler API reference](../../../application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md). + + +## c4.resourceschedule.reminderAgent + +Rectified original APIs of **reminderAgent** of the resource scheduler subsystem. All APIs in API version 8 and earlier versions are deprecated, and original APIs in API version 9 are deleted. New APIs in API version 9 need to be used. The new APIs in API version 9 comply with the error code specifications. + +**Change Impacts** + +The application developed based on the SDK versions of OpenHarmony 3.2.8.2 and later needs to adapt the modules and APIs in API version 9 and their methods for returning API error information. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + +The following methods, attributes, enumerations, and constants are changed in API version 9 and later versions. The **@ohos.reminderAgent.d.ts** file is deprecated, the **@ohos.reminderAgentManager.d.ts** file is added, and the class name is changed from **reminderAgent** to **reminderAgentManager**. + +| Class | API Type | Method/Attribute/Enumeration/Constant | Change Type | +| --------------------- | ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| reminderAgent | method | publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | publishReminder(reminderReq: ReminderRequest): Promise; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | cancelReminder(reminderId: number, callback: AsyncCallback): void; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | cancelReminder(reminderId: number): Promise; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | getValidReminders(callback: AsyncCallback>): void; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | getValidReminders(): Promise>; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | cancelAllReminders(callback: AsyncCallback): void; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | cancelAllReminders(): Promise; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | addNotificationSlot(slot: NotificationSlot): Promise; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent | method | removeNotificationSlot(slotType: notification.SlotType): Promise; | Deprecated and migrated to **reminderAgentManager**| +| reminderAgent.ActionButtonType | enum | ACTION_BUTTON_TYPE_CLOSE | Deprecated and migrated to **reminderAgentManager.ActionButtonType**| +| reminderAgent.ActionButtonType | enum | ACTION_BUTTON_TYPE_SNOOZE | Deprecated and migrated to **reminderAgentManager.ActionButtonType**| +| reminderAgent.ReminderType | enum | REMINDER_TYPE_TIMER | Deprecated and migrated to **reminderAgentManager.ReminderType**| +| reminderAgent.ReminderType | enum | REMINDER_TYPE_CALENDAR | Deprecated and migrated to **reminderAgentManager.ReminderType**| +| reminderAgent.ReminderType | enum | REMINDER_TYPE_CALENDAR | Deprecated and migrated to **reminderAgentManager.ReminderType**| +| reminderAgent.ActionButton | field | title:string | Deprecated and migrated to **reminderAgentManager.ActionButton**| +| reminderAgent.ActionButton | field | type:ActionButtonType | Deprecated and migrated to **reminderAgentManager.ActionButton**| +| reminderAgent.WantAgent | field | pkgName:string | Deprecated and migrated to **reminderAgentManager.WantAgent**| +| reminderAgent.WantAgent | field | abilityName:string | Deprecated and migrated to **reminderAgentManager.WantAgent**| +| reminderAgent.MaxScreenWantAgent | field | pkgName:string | Deprecated and migrated to **reminderAgentManager.MaxScreenWantAgent**| +| reminderAgent.MaxScreenWantAgent | field | abilityName:string | Deprecated and migrated to **reminderAgentManager.MaxScreenWantAgent**| +| reminderAgent.ReminderRequest | field | reminderType:ReminderType | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | actionButton?:ActionButton | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | wantAgent?:WantAgent | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | maxScreenWantAgent?:MaxScreenWantAgent | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | ringDuration?:number | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | snoozeTimes?:number | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | timeInterval?:number | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | title?:string | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | content?:string | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | expiredContent?:string | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | snoozeContent?:string | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | notificationId?:number | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequest | field | slotType?: notification.SlotType | Deprecated and migrated to **reminderAgentManager.ReminderRequest**| +| reminderAgent.ReminderRequestCalendar | field | dateTime:LocalDateTime | Deprecated and migrated to **reminderAgentManager.ReminderRequestCalendar**| +| reminderAgent.ReminderRequestCalendar | field | repeatMonths?:Array | Deprecated and migrated to **reminderAgentManager.ReminderRequestCalendar**| +| reminderAgent.ReminderRequestCalendar | field | repeatDays?:Array | Deprecated and migrated to **reminderAgentManager.ReminderRequestCalendar**| +| reminderAgent.ReminderRequestAlarm | field | hour:number | Deprecated and migrated to **reminderAgentManager.ReminderRequestAlarm**| +| reminderAgent.ReminderRequestAlarm | field | minute:number | Deprecated and migrated to **reminderAgentManager.ReminderRequestAlarm**| +| reminderAgent.ReminderRequestAlarm | field | daysOfWeek?:Array | Deprecated and migrated to **reminderAgentManager.ReminderRequestAlarm**| +| reminderAgent.ReminderRequestTimer | field | triggerTimeInSeconds:number | Deprecated and migrated to **reminderAgentManager.ReminderRequestTimer**| +| reminderAgent.LocalDateTime | field | year:number | Deprecated and migrated to **reminderAgentManager.LocalDateTime**| +| reminderAgent.LocalDateTime | field | month:number | Deprecated and migrated to **reminderAgentManager.LocalDateTime**| +| reminderAgent.LocalDateTime | field | day:number | Deprecated and migrated to **reminderAgentManager.LocalDateTime**| +| reminderAgent.LocalDateTime | field | hour:number | Deprecated and migrated to **reminderAgentManager.LocalDateTime**| +| reminderAgent.LocalDateTime | field | minute:number | Deprecated and migrated to **reminderAgentManager.LocalDateTime**| +| reminderAgent.LocalDateTime | field | second?:number | Deprecated and migrated to **reminderAgentManager.LocalDateTime**| + + +**Adaptation Guide**
+ +Import the **reminderAgentManager** module. +``` +import bundle form '@ohos.reminderAgentManager' +``` +Exception handling also needs to be adapted. For details, see the [reminderAgentManager API reference](../../../application-dev/reference/apis/js-apis-reminderAgentManager.md). diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.1.5/changelogs-geoLocationManager.md b/en/release-notes/changelogs/OpenHarmony_4.0.1.5/changelogs-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..610a18c426c33ef08212dfa28070f9053bd4d44e --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.1.5/changelogs-geoLocationManager.md @@ -0,0 +1,18 @@ +# Location Subsystem ChangeLog + +## cl.location.1 Deletion of the geoLocationManager.requestEnableLocation API in API Version 9 + +When the location function is disabled, your application can call the **geoLocationManager.requestEnableLocation** API to request the user to enable the location function. However, this API is seldom used, and user experience for this API is not very good because the user is not notified of the scenario in which your application uses the location information. + +Therefore, your app shows a popup, asking the user to go to the settings page and enable the location function. In addition, the popup clearly states the scenarios in which the location information will be used, improving user experience. + +**Change Impacts** + +Your application cannot use the **geoLocationManager.requestEnableLocation** API in API version 9 to request the user to enable the location function. Instead, you need to implement a popup asking the user to enable the location function for your application. + +**Key API/Component Changes** + +| Class | API Type| Declaration | Change Type | +| ------------------ | -------- | ------------------------------------------------------------ | ------------------ | +| geoLocationManager | method | function requestEnableLocation(callback: AsyncCallback<boolean>): void; | Deleted from API version 9| +| geoLocationManager | method | function requestEnableLocation(): Promise<boolean>; | Deleted from API version 9| diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-ability.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..773d4439728d3c25369d47e384120d7beb543618 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-ability.md @@ -0,0 +1,140 @@ +# Ability Subsystem ChangeLog + +## cl.ability.1 System API Usage Rule Change + +System application verification is not performed for system APIs provided by the ability when they are called. The APIs can be used by a third-party application using the full SDK, which brings security risks. Therefore, application identity verification is added to OpenHarmony 4.0.2.1 and later versions. + +**Change Impacts** + +System APIs are available to only system applications. When a third-party application tries to use a system API, the **202** error will be returned via either an exception or asynchronous callback. + +**Key API/Component Changes** + +Below are the system APIs. + +| Module | API | Error Code Return Mode| +| -------------------------------------- | ------------------------------------------------------------ | -------------- | +| @ohos.app.ability.abilityManager.d.ts | updateConfiguration(config: Configuration, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.abilityManager.d.ts | updateConfiguration(config: Configuration): Promise | Asynchronous callback | +| @ohos.app.ability.abilityManager.d.ts | getAbilityRunningInfos(): Promise> | Asynchronous callback | +| @ohos.app.ability.abilityManager.d.ts | getAbilityRunningInfos(callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.ability.abilityManager.d.ts | getExtensionRunningInfos(upperLimit: number): Promise> | Asynchronous callback | +| @ohos.app.ability.abilityManager.d.ts | getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.ability.abilityManager.d.ts | getTopAbility(): Promise | Exception | +| @ohos.app.ability.abilityManager.d.ts | getTopAbility(callback: AsyncCallback): void | Exception | +| @ohos.app.ability.appManager.d.ts | on(type: "applicationState", observer: ApplicationStateObserver): number | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | on(type: "applicationState", observer: ApplicationStateObserver, bundleNameList: Array): number | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | off(type: "applicationState", observerId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | off(type: "applicationState", observerId: number): Promise | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | getForegroundApplications(callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | getForegroundApplications(): Promise> | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | killProcessWithAccount(bundleName: string, accountId: number): Promise | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | killProcessesByBundleName(bundleName: string): Promise | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | killProcessesByBundleName(bundleName: string, callback: AsyncCallback) | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | clearUpApplicationData(bundleName: string): Promise | Asynchronous callback | +| @ohos.app.ability.appManager.d.ts | clearUpApplicationData(bundleName: string, callback: AsyncCallback) | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | on(type: "mission", listener: MissionListener): number | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | off(type: "mission", listenerId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | off(type: "mission", listenerId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getMissionInfo(deviceId: string, missionId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getMissionInfos(deviceId: string, numMax: number): Promise> | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getMissionSnapShot(deviceId: string, missionId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | lockMission(missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | lockMission(missionId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | unlockMission(missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | unlockMission(missionId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | clearMission(missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | clearMission(missionId: number): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | clearAllMissions(callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | clearAllMissions(): Promise | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | moveMissionToFront(missionId: number, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.missionManager.d.ts | moveMissionToFront(missionId: number, options?: StartOptions): Promise | Asynchronous callback | +| @ohos.app.ability.quickFixManager.d.ts | applyQuickFix(hapModuleQuickFixFiles: Array, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.quickFixManager.d.ts | applyQuickFix(hapModuleQuickFixFiles: Array): Promise | Asynchronous callback | +| @ohos.app.ability.quickFixManager.d.ts | getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.quickFixManager.d.ts | getApplicationQuickFixInfo(bundleName: string): Promise | Asynchronous callback | +| @ohos.app.ability.wantAgent.d.ts | getWant(agent: WantAgent, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.ability.wantAgent.d.ts | getWant(agent: WantAgent): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | deleteForm(formId: string, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | deleteForm(formId: string): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | releaseForm(formId: string, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | releaseForm(formId: string, isReleaseCache?: boolean): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | requestForm(formId: string, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | requestForm(formId: string): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | castToNormalForm(formId: string, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | castToNormalForm(formId: string): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyVisibleForms(formIds: Array, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyVisibleForms(formIds: Array): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyInvisibleForms(formIds: Array, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyInvisibleForms(formIds: Array): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | enableFormsUpdate(formIds: Array, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | enableFormsUpdate(formIds: Array): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | disableFormsUpdate(formIds: Array, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | disableFormsUpdate(formIds: Array): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | isSystemReady(callback: AsyncCallback): void | Exception | +| @ohos.app.form.formHost.d.ts | isSystemReady(): Promise | Exception | +| @ohos.app.form.formHost.d.ts | getAllFormsInfo(callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | getAllFormsInfo(): Promise> | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | getFormsInfo(bundleName: string, callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback>): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | getFormsInfo(bundleName: string, moduleName?: string): Promise> | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | deleteInvalidForms(formIds: Array, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | deleteInvalidForms(formIds: Array): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | acquireFormState(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | acquireFormState(want: Want): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | on(type: "formUninstall", callback: Callback): void | Exception | +| @ohos.app.form.formHost.d.ts | off(type: "formUninstall", callback?: Callback): void | Exception | +| @ohos.app.form.formHost.d.ts | notifyFormsVisible(formIds: Array, isVisible: boolean, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyFormsVisible(formIds: Array, isVisible: boolean): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyFormsEnableUpdate(formIds: Array, isEnableUpdate: boolean, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyFormsEnableUpdate(formIds: Array, isEnableUpdate: boolean): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | shareForm(formId: string, deviceId: string, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | shareForm(formId: string, deviceId: string): Promise | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyFormsPrivacyProtected(formIds: Array, isProtected: boolean, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formHost.d.ts | notifyFormsPrivacyProtected(formIds: Array, isProtected: boolean): Promise | Asynchronous callback | +| @ohos.app.form.formProvider.d.ts | requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formProvider.d.ts | requestPublishForm(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| @ohos.app.form.formProvider.d.ts | requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise | Asynchronous callback | +| @ohos.app.form.formProvider.d.ts | isRequestPublishFormSupported(callback: AsyncCallback): void | Exception | +| @ohos.app.form.formProvider.d.ts | isRequestPublishFormSupported(): Promise | Exception | +| UIAbilityContext.d.ts | startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise | Asynchronous callback | +| UIAbilityContext.d.ts | startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Exception | +| UIAbilityContext.d.ts | startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback): void | Exception | +| UIAbilityContext.d.ts | startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise | Exception | +| UIAbilityContext.d.ts | startServiceExtensionAbility(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | startServiceExtensionAbility(want: Want): Promise | Asynchronous callback | +| UIAbilityContext.d.ts | startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise | Asynchronous callback | +| UIAbilityContext.d.ts | stopServiceExtensionAbility(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | stopServiceExtensionAbility(want: Want): Promise | Asynchronous callback | +| UIAbilityContext.d.ts | stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise | Asynchronous callback | +| UIAbilityContext.d.ts | connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number | Asynchronous callback | +| UIAbilityContext.d.ts | setMissionIcon(icon: image.PixelMap, callback: AsyncCallback): void | Asynchronous callback | +| UIAbilityContext.d.ts | setMissionIcon(icon: image.PixelMap): Promise | Asynchronous callback | +| ServiceExtensionContext.d.ts | startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| ServiceExtensionContext.d.ts | startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback): void | Asynchronous callback | +| ServiceExtensionContext.d.ts | startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise | Asynchronous callback | +| ServiceExtensionContext.d.ts | startServiceExtensionAbility(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| ServiceExtensionContext.d.ts | startServiceExtensionAbility(want: Want): Promise | Asynchronous callback | +| ServiceExtensionContext.d.ts | startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| ServiceExtensionContext.d.ts | startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise | Asynchronous callback | +| ServiceExtensionContext.d.ts | stopServiceExtensionAbility(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| ServiceExtensionContext.d.ts | stopServiceExtensionAbility(want: Want): Promise | Asynchronous callback | +| ServiceExtensionContext.d.ts | stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void | Asynchronous callback | +| ServiceExtensionContext.d.ts | stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise | Asynchronous callback | +| ServiceExtensionContext.d.ts | connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number | Asynchronous callback | +| Context.d.ts | createBundleContext(bundleName: string): Context | Exception | +| Context.d.ts | createModuleContext(bundleName: string, moduleName: string): Context | Exception | +| FormExtensionContext.d.ts | startAbility(want: Want, callback: AsyncCallback): void | Asynchronous callback | +| FormExtensionContext.d.ts | startAbility(want: Want): Promise | Asynchronous callback | diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md new file mode 100644 index 0000000000000000000000000000000000000000..d67dc521bfdb10aff1beee5453a9381ef39d4dc6 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-filemanagement.md @@ -0,0 +1,145 @@ +# File Management Subsystem ChangeLog + +## cl.filemanagement.1 Changed environment + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **environment** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **environment** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **environment** was imported using **@ohos.environment**: + +```js +import environment from '@ohos.environment'; +``` + +But now, **environment** is imported using **@ohos.file.environment**: + +```js +import environment from '@ohos.file.environment'; +``` + +## cl.filemanagement.2 Changed securityLabel + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **securityLabel** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **securityLabel** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **securityLabel** was imported using **@ohos.securityLabel**: + +```js +import securityLabel from '@ohos.securityLabel'; +``` + +But now, **securityLabel** is imported using **@ohos.file.securityLabel**: + +```js +import securityLabel from '@ohos.file.securityLabel'; +``` + +## cl.filemanagement.3 Changed fs + +The **ino** attribute type of the **Stat** API under the **fs** module is changed. + +**Change Impacts** + +The **ino** attribute type is changed from number to BigInt, to adapt to the inode range of all types of files in the file system. + +**Key API/Component Changes** + +The type of the **ino** attribute of the **Stat** API is changed from number to BigInt. + +## cl.filemanagement.4 Changed fileAccess + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileAccess** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **fileAccess** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **fileAccess** was imported using **@ohos.data.fileAccess**: + +```js +import fileAccess from '@ohos.data.fileAccess'; +``` + +But now, **fileAccess** is imported using **@ohos.file.fileAccess**: + +```js +import fileAccess from '@ohos.file.fileAccess'; +``` + +## cl.filemanagement.5 Changed fileExtensionInfo + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **fileExtensionInfo** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **fileExtensionInfo** was imported using **@ohos.fileExtensionInfo**: + +```js +import fileExtensionInfo from '@ohos.fileExtensionInfo'; +``` + +But now, **fileExtensionInfo** is imported using **@ohos.file.fileExtensionInfo**: + +```js +import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; +``` + +## cl.filemanagement.6 Changed storageStatistics + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **storageStatistics** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **storageStatistics** was imported using **@ohos.storageStatistics**: + +```js +import storageStatistics from '@ohos.storageStatistics'; +``` + +But now, **storageStatistics** is imported using **@ohos.file.storageStatistics**: + +```js +import storageStatistics from '@ohos.file.storageStatistics'; +``` + +## cl.filemanagement.7 Changed volumeManager + +The file management subsystem **d.ts** file has been moved to the **file** directory. The **fileExtensionInfo** module supports error code processing. + +**Change Impacts** + +If your application is developed based on earlier versions, note that the **d.ts** file storage location and the name of the module to be imported are changed. The **volumeManager** module supports error code processing. See [adaptation instructions](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details. + +**Key API/Component Changes** + +Before the change, **volumeManager** was imported using **@ohos.volumeManager**: + +```js +import volumeManager from '@ohos.volumeManager'; +``` + +But now, **volumeManager** is imported using **@ohos.file.volumeManager**: + +```js +import volumeManager from '@ohos.file.volumeManager'; +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-global.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-global.md new file mode 100644 index 0000000000000000000000000000000000000000..7192f94cba5682b78cd477953ed521bc42434609 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-global.md @@ -0,0 +1,41 @@ +# Globalization Subsystem ChangeLog + +## cl.global.1 Runtime Authentication Added for System APIs + +The internationalization component of the globalization subsystem adds runtime authentication for system APIs in certain scenarios. The following changes are made in API version 9 and later: + - Setting the system language, country or region, and area + - Setting the 24-hour format of the system + - Adding and removing the preferred language + - Setting localized numbers + +You need to adapt your application based on the following information. + +**Change Impacts** + +APIs involved in the preceding scenarios can be properly called only by system applications that have the **UPDATE_CONFIGURATION** permission. + +**Key API/Component Changes** + + - Involved APIs: + - setSystemLanguage(language: string): void; + - setSystemRegion(region: string): void; + - setSystemLocale(locale: string): void; + - set24HourClock(option: boolean): void; + - addPreferredLanguage(language: string, index?: number): void; + - removePreferredLanguage(index: number): void; + - setUsingLocalDigit(flag: boolean): void; + +**Adaptation Guide** + +Make sure the application trying to call any of the above APIs is a system application. Non-system applications are not allowed to call the APIs. +An exception will be thrown upon lack of a necessary permission or a call request from a non-system application. The exception can be captured via **try-catch**. + +```js +import I18n from '@ohos.i18n' + +try { + I18n.System.setSystemLanguage('zh'); +} catch(error) { + console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-media.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-media.md new file mode 100644 index 0000000000000000000000000000000000000000..01455e8774555943174a21a80f343b607a4a0069 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-media.md @@ -0,0 +1,314 @@ +# Media Subsystem ChangeLog + +## cl.media.1 API Change of the Playback Function + +Added the [AVPlayer](../../../application-dev/reference/apis/js-apis-media.md#avplayer9)9+ API for audio and video playback, with the updated state machine and error codes, which is recommended. The following APIs for audio playback and video playback are no longer maintained: [AudioPlayer](../../../application-dev/reference/apis/js-apis-media.md#audioplayer)6+ and [VideoPlayer](../../../application-dev/reference/apis/js-apis-media.md#videoplayer)8+. + +**Change Impacts** + +The original APIs can still be used but are no longer maintained. You are advised to use the new API instead. + +**Key API/Component Changes** + +Added APIs + +| Class | Declaration | +| -------------- | ------------------------------------------------------------ | +| media | createAVPlayer(callback: AsyncCallback\): void | +| media | createAVPlayer() : Promise\ | +| media.AVPlayer | interface AVPlayer | +| media.AVPlayer | videoScaleType ?: VideoScaleType | +| media.AVPlayer | url ?: string | +| media.AVPlayer | surfaceId ?: string | +| media.AVPlayer | stop(callback: AsyncCallback\): void | +| media.AVPlayer | stop(): Promise\ | +| media.AVPlayer | setVolume(volume: number): void | +| media.AVPlayer | setSpeed(speed: PlaybackSpeed): void | +| media.AVPlayer | setBitrate(bitrate: number): void | +| media.AVPlayer | seek(timeMs: number, mode?:SeekMode): void | +| media.AVPlayer | reset(callback: AsyncCallback\): void | +| media.AVPlayer | reset(): Promise\ | +| media.AVPlayer | release(callback: AsyncCallback\): void | +| media.AVPlayer | release(): Promise\ | +| media.AVPlayer | readonly width: number | +| media.AVPlayer | readonly state: AVPlayerState | +| media.AVPlayer | readonly height: number | +| media.AVPlayer | readonly duration: number | +| media.AVPlayer | readonly currentTime: number | +| media.AVPlayer | prepare(callback: AsyncCallback\): void | +| media.AVPlayer | prepare(): Promise\ | +| media.AVPlayer | play(callback: AsyncCallback\): void | +| media.AVPlayer | play(): Promise\ | +| media.AVPlayer | pause(callback: AsyncCallback\): void | +| media.AVPlayer | pause(): Promise\ | +| media.AVPlayer | on(type: 'volumeChange', callback: Callback\): void | +| media.AVPlayer | on(type: 'videoSizeChange', callback: (width: number, height: number) => void): void | +| media.AVPlayer | on(type: 'timeUpdate', callback: Callback\): void | +| media.AVPlayer | on(type: 'stateChange', callback: (state: AVPlayerState, reason: StateChangeReason) => void): void | +| media.AVPlayer | on(type: 'startRenderFrame', callback: Callback\): void | +| media.AVPlayer | on(type: 'speedDone', callback: Callback\): void | +| media.AVPlayer | on(type: 'seekDone', callback: Callback\): void | +| media.AVPlayer | on(type: 'error', callback: ErrorCallback): void | +| media.AVPlayer | on(type: 'endOfStream', callback: Callback\): void | +| media.AVPlayer | on(type: 'durationUpdate', callback: Callback\): void | +| media.AVPlayer | on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void | +| media.AVPlayer | on(type: 'bitrateDone', callback: Callback\): void | +| media.AVPlayer | on(type: 'availableBitrates', callback: (bitrates: Array\) => void): void | +| media.AVPlayer | on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void | +| media.AVPlayer | off(type: 'volumeChange'): void | +| media.AVPlayer | off(type: 'videoSizeChange'): void | +| media.AVPlayer | off(type: 'timeUpdate'): void | +| media.AVPlayer | off(type: 'stateChange'): void | +| media.AVPlayer | off(type: 'startRenderFrame'): void | +| media.AVPlayer | off(type: 'speedDone'): void | +| media.AVPlayer | off(type: 'seekDone'): void | +| media.AVPlayer | off(type: 'error'): void | +| media.AVPlayer | off(type: 'endOfStream'): void | +| media.AVPlayer | off(type: 'durationUpdate'): void | +| media.AVPlayer | off(type: 'bufferingUpdate'): void | +| media.AVPlayer | off(type: 'bitrateDone'): void | +| media.AVPlayer | off(type: 'availableBitrates'): void | +| media.AVPlayer | off(type: 'audioInterrupt'): void | +| media.AVPlayer | loop: boolean | +| media.AVPlayer | getTrackDescription(callback: AsyncCallback\>): void | +| media.AVPlayer | getTrackDescription() : Promise\> | +| media.AVPlayer | fdSrc ?: AVFileDescriptor | +| media.AVPlayer | audioInterruptMode ?: audio.InterruptMode | +| unnamed | type AVPlayerState = 'idle' \| 'initialized' \| 'prepared' \| 'playing' \| 'paused' \| 'completed' \| 'stopped' \| 'released' \| 'error' | + +APIs no longer maintained + +| Class | Declaration | +| ----------------- | ------------------------------------------------------------ | +| media | createVideoPlayer(callback: AsyncCallback\): void | +| media | createVideoPlayer() : Promise\ | +| media | createAudioPlayer(): AudioPlayer | +| media.AudioPlayer | interface AudioPlayer | +| media.AudioPlayer | play(): void | +| media.AudioPlayer | release(): void | +| media.AudioPlayer | audioInterruptMode ?: audio.InterruptMode | +| media.AudioPlayer | fdSrc: AVFileDescriptor | +| media.AudioPlayer | seek(timeMs: number): void | +| media.AudioPlayer | readonly duration: number | +| media.AudioPlayer | loop: boolean | +| media.AudioPlayer | readonly state: AudioState | +| media.AudioPlayer | getTrackDescription(callback: AsyncCallback\>): void | +| media.AudioPlayer | getTrackDescription() : Promise\> | +| media.AudioPlayer | on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void | +| media.AudioPlayer | on(type: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange', callback: () => void): void | +| media.AudioPlayer | on(type: 'timeUpdate', callback: Callback\): void | +| media.AudioPlayer | on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void | +| media.AudioPlayer | on(type: 'error', callback: ErrorCallback): void | +| media.AudioPlayer | setVolume(vol: number): void | +| media.AudioPlayer | pause(): void | +| media.AudioPlayer | readonly currentTime: number | +| media.AudioPlayer | stop(): void | +| media.AudioPlayer | reset(): void | +| media.AudioPlayer | src: string | +| media.VideoPlayer | interface VideoPlayer | +| media.VideoPlayer | play(callback: AsyncCallback\): void | +| media.VideoPlayer | play(): Promise\ | +| media.VideoPlayer | prepare(callback: AsyncCallback\): void | +| media.VideoPlayer | prepare(): Promise\ | +| media.VideoPlayer | release(callback: AsyncCallback\): void | +| media.VideoPlayer | release(): Promise\ | +| media.VideoPlayer | audioInterruptMode ?: audio.InterruptMode | +| media.VideoPlayer | fdSrc: AVFileDescriptor | +| media.VideoPlayer | seek(timeMs: number, callback: AsyncCallback\): void | +| media.VideoPlayer | seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void | +| media.VideoPlayer | seek(timeMs: number, mode?:SeekMode): Promise\ | +| media.VideoPlayer | readonly duration: number | +| media.VideoPlayer | loop: boolean | +| media.VideoPlayer | videoScaleType ?: VideoScaleType | +| media.VideoPlayer | readonly state: VideoPlayState | +| media.VideoPlayer | getTrackDescription(callback: AsyncCallback\>): void | +| media.VideoPlayer | getTrackDescription() : Promise\> | +| media.VideoPlayer | readonly height: number | +| media.VideoPlayer | on(type: 'playbackCompleted', callback: Callback\): void | +| media.VideoPlayer | on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void | +| media.VideoPlayer | on(type: 'startRenderFrame', callback: Callback\): void | +| media.VideoPlayer | on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void | +| media.VideoPlayer | on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void | +| media.VideoPlayer | on(type: 'error', callback: ErrorCallback): void | +| media.VideoPlayer | setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void | +| media.VideoPlayer | setDisplaySurface(surfaceId: string): Promise\ | +| media.VideoPlayer | setVolume(vol: number, callback: AsyncCallback\): void | +| media.VideoPlayer | setVolume(vol: number): Promise\ | +| media.VideoPlayer | url: string | +| media.VideoPlayer | pause(callback: AsyncCallback\): void | +| media.VideoPlayer | pause(): Promise\ | +| media.VideoPlayer | readonly currentTime: number | +| media.VideoPlayer | setSpeed(speed:number, callback: AsyncCallback\): void | +| media.VideoPlayer | setSpeed(speed:number): Promise\ | +| media.VideoPlayer | stop(callback: AsyncCallback\): void | +| media.VideoPlayer | stop(): Promise\ | +| media.VideoPlayer | readonly width: number | +| media.VideoPlayer | reset(callback: AsyncCallback\): void | +| media.VideoPlayer | reset(): Promise\ | +| unnamed | type AudioState = 'idle' \| 'playing' \| 'paused' \| 'stopped' \| 'error' | +| unnamed | type VideoPlayState = 'idle' \| 'prepared' \| 'playing' \| 'paused' \| 'stopped' \| 'error' | + +**Adaptation Guide** + +For details, see the [reference](../../../application-dev/reference/apis/js-apis-media.md) for each API. + +## cl.media.2 API Change of the Recording Function + +Added the [AVRecorder](../../../application-dev/reference/apis/js-apis-media.md#avrecorder9)9+ API for audio and video recording, with the updated state machine and error codes, which is recommended. The following APIs for audio recording and video recording are no longer maintained: [AudioRecorder](../../../application-dev/reference/apis/js-apis-media.md#audiorecorder)6+ and [VideoRecorder](../../../application-dev/reference/apis/js-apis-media.md#videorecorder9)9+. + +The [AudioSourceType](../../../application-dev/reference/apis/js-apis-media.md#audiosourcetype9) and [VideoSourceType](../../../application-dev/reference/apis/js-apis-media.md#videosourcetype9) APIs shared by the old and new recording APIs are changed to non-system APIs. + +**Change Impacts** + +The [AudioRecorder](../../../application-dev/reference/apis/js-apis-media.md#audiorecorder)6+ and [VideoRecorder](../../../application-dev/reference/apis/js-apis-media.md#videorecorder9)9+ APIs can still be used but are no longer maintained. You are advised to use the [AVRecorder](../../../application-dev/reference/apis/js-apis-media.md#avrecorder9)9+ API instead. + +**Key API/Component Changes** + +Added APIs + +| Class | Declaration | +| ----------------------- | ------------------------------------------------------------ | +| media | createAVRecorder(callback: AsyncCallback\): void | +| media | createAVRecorder() : Promise\ | +| media.AVRecorder | interface AVRecorder | +| media.AVRecorder | prepare(config: AVRecorderConfig, callback: AsyncCallback\): void | +| media.AVRecorder | prepare(config: AVRecorderConfig): Promise\ | +| media.AVRecorder | release(callback: AsyncCallback\): void | +| media.AVRecorder | release(): Promise\ | +| media.AVRecorder | readonly state: AVRecorderState | +| media.AVRecorder | on(type: 'stateChange', callback: (state: AVRecorderState, reason: StateChangeReason) => void): void | +| media.AVRecorder | on(type: 'error', callback: ErrorCallback): void | +| media.AVRecorder | resume(callback: AsyncCallback\): void | +| media.AVRecorder | resume(): Promise\ | +| media.AVRecorder | start(callback: AsyncCallback\): void | +| media.AVRecorder | start(): Promise\ | +| media.AVRecorder | off(type: 'stateChange'): void | +| media.AVRecorder | off(type: 'error'): void | +| media.AVRecorder | pause(callback: AsyncCallback\): void | +| media.AVRecorder | pause(): Promise\ | +| media.AVRecorder | stop(callback: AsyncCallback\): void | +| media.AVRecorder | stop(): Promise\ | +| media.AVRecorder | reset(callback: AsyncCallback\): void | +| media.AVRecorder | reset(): Promise\ | +| media.AVRecorder | getInputSurface(callback: AsyncCallback\): void | +| media.AVRecorder | getInputSurface(): Promise\ | +| media.AVRecorderConfig | videoSourceType?: VideoSourceType | +| media.AVRecorderConfig | audioSourceType?: AudioSourceType | +| media.AVRecorderConfig | profile: AVRecorderProfile | +| media.AVRecorderConfig | rotation?: number | +| media.AVRecorderConfig | url: string | +| media.AVRecorderConfig | location?: Location | +| media.AVRecorderConfig | interface AVRecorderConfig | +| media.AVRecorderProfile | videoBitrate?: number | +| media.AVRecorderProfile | videoCodec?: CodecMimeType | +| media.AVRecorderProfile | audioCodec?: CodecMimeType | +| media.AVRecorderProfile | videoFrameRate?: number | +| media.AVRecorderProfile | videoFrameHeight?: number | +| media.AVRecorderProfile | audioSampleRate?: number | +| media.AVRecorderProfile | audioBitrate?: number | +| media.AVRecorderProfile | videoFrameWidth?: number | +| media.AVRecorderProfile | audioChannels?: number | +| media.AVRecorderProfile | fileFormat: ContainerFormatType | +| media.AVRecorderProfile | interface AVRecorderProfile | +| unnamed | type AVRecorderState = 'idle' \| 'prepared' \| 'started' \| 'paused' \| 'stopped' \| 'released' \| 'error' | + +APIs no longer maintained + +| Class | Declaration | +| -------------------------- | ------------------------------------------------------------ | +| media | createVideoRecorder(callback: AsyncCallback\): void | +| media | createVideoRecorder(): Promise\ | +| media | createAudioRecorder(): AudioRecorder | +| media.AudioRecorder | interface AudioRecorder | +| media.AudioRecorder | prepare(config: AudioRecorderConfig): void | +| media.AudioRecorder | release(): void | +| media.AudioRecorder | on(type: 'prepare' \| 'start' \| 'pause' \| 'resume' \| 'stop' \| 'release' \| 'reset', callback: () => void): void | +| media.AudioRecorder | on(type: 'error', callback: ErrorCallback): void | +| media.AudioRecorder | resume(): void | +| media.AudioRecorder | start(): void | +| media.AudioRecorder | pause(): void | +| media.AudioRecorder | stop(): void | +| media.AudioRecorder | reset(): void | +| media.AudioRecorderConfig | audioSampleRate?: number | +| media.AudioRecorderConfig | location?: Location | +| media.AudioRecorderConfig | fileFormat?: ContainerFormatType | +| media.AudioRecorderConfig | interface AudioRecorderConfig | +| media.AudioRecorderConfig | audioEncoder?: AudioEncoder | +| media.AudioRecorderConfig | audioEncodeBitRate?: number | +| media.AudioRecorderConfig | numberOfChannels?: number | +| media.AudioRecorderConfig | format?: AudioOutputFormat | +| media.AudioRecorderConfig | uri: string | +| media.AudioRecorderConfig | audioEncoderMime?: CodecMimeType | +| media.VideoRecorder | interface VideoRecorder | +| media.VideoRecorder | prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void | +| media.VideoRecorder | prepare(config: VideoRecorderConfig): Promise\ | +| media.VideoRecorder | release(callback: AsyncCallback\): void | +| media.VideoRecorder | release(): Promise\ | +| media.VideoRecorder | readonly state: VideoRecordState | +| media.VideoRecorder | on(type: 'error', callback: ErrorCallback): void | +| media.VideoRecorder | resume(callback: AsyncCallback\): void | +| media.VideoRecorder | resume(): Promise\ | +| media.VideoRecorder | start(callback: AsyncCallback\): void | +| media.VideoRecorder | start(): Promise\ | +| media.VideoRecorder | pause(callback: AsyncCallback\): void | +| media.VideoRecorder | pause(): Promise\ | +| media.VideoRecorder | stop(callback: AsyncCallback\): void | +| media.VideoRecorder | stop(): Promise\ | +| media.VideoRecorder | reset(callback: AsyncCallback\): void | +| media.VideoRecorder | reset(): Promise\ | +| media.VideoRecorder | getInputSurface(callback: AsyncCallback\): void | +| media.VideoRecorder | getInputSurface(): Promise\ | +| media.VideoRecorderConfig | videoSourceType: VideoSourceType | +| media.VideoRecorderConfig | audioSourceType?: AudioSourceType | +| media.VideoRecorderConfig | profile: VideoRecorderProfile | +| media.VideoRecorderConfig | rotation?: number | +| media.VideoRecorderConfig | url: string | +| media.VideoRecorderConfig | location?: Location | +| media.VideoRecorderConfig | interface VideoRecorderConfig | +| media.VideoRecorderProfile | readonly videoBitrate: number | +| media.VideoRecorderProfile | readonly videoCodec: CodecMimeType | +| media.VideoRecorderProfile | readonly audioCodec: CodecMimeType | +| media.VideoRecorderProfile | readonly videoFrameRate: number | +| media.VideoRecorderProfile | readonly videoFrameHeight: number | +| media.VideoRecorderProfile | readonly audioSampleRate: number | +| media.VideoRecorderProfile | readonly audioBitrate: number | +| media.VideoRecorderProfile | readonly videoFrameWidth: number | +| media.VideoRecorderProfile | readonly audioChannels: number | +| media.VideoRecorderProfile | readonly fileFormat: ContainerFormatType | +| media.VideoRecorderProfile | interface VideoRecorderProfile | +| unnamed | type VideoRecordState = 'idle' \| 'prepared' \| 'playing' \| 'paused' \| 'stopped' \| 'error' | + +Changed APIs + +| Class | Declaration | Capability Before Change | Capability After Change | Whether a System API Before Change| Whether a System API After Change| +| --------------------- | ------------------------------------------------------------ | ----------------------------------------------- | -------------------------------------------- | -------------------- | -------------------- | +| media.AudioSourceType | enum AudioSourceType { /** * default audio source type. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ AUDIO_SOURCE_TYPE_DEFAULT = 0, /** * source type mic. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ AUDIO_SOURCE_TYPE_MIC = 1, } | SystemCapability.Multimedia.Media.VideoRecorder | SystemCapability.Multimedia.Media.AVRecorder | Yes | No | +| media.VideoSourceType | enum VideoSourceType { /** * surface raw data. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ VIDEO_SOURCE_TYPE_SURFACE_YUV = 0, /** * surface ES data. * @since 9 * @syscap SystemCapability.Multimedia.Media.AVRecorder */ VIDEO_SOURCE_TYPE_SURFACE_ES = 1, } | SystemCapability.Multimedia.Media.VideoRecorder | SystemCapability.Multimedia.Media.AVRecorder | Yes | No | + +**Adaptation Guide** + +For details, see the [reference](../../../application-dev/reference/apis/js-apis-media.md) for each API. + +## cl.media.3 Error Code Change + +Added the standard error code enumeration type [AVErrorCode9](../../../application-dev/reference/apis/js-apis-media.md#averrorcode)9+ that replaces the original error code enumeration type [MediaErrorCode](../../../application-dev/reference/apis/js-apis-media.md#mediaerrorcode)8+. + +**Change Impacts** + +The error code enumeration type [MediaErrorCode](../../../application-dev/reference/apis/js-apis-media.md#mediaerrorcode)8+ is still used for original APIs. [AVErrorCode9](../../../application-dev/reference/apis/js-apis-media.md#averrorcode)9+ is used for newly added APIs. + +**Key API/Component Changes** + +Added API + +| Class | Declaration | +| ----------------- | ------------------------------------------------------------ | +| media.AVErrorCode | enum AVErrorCode { /** * operation success. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_OK = 0, /** * permission denied. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_NO_PERMISSION = 201, /** * invalid parameter. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_INVALID_PARAMETER = 401, /** * the api is not supported in the current version * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_UNSUPPORT_CAPABILITY = 801, /** * the system memory is insufficient or the number of services reaches the upper limit * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_NO_MEMORY = 5400101, /** * current status does not allow or do not have permission to perform this operation * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_OPERATE_NOT_PERMIT = 5400102, /** * data flow exception information * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_IO = 5400103, /** * system or network response timeout. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_TIMEOUT = 5400104, /** * service process died. * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_SERVICE_DIED = 5400105, /** * unsupported media format * @since 9 * @syscap SystemCapability.Multimedia.Media.Core */ AVERR_UNSUPPORT_FORMAT = 5400106, } | + +API no longer maintained + +| Class | Declaration | +| -------------------- | ------------------------------------------------------------ | +| media.MediaErrorCode | enum MediaErrorCode { /** * operation success. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_OK = 0, /** * malloc or new memory failed. maybe system have no memory. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_NO_MEMORY = 1, /** * no permission for the operation. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_OPERATION_NOT_PERMIT = 2, /** * invalid argument. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_INVALID_VAL = 3, /** * an I/O error occurred. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_IO = 4, /** * operation time out. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_TIMEOUT = 5, /** * unknown error. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_UNKNOWN = 6, /** * media service died. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_SERVICE_DIED = 7, /** * operation is not permit in current state. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_INVALID_STATE = 8, /** * operation is not supported in current version. * @since 8 * @syscap SystemCapability.Multimedia.Media.Core */ MSERR_UNSUPPORTED = 9, } | + + \ No newline at end of file diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md new file mode 100644 index 0000000000000000000000000000000000000000..9a5e30e4a4c8d24266d966f9ac6dc249748cfa60 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.1/changelogs-usb.md @@ -0,0 +1,18 @@ +USB Manager ChangeLog + +## cl.usb_manager.1 System API Change + +Runtime authentication is performed for system APIs of the USB manager. An asynchronous API throws an error code via **Promise.reject**. + +If your application is developed based on earlier versions, modify the return values of functions. Otherwise, the original service logic will be affected. + +**Key API/Component Changes** + +| Bundle Name | Original API | New API | +| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.usbV9.d.ts | function setCurrentFunctions(funcs: FunctionType): Promise; | function setCurrentFunctions(funcs: FunctionType): Promise; | +| ohos.usbV9.d.ts | function setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise; | function setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise; | + +**Adaptation Guide** + +For details, see the [reference](../../../application-dev/reference/errorcodes/errorcode-universal.md) for each API. diff --git a/zh-cn/application-dev/ability-deprecated/fa-brief.md b/zh-cn/application-dev/ability-deprecated/fa-brief.md index 304cbc0be9f90d6ac83699c5b3da83aef02fb623..0e076ebc937aa8e0726361f865285fb181068c10 100644 --- a/zh-cn/application-dev/ability-deprecated/fa-brief.md +++ b/zh-cn/application-dev/ability-deprecated/fa-brief.md @@ -52,9 +52,9 @@ FA模型的应用包的工程目录结构,请参考[OpenHarmony工程介绍](h - [`DistributeGraffiti`:分布式涂鸦(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DistributedGraffiti) - [分布式调度启动远程FA(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA) - [分布式新闻客户端(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo) -- [分布式手写板(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) +- [分布式手写板(ArkTS)(Full SDK)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) - [分布式鉴权(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH) -- [分布式游戏手柄(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) -- [分布式邮件(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) -- [分布式亲子早教系统(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) -- [分布式遥控器(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) \ No newline at end of file +- [分布式游戏手柄(ArkTS)(Full SDK)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) +- [分布式邮件(ArkTS)(Full SDK)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) +- [分布式亲子早教系统(ArkTS)(Full SDK)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) +- [分布式遥控器(ArkTS)(Full SDK)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) \ No newline at end of file diff --git a/zh-cn/application-dev/ability-deprecated/stage-ability.md b/zh-cn/application-dev/ability-deprecated/stage-ability.md index 9d46fe84685e67a9426e1f90f3fa2ae906765fe7..6c01bfd65ab80f3928f36dca6d9462d373528872 100644 --- a/zh-cn/application-dev/ability-deprecated/stage-ability.md +++ b/zh-cn/application-dev/ability-deprecated/stage-ability.md @@ -302,3 +302,12 @@ struct Index { } } ``` +## 相关实例 + +基于Stage模型下的Ability开发,有以下相关实例可供参考: + +- [Ability内和Ability间页面的跳转(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/StageAbility) + +- [Stage模型下Ability的创建和使用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/StageAbilityDemo) + +- [Ability内页面间的跳转(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/PagesRouter) \ No newline at end of file diff --git a/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md b/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md index fd8691f841abfa4d3ce4407b9f849875eb2bda0d..b04c8a609efea09cdfef39d54a811756aabc180f 100644 --- a/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md +++ b/zh-cn/application-dev/ability-deprecated/stage-serviceextension.md @@ -75,4 +75,6 @@ OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。 ## 相关实例 针对ServiceExtensionAbility开发,有以下相关实例可供参考: + +- [`AbilityConnectServiceExtension`:Ability与ServiceExtensionAbility通信(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/AbilityConnectServiceExtension) - [`ServiceExtAbility`:StageExtAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceExtAbility) diff --git a/zh-cn/application-dev/application-models/Readme-CN.md b/zh-cn/application-dev/application-models/Readme-CN.md index 84810a7ad13e9b1c6926946b1bd3c4777d026cf9..8cb463f4095fc47edbac1dfa6f969a116226ba9f 100644 --- a/zh-cn/application-dev/application-models/Readme-CN.md +++ b/zh-cn/application-dev/application-models/Readme-CN.md @@ -19,6 +19,7 @@ - [ServiceExtensionAbility](serviceextensionability.md) - [DataShareExtensionAbility(仅对系统应用开放)](datashareextensionability.md) - [FormExtensionAbility(服务卡片)](widget-development-stage.md) + - [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md) - [AbilityStage组件容器](abilitystage.md) - [应用上下文Context](application-context-stage.md) - 信息传递载体Want diff --git a/zh-cn/application-dev/application-models/actions-entities.md b/zh-cn/application-dev/application-models/actions-entities.md index a03921827b795c847d66cd8d4637b2639cb3b9a0..03dac0817a7f92076f49e4a77eb9da1cd0e69655 100644 --- a/zh-cn/application-dev/application-models/actions-entities.md +++ b/zh-cn/application-dev/application-models/actions-entities.md @@ -1,6 +1,6 @@ # 常见action与entities -**[action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)**:表示调用方要执行的通用操作(如查看、分享、应用详情)。在隐式Want中,您可定义该字段,配合uri或parameters来表示对数据要执行的操作。如打开,查看该uri数据。例如,当uri为一段网址,action为ohos.want.action.viewData则表示匹配可查看该网址的Ability。在Want内声明action字段表示希望被调用方应用支持声明的操作。在被调用方应用配置文件skills字段内声明actions表示该应用支持声明操作。 +**[action](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantaction)**:表示调用方要执行的通用操作(如查看、分享、应用详情)。在隐式Want中,您可定义该字段,配合uri或parameters来表示对数据要执行的操作。如打开,查看该uri数据。例如,当uri为一段网址,action为ohos.want.action.viewData则表示匹配可查看该网址的Ability。在Want内声明action字段表示希望被调用方应用支持声明的操作。在被调用方应用配置文件skills字段内声明actions表示该应用支持声明操作。 **常见action** @@ -14,7 +14,7 @@ - ACTION_VIEW_MULTIPLE_DATA:发送多个数据记录的操作。 -**[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)**:表示目标Ability的类别信息(如浏览器、视频播放器),在隐式Want中是对action的补充。在隐式Want中,开发者可定义该字段,来过滤匹配应用的类别,例如必须是浏览器。在Want内声明entities字段表示希望被调用方应用属于声明的类别。在被调用方应用配置文件skills字段内声明entites表示该应用支持的类别。 +**[entities](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantentity)**:表示目标Ability的类别信息(如浏览器、视频播放器),在隐式Want中是对action的补充。在隐式Want中,开发者可定义该字段,来过滤匹配应用的类别,例如必须是浏览器。在Want内声明entities字段表示希望被调用方应用属于声明的类别。在被调用方应用配置文件skills字段内声明entites表示该应用支持的类别。 **常用entities** diff --git a/zh-cn/application-dev/application-models/dataability-overview.md b/zh-cn/application-dev/application-models/dataability-overview.md index 40a2b556a376ace6c5f4eb9dcc77d052ae175c22..f764dd7148be1bf493f89e79c4c1160e8fd2cd74 100644 --- a/zh-cn/application-dev/application-models/dataability-overview.md +++ b/zh-cn/application-dev/application-models/dataability-overview.md @@ -8,3 +8,9 @@ DataAbility,即"使用Data模板的Ability",主要用于对外部提供统 数据的存放形式多样,可以是数据库,也可以是磁盘上的文件。DataAbility对外提供对数据的增、删、改、查,以及打开文件等接口,这些接口的具体实现由开发者提供。 + +## 相关实例 + +基于DataAbility组件的开发,以下相关实例可供参考: + +- [`DataAbility`:DataAbility的创建与访问(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DataAbility) diff --git a/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md b/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md index 7708ceff9d8511cce98c3451c28b84e12cd0b807..4d79a19ba55ae1559fb651a669dbb1d7ef459873 100644 --- a/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md @@ -50,7 +50,7 @@ ### want参数的action匹配规则 -将调用方传入的want参数的[action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)与待匹配Ability的skills配置中的actions进行匹配。 +将调用方传入的want参数的[action](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantaction)与待匹配Ability的skills配置中的actions进行匹配。 - 调用方传入的want参数的action不为空,待匹配Ability的skills配置中的actions为空,则action匹配失败。 @@ -66,7 +66,7 @@ ### want参数的entities匹配规则 -将调用方传入的want参数的[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)与待匹配Ability的skills配置中的entities进行匹配。 +将调用方传入的want参数的[entities](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantentity)与待匹配Ability的skills配置中的entities进行匹配。 - 调用方传入的want参数的entities为空,待匹配Ability的skills配置中的entities不为空,则entities匹配成功。 diff --git a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md index 8ef80658209941597a75fc1b8b15b2e326999c75..411f454354fd2c430eff1badf41b759485d9aab0 100644 --- a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md +++ b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md @@ -93,7 +93,7 @@ } ``` -4. 设置目标组件参数,调用startAbility()接口,启动UIAbility或ServiceExtensionAbility。 +4. 设置目标组件参数,调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)接口,启动UIAbility或ServiceExtensionAbility。 ```ts let want = { diff --git a/zh-cn/application-dev/application-models/mission-management-launch-type.md b/zh-cn/application-dev/application-models/mission-management-launch-type.md index 713e62c3dfccc25ca1d9df56ab986c74ba30590d..2ed765ca1a03b809165808c9d42e604c75baa659 100644 --- a/zh-cn/application-dev/application-models/mission-management-launch-type.md +++ b/zh-cn/application-dev/application-models/mission-management-launch-type.md @@ -10,7 +10,7 @@ **图1** 任务与singleton模式 ![mission-and-singleton](figures/mission-and-singleton.png) -- standard:多实例模式,每次调用startAbility()方法,都会在应用进程中创建一个该Ability的实例。 +- standard:多实例模式,每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法,都会在应用进程中创建一个该Ability的实例。 **图2** 任务与standard模式 ![mission-and-standard](figures/mission-and-standard.png) diff --git a/zh-cn/application-dev/application-models/mission-management-overview.md b/zh-cn/application-dev/application-models/mission-management-overview.md index df1022b3739b5b85a8606d1dbe005f004d927606..527a00d8dcca4221251bf2bbb9ec4e6ecc7baa75 100644 --- a/zh-cn/application-dev/application-models/mission-management-overview.md +++ b/zh-cn/application-dev/application-models/mission-management-overview.md @@ -28,7 +28,7 @@ - 将一个指定的任务切换到前台。 -一个UIAbility实例对应一个单独的任务,因此应用调用startAbility()方法启动一个UIAbility时,就是创建了一个任务。 +一个UIAbility实例对应一个单独的任务,因此应用调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动一个UIAbility时,就是创建了一个任务。 桌面应用调用[missionManager](../reference/apis/js-apis-application-missionManager.md)的接口管理任务,需要申请`ohos.permission.MANAGE_MISSIONS`权限,配置方式请参见[访问控制授权申请](../security/accesstoken-guidelines.md#配置文件权限声明)。 diff --git a/zh-cn/application-dev/application-models/serviceextensionability.md b/zh-cn/application-dev/application-models/serviceextensionability.md index 1d16582fb62e56f7d1edebabbcd4791f230665ad..3804801e9f6863ae3a98786d3ea8d2fe1d071d47 100644 --- a/zh-cn/application-dev/application-models/serviceextensionability.md +++ b/zh-cn/application-dev/application-models/serviceextensionability.md @@ -287,4 +287,5 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap 针对ServiceExtensionAbility开发,有以下相关示例可供参考: -[ServiceExtAbility:StageExtAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceExtAbility) +- [`AbilityConnectServiceExtension`:Ability与ServiceExtensionAbility通信(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/AbilityConnectServiceExtension) +- [`ServiceExtAbility`:StageExtAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceExtAbility) diff --git a/zh-cn/application-dev/application-models/start-serviceability.md b/zh-cn/application-dev/application-models/start-serviceability.md index 58140a70a3293745350b174b5fa550a341574746..c097ebdee1074f71d8147155d0d8167b11c170bb 100644 --- a/zh-cn/application-dev/application-models/start-serviceability.md +++ b/zh-cn/application-dev/application-models/start-serviceability.md @@ -27,7 +27,7 @@ async function startServiceAbility() { ``` -执行上述代码后,Ability将通过startAbility() 方法来启动ServiceAbility。 +执行上述代码后,Ability将通过[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法来启动ServiceAbility。 - 如果ServiceAbility尚未运行,则系统会先调用onStart()来初始化ServiceAbility,再回调Service的onCommand()方法来启动ServiceAbility。 diff --git a/zh-cn/application-dev/application-models/static-subscriber-extension-ability.md b/zh-cn/application-dev/application-models/static-subscriber-extension-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..c3710ea14ed77077049e4a7c5289160b5498063d --- /dev/null +++ b/zh-cn/application-dev/application-models/static-subscriber-extension-ability.md @@ -0,0 +1,108 @@ +# StaticSubscriberExtensionAbility开发指导 + +## 场景介绍 + +​公共事件服务提供了动态订阅和静态订阅两种订阅方式。动态订阅即订阅方在运行期调用公共事件订阅的API实现对公共事件的订阅,详见[公共事件订阅](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/application-models/common-event-subscription.md)。与动态订阅相对应的是静态订阅方式,这种方式不需要主动调用公共事件的API,而是通过配置文件声明和实现继承自StaticSubscriberExtensionAbility的类实现对公共事件的订阅。静态订阅者在未接收订阅的目标事件时,处于未拉起状态,当系统或应用发布了指定的公共事件后,静态订阅者将被拉起,并执行onReceiveEvent回调,开发者可通过在onReceiveEvent回调中执行业务逻辑,实现当应用接收到特定公共事件(例如开机事件)时执行业务逻辑的目的。**需要注意的是,静态订阅能力严格受限,相关接口为系统API,仅限于经过系统层面功耗评审的特定系统应用使用**。 + + + +## 开发步骤 + +1. 前置条件 + + 请确保您的应用具备以下特征: + + 1)系统应用 + + 2)使用full-sdk开发 + + 3)经过性能功耗团队评审符合功耗要求,如果您希望在调试阶段尝试使用该功能,可修改系统配置文件/etc/static_subscriber_config.json,将待调试应用的包名添加至json文件中即可。 + + + +2. 静态订阅者声明 + + 声明一个静态订阅者,首先需要在工程中新建一个ExtensionAbility, 该ExtensionAbility从StaticSubscriberExtensionAbility派生,其代码实现如下: + + ```ts + import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' + + export default class StaticSubscriber extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log('onReceiveEvent, event:' + event.event); + } + } + ``` + + 开发者可以在onReceiveEvent中实现业务逻辑。 + + + +3. 静态订阅者工程配置 + + 在完成静态订阅者的代码实现后,需要将该订阅者配置到系统的module.json5中,配置形式如下: + + ```ts + { + "module": { + ...... + "extensionAbilities": [ + { + "name": "StaticSubscriber", + "srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts", + "description": "$string:StaticSubscriber_desc", + "icon": "$media:icon", + "label": "$string:StaticSubscriber_label", + "type": "staticSubscriber", + "visible": true, + "metadata": [ + { + "name": "ohos.extension.staticSubscriber", + "resource": "$profile:subscribe" + } + ] + } + ] + ...... + } + } + ``` + + 上述json文件主要关注以下字段: + + **srcEntrance**: 表示extension的入口文件路径,即步骤2中声明的静态订阅者所在的文件路径 + + **type**: 表示extension的类型,对于静态订阅者需要声明为“staticSubscriber” + + **metadata**: 表示extension的二级配置文件信息。由于不同的extension类型其配置信息不尽相同,因此需要使用不同的config文件表示其具体配置信息。metadata字段共包含两个关键字name和resource。其中name字段表示extension的类型名称,对于静态订阅类型,name必须声明为“ohos.extension.staticSubscriber”,否则无法识别为静态订阅者;resource字段表示extension的配置信息路径,由开发者自行定义,在本例中表示路径为“resources/base/profile/subscribe.json"。 + + metadata指向的二级配置文件的通常形式如下: + + ```ts + { + "commonEvents": [ + { + "name": "xxx", + "permission": "xxx", + "events":[ + "xxx" + ] + } + ] + } + ``` + + 需要注意二级配置文件必须按照此形式进行声明,否则会无法正确识别。下面对字段进行介绍: + + **name**: 静态订阅extension的名称,需要和module.json5中声明的extensionAbility的name一致 + + **permission**:订阅者要求的发布者需要具备的权限,对于发布了目标事件但不具备permission中声明的权限的发布者将被视为非法事件不予发布 + + **events**: 订阅的目标事件列表 + + + +## 相关示例 + +针对StaticSubscriberExtensionAbility开发,可参考如下实例:[StaticSubscriber:静态订阅(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber) + diff --git a/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md b/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md index 1ab965ef42c2d3d6df911954a0342511bebbcbbf..f1209e81196a1f362e64cd7656426b322b35fcad 100644 --- a/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md +++ b/zh-cn/application-dev/application-models/uiability-data-sync-with-ui.md @@ -106,10 +106,10 @@ globalThis是ArkTS引擎实例内部的一个全局对象,引擎内部的UIAbi globalThis为[ArkTS引擎实例](thread-model-stage.md)下的全局对象,可以通过globalThis绑定属性/方法来进行UIAbility组件与UI的数据同步。例如在UIAbility组件中绑定want参数,即可在UIAbility对应的UI界面上使用want参数信息。 -1. 调用startAbility()方法启动一个UIAbility实例时,被启动的UIAbility创建完成后会进入onCreate()生命周期回调,且在onCreate()生命周期回调中能够接受到传递过来的want参数,可以将want参数绑定到globalThis上。 +1. 调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动一个UIAbility实例时,被启动的UIAbility创建完成后会进入onCreate()生命周期回调,且在onCreate()生命周期回调中能够接受到传递过来的want参数,可以将want参数绑定到globalThis上。 ```ts - import UIAbility from '@ohos.app.ability.UIAbility' + import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { onCreate(want, launch) { diff --git a/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md b/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md index 5da14dadd1a34b8d381f1bdc53b006f5295f2d41..7c52870b517f6ed8bc8e4028b17d3b770659f0c5 100644 --- a/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md +++ b/zh-cn/application-dev/application-models/uiability-intra-device-interaction.md @@ -26,7 +26,7 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳 假设应用中有两个UIAbility:EntryAbility和FuncAbility(可以在应用的一个Module中,也可以在的不同Module中),需要从EntryAbility的页面中启动FuncAbility。 -1. 在EntryAbility中,通过调用startAbility()方法启动UIAbility,[want](../reference/apis/js-apis-app-ability-want.md)为UIAbility实例启动的入口参数,其中bundleName为待启动应用的Bundle名称,abilityName为待启动的Ability名称,moduleName在待启动的UIAbility属于不同的Module时添加,parameters为自定义信息参数。示例中的context的获取方式参见[获取UIAbility的Context属性](uiability-usage.md#获取uiability的上下文信息)。 +1. 在EntryAbility中,通过调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动UIAbility,[want](../reference/apis/js-apis-app-ability-want.md)为UIAbility实例启动的入口参数,其中bundleName为待启动应用的Bundle名称,abilityName为待启动的Ability名称,moduleName在待启动的UIAbility属于不同的Module时添加,parameters为自定义信息参数。示例中的context的获取方式参见[获取UIAbility的Context属性](uiability-usage.md#获取uiability的上下文信息)。 ```ts let wantInfo = { @@ -149,11 +149,11 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳 - 显式Want启动:启动一个确定应用的UIAbility,在want参数中需要设置该应用bundleName和abilityName,当需要拉起某个明确的UIAbility时,通常使用显式Want启动方式。 -- 隐式Want启动:根据匹配条件由用户选择启动哪一个UIAbility,即不明确指出要启动哪一个UIAbility(abilityName参数未设置),在调用startAbility()方法时,其入参want中指定了一系列的[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)字段(表示目标UIAbility额外的类别信息,如浏览器、视频播放器)和[actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)字段(表示要执行的通用操作,如查看、分享、应用详情等)等参数信息,然后由系统去分析want,并帮助找到合适的UIAbility来启动。当需要拉起其他应用的UIAbility时,开发者通常不知道用户设备中应用的安装情况,也无法确定目标应用的bundleName和abilityName,通常使用隐式Want启动方式。 +- 隐式Want启动:根据匹配条件由用户选择启动哪一个UIAbility,即不明确指出要启动哪一个UIAbility(abilityName参数未设置),在调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,其入参want中指定了一系列的[entities](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantentity)字段(表示目标UIAbility额外的类别信息,如浏览器、视频播放器)和[actions](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantaction)字段(表示要执行的通用操作,如查看、分享、应用详情等)等参数信息,然后由系统去分析want,并帮助找到合适的UIAbility来启动。当需要拉起其他应用的UIAbility时,开发者通常不知道用户设备中应用的安装情况,也无法确定目标应用的bundleName和abilityName,通常使用隐式Want启动方式。 本章节主要讲解如何通过隐式Want启动其他应用的UIAbility。 -1. 将多个待匹配的文档应用安装到设备,在其对应UIAbility的[module.json5配置文件](../quick-start/module-configuration-file.md)中,配置skills的[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)字段和[actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)字段。 +1. 将多个待匹配的文档应用安装到设备,在其对应UIAbility的[module.json5配置文件](../quick-start/module-configuration-file.md)中,配置skills的[entities](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantentity)字段和[actions](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantaction)字段。 ```json { @@ -216,7 +216,7 @@ UIAbility是系统调度的最小单元。在设备内的功能模块之间跳 当使用隐式Want启动其他应用的UIAbility并希望获取返回结果时,调用方需要使用[startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult)方法启动目标UIAbility。例如主应用中需要启动三方支付并获取支付结果。 -1. 在支付应用对应UIAbility的module.json5配置文件中,配置skills的[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)字段和[actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)字段。 +1. 在支付应用对应UIAbility的module.json5配置文件中,配置skills的[entities](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantentity)字段和[actions](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantaction)字段。 ```json { diff --git a/zh-cn/application-dev/application-models/want-overview.md b/zh-cn/application-dev/application-models/want-overview.md index 2f4e72601056a6bbdf2beb24898f441bee11dd23..a4b2d99348769a9fbed5979c911c542f547b9516 100644 --- a/zh-cn/application-dev/application-models/want-overview.md +++ b/zh-cn/application-dev/application-models/want-overview.md @@ -3,7 +3,7 @@ ## Want的定义与用途 -[Want](../reference/apis/js-apis-app-ability-want.md)是对象间信息传递的载体,可以用于应用组件间的信息传递。其使用场景之一是作为startAbility()的参数,包含了指定的启动目标以及启动时需携带的相关数据,如bundleName和abilityName字段分别指明目标Ability所在应用的Bundle名称以及对应包内的Ability名称。当UIAbilityA启动UIAbilityB并需要传入一些数据给UIAbilityB时,Want可以作为一个载体将数据传给UIAbilityB。 +[Want](../reference/apis/js-apis-app-ability-want.md)是对象间信息传递的载体,可以用于应用组件间的信息传递。其使用场景之一是作为[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)的参数,包含了指定的启动目标以及启动时需携带的相关数据,如bundleName和abilityName字段分别指明目标Ability所在应用的Bundle名称以及对应包内的Ability名称。当UIAbilityA启动UIAbilityB并需要传入一些数据给UIAbilityB时,Want可以作为一个载体将数据传给UIAbilityB。 **图1** Want用法示意 usage-of-want diff --git a/zh-cn/application-dev/application-test/arkxtest-guidelines.md b/zh-cn/application-dev/application-test/arkxtest-guidelines.md index 8d31275f5d196b82a936c82c11baa53a17eefa9d..f79e8b5cce3c66e0c16b140c64c16326d76aade3 100644 --- a/zh-cn/application-dev/application-test/arkxtest-guidelines.md +++ b/zh-cn/application-dev/application-test/arkxtest-guidelines.md @@ -58,7 +58,7 @@ DevEco Studio可参考其官网介绍进行[下载](https://developer.harmonyos. ## 新建测试脚本 1. 在DevEco Studio中新建应用开发工程,其中ohos目录即为测试脚本所在的目录。 -2. 在工程目录下打开待测试模块下的ets文件,将光标置于代码中任意位置,单击**右键 > Show Context Actions** **> Create Ohos Test**或快捷键**Alt+enter** **> Create Ohos Test**创建测试类,更多指导请参考DevEco Studio中[指导](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001267284568)。 +2. 在工程目录下打开待测试模块下的ets文件,将光标置于代码中任意位置,单击**右键 > Show Context Actions** **> Create Ohos Test**或快捷键**Alt+enter** **> Create Ohos Test**创建测试类,更多指导请参考DevEco Studio中[指导](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453)。 ## 编写单元测试脚本 @@ -197,7 +197,8 @@ export default function abilityTest() { | breakOnError | 遇错即停模式,当执行用例断言失败或者发生错误时,退出测试执行流程 | true/false(默认值) | -s breakOnError true | | testType | 指定要执行用例的用例类型 | function,performance,power,reliability, security,global,compatibility,user,standard,safety,resilience' | -s testType function | | level | 指定要执行用例的用例级别 | 0,1,2,3,4 | -s level 0 | -| size | 指定要执行用例的用例规模 | small,medium,large | -s size small | +| size | 指定要执行用例的用例规模 | small,medium,large | -s size small +| stress | 指定要执行用例的执行次数 | 正整数 | -s stress 1000 | **通过在cmd窗口直接执行命令。** @@ -266,6 +267,12 @@ export default function abilityTest() { hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s size small ``` +**示例代码11**:执行测试用例指定次数。 + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s stress 1000 +``` + **查看测试结果** - cmd模式执行过程,会打印如下相关日志信息。 @@ -412,11 +419,11 @@ UI测试用例执行失败,查看hilog日志发现日志中有“uitest-api do 2.避免多进程执行UI测试用例。 -**3、失败日志有“dose not exist on current UI! Check if the UI has changed after you got the widget object”错误信息** +**3、失败日志有“does not exist on current UI! Check if the UI has changed after you got the widget object”错误信息** **问题描述** -UI测试用例执行失败,查看hilog日志发现日志中有“dose not exist on current UI! Check if the UI has changed after you got the widget object”错误信息。 +UI测试用例执行失败,查看hilog日志发现日志中有“does not exist on current UI! Check if the UI has changed after you got the widget object”错误信息。 **可能原因** diff --git a/zh-cn/application-dev/application-test/figures/Execute.PNG b/zh-cn/application-dev/application-test/figures/Execute.PNG index 49155c9b3406ea477e08273818e52fe026a62737..7c9d9be0d39c8b07c32f351622423085a4086584 100644 Binary files a/zh-cn/application-dev/application-test/figures/Execute.PNG and b/zh-cn/application-dev/application-test/figures/Execute.PNG differ diff --git a/zh-cn/application-dev/application-test/figures/TestResult.PNG b/zh-cn/application-dev/application-test/figures/TestResult.PNG index 300266842efab6da7a4f7469ab8c9e890f238b89..c2938e7f8fbd4ec112506db5b9b9ac03a7b42397 100644 Binary files a/zh-cn/application-dev/application-test/figures/TestResult.PNG and b/zh-cn/application-dev/application-test/figures/TestResult.PNG differ diff --git a/zh-cn/application-dev/connectivity/socket-connection.md b/zh-cn/application-dev/connectivity/socket-connection.md index 2c04d2270a2f2b9c0e9a4551fe06bd1d91483620..815b0fde28387264cf5cf0c6effe7d27f8c44c44 100644 --- a/zh-cn/application-dev/connectivity/socket-connection.md +++ b/zh-cn/application-dev/connectivity/socket-connection.md @@ -125,6 +125,6 @@ UDP与TCP流程大体类似,下面以TCP为例: ## 相关实例 针对Socket连接开发,有以下相关实例可供参考: -- [`Socket`:Socket 连接(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) +- [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) - [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) - [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-preference-guidelines.md b/zh-cn/application-dev/database/database-preference-guidelines.md index 95d59ac6e21e7c54136e72da7e091bfcff1df1df..2c7a5bfbc24291f6471b879daaa17327858b1633 100644 --- a/zh-cn/application-dev/database/database-preference-guidelines.md +++ b/zh-cn/application-dev/database/database-preference-guidelines.md @@ -208,4 +208,6 @@ 针对首选项开发,有以下相关实例可供参考: -- [`Preferences`:首选项(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Preferences) \ No newline at end of file +- [`Preferences`:首选项(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Preferences) + +- [首选项(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Data/Preferences) \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md index a4fdb811b66e7f370208c7f5c169b25256bbcc13..6d62e1d6024c0faff563643d3ae9d5100c8c6f14 100644 --- a/zh-cn/application-dev/database/database-relational-guidelines.md +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -202,39 +202,77 @@ ```js import data_rdb from '@ohos.data.relationalStore' - // 获取context import featureAbility from '@ohos.ability.featureAbility' + + // 获取context let context = featureAbility.getContext() - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 + } - const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} + // 假设当前数据库版本为3 data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - rdbStore.executeSql(CREATE_TABLE_TEST) - console.info('create table done.') + // 当数据库创建时,数据库默认版本为0 + if (rdbStore.version == 0) { + rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) + // 设置数据库的版本,入参为大于0的整数 + rdbStore.version = 3 + } + + // 当数据库存在并假定版本为1时,例应用从某一版本升级到当前版本,数据库需要从1版本升级到2版本 + if (rdbStore.version != 3 && rdbStore.version == 1) { + // version = 1:表结构:student (id, age) => version = 2:表结构:student (id, age, score) + rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) + rdbStore.version = 2 + } + + // 当数据库存在并假定版本为2时,例应用从某一版本升级到当前版本,数据库需要从2版本升级到3版本 + if (rdbStore.version != 3 && rdbStore.version == 2) { + // version = 2:表结构:student (id, age, score) => version = 3:表结构:student (id, score) + rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) + rdbStore.version = 3 + } }) ``` Stage模型示例: ```ts import data_rdb from '@ohos.data.relationalStore' - // 获取context - import UIAbility from '@ohos.app.ability.UIAbility'; - let context = null + import UIAbility from '@ohos.app.ability.UIAbility' + class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { - context = this.context + const STORE_CONFIG = { + name: "rdbstore.db", + securityLevel: data_rdb.SecurityLevel.S1 + } + + // 假设当前数据库版本为3 + data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + // 当数据库创建时,数据库默认版本为0 + if (rdbStore.version == 0) { + rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) + // 设置数据库的版本,入参为大于0的整数 + rdbStore.version = 3 + } + + // 当数据库存在并假定版本为1时,例应用从某一版本升级到当前版本,数据库需要从1版本升级到2版本 + if (rdbStore.version != 3 && rdbStore.version == 1) { + // version = 1:表结构:student (id, age) => version = 2:表结构:student (id, age, score) + rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) + rdbStore.version = 2 + } + + // 当数据库存在并假定版本为2时,例应用从某一版本升级到当前版本,数据库需要从2版本升级到3版本 + if (rdbStore.version != 3 && rdbStore.version == 2) { + // version = 2:表结构:student (id, age, score) => version = 3:表结构:student (id, score) + rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) + rdbStore.version = 3 + } + }) } } - - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - - const STORE_CONFIG = { name: "rdbstore.db", - securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - rdbStore.executeSql(CREATE_TABLE_TEST) - console.info('create table done.') - }) ``` 2. 插入数据。 @@ -384,14 +422,13 @@ 8. 远程查询。 - (1) 构造用于查询分布式表的谓词对象,指定组网内的远程分布式表名和设备。 (2) 调用结果集接口,返回查询结果。 示例代码如下: - - ```js + + ```js let rdbPredicate = new data_rdb.RdbPredicates('employee') predicates.greaterThan("id", 0) let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) @@ -406,36 +443,41 @@ }).catch((err) => { console.info("failed to remoteQuery, err: " + err) }) - ``` - + ``` + 9. 数据库的备份和恢复。 (1) 调用数据库的备份接口,备份当前数据库文件。 - 示例代码如下: + 示例代码如下: - ```js + ```js let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(() => { - console.info('Backup success.') + console.info('Backup success.') }).catch((err) => { - console.info('Backup failed, err: ' + err) + console.info('Backup failed, err: ' + err) }) - ``` - (2) 调用数据库的恢复接口,从数据库的备份文件恢复数据库文件。 + ``` - 示例代码如下: + (2) 调用数据库的恢复接口,从数据库的备份文件恢复数据库文件。 - ```js + 示例代码如下: + + ```js let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { - console.info('Restore success.') + console.info('Restore success.') }).catch((err) => { - console.info('Restore failed, err: ' + err) + console.info('Restore failed, err: ' + err) }) - ``` + ``` ## 相关实例 针对关系型数据库开发,有以下相关实例可供参考: + - [`DistributedRdb`:分布式关系型数据库(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedRdb) -- [关系型数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) \ No newline at end of file + +- [关系型数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) + +- [关系型数据库(ArkS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Data/Rdb) \ No newline at end of file diff --git a/zh-cn/application-dev/device/pointerstyle-guidelines.md b/zh-cn/application-dev/device/pointerstyle-guidelines.md index cc5f3fd52ed14efacfad961345635e7588f9f8ac..997f375bd75be6272929213058fe51a38a23a468 100644 --- a/zh-cn/application-dev/device/pointerstyle-guidelines.md +++ b/zh-cn/application-dev/device/pointerstyle-guidelines.md @@ -17,8 +17,8 @@ import pointer from '@ohos.multimodalInput.pointer'; | 实例名 | 接口名 | 说明 | | ------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | pointer | function isPointerVisible(callback: AsyncCallback\): void; | 获取鼠标指针显示或隐藏状态。 | -| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\): void; | 设置鼠标指针显示或隐藏状态,改接口会影响全局鼠标光标的显示状态。 | -| pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\): void; | 设置鼠标光标样式,改接口会影响指定窗口鼠标光标样式。 | +| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\): void; | 设置鼠标指针显示或隐藏状态,该接口会影响全局鼠标光标的显示状态。 | +| pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\): void; | 设置鼠标光标样式,该接口会影响指定窗口鼠标光标样式。 | | pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\): void; | 查询鼠标光标样式。 | ## 设置鼠标光标隐藏 diff --git a/zh-cn/application-dev/dfx/errormanager-guidelines.md b/zh-cn/application-dev/dfx/errormanager-guidelines.md index 8a588efc18d0798d1b10a24ee43d730960309abb..003b0c2107a00c3e2a4c52108dccddc04791fb50 100644 --- a/zh-cn/application-dev/dfx/errormanager-guidelines.md +++ b/zh-cn/application-dev/dfx/errormanager-guidelines.md @@ -39,8 +39,8 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import errorManager from '@ohos.app.ability.errorManager'; -var registerId = -1; -var callback = { +let registerId = -1; +let callback = { onUnhandledException: function (errMsg) { console.log(errMsg); } @@ -49,13 +49,13 @@ var callback = { export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log("[Demo] EntryAbility onCreate") - registerId = errorManager.registerErrorObserver(callback); + registerId = errorManager.on("error", callback); globalThis.abilityWant = want; } onDestroy() { console.log("[Demo] EntryAbility onDestroy") - errorManager.unregisterErrorObserver(registerId, (result) => { + errorManager.off("error", registerId, (result) => { console.log("[Demo] result " + result.code + ";" + result.message) }); } diff --git a/zh-cn/application-dev/media/image.md b/zh-cn/application-dev/media/image.md index e4050515a516db43743a58b56a72705a1fb3c44b..7a3ba2c76e9da06f5500e6a8b64366942dff0e6f 100644 --- a/zh-cn/application-dev/media/image.md +++ b/zh-cn/application-dev/media/image.md @@ -286,5 +286,6 @@ public async init(surfaceId: any) { 针对图片开发,有以下相关实例可供参考: -- [`Image`:图片处理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Image) +- [`Image`:图片处理(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Image) + - [`GamePuzzle`:拼图(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/GamePuzzle) \ No newline at end of file diff --git a/zh-cn/application-dev/media/video-playback.md b/zh-cn/application-dev/media/video-playback.md index ea6044a54b0774ebd6954839a29b931874e0558a..7f8586dede5e4700319f05928c4e3666663f1351 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -452,4 +452,4 @@ export class VideoPlayerDemo { 针对视频播放开发,有以下相关实例可供参考: - [`VideoPlayer:`视频播放(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/VideoPlayer) -- [视频播放器(ArkTS)(API 9)](https://gitee.com/openharmony/codelabs/tree/master/Media/VideoPlayerStage) \ No newline at end of file +- [视频播放器(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/VideoPlayerStage) \ No newline at end of file diff --git a/zh-cn/application-dev/notification/notification-overview.md b/zh-cn/application-dev/notification/notification-overview.md index 52b4b5881588c37c7d449a235d2446b8d739b955..50525376aabb0a39bae6b303bd3fb29c7a84c3bf 100644 --- a/zh-cn/application-dev/notification/notification-overview.md +++ b/zh-cn/application-dev/notification/notification-overview.md @@ -25,3 +25,11 @@ OpenHarmony通过ANS(Advanced Notification Service,通知系统服务)对 系统应用还支持通知相关配置,如使能开关、配置参数由系统配置发起请求,发送到通知子系统存储到内存和数据库。 ![zh-cn_image_0000001466582017](figures/zh-cn_image_0000001466582017.png) + +## 相关实例 + +基于通知的开发,有以下相关实例可供参考: + +- [`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 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 9d0df149ac85a5a8fd4ae0fba6841f1486080796..cdbdf0668e836a5419d9daebb7e72b8781bb5b6d 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 @@ -41,7 +41,7 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\) ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbility( { want: @@ -94,7 +94,7 @@ startAbility(parameter: StartAbilityParameter): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbility( { want: @@ -174,7 +174,7 @@ startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbilityForResult( { want: @@ -225,7 +225,7 @@ startAbilityForResult(parameter: StartAbilityParameter): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbilityForResult( { want: @@ -276,7 +276,7 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.terminateSelfWithResult( { resultCode: 1, @@ -333,7 +333,7 @@ terminateSelfWithResult(parameter: AbilityResult): Promise\ ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.terminateSelfWithResult( { resultCode: 1, @@ -745,8 +745,8 @@ featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED | ---------------------------------------- | ---- | ---------------------------------------- | | WINDOW_MODE_UNDEFINED7+ | 0 | 未定义。 | | WINDOW_MODE_FULLSCREEN7+ | 1 | 全屏。 | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | 分屏主屏。 | -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | 分屏次屏。 | +| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | 屏幕如果是水平方向表示左分屏,屏幕如果是竖直方向表示上分屏。 | +| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | 屏幕如果是水平方向表示右分屏,屏幕如果是竖直方向表示下分屏。 | | WINDOW_MODE_FLOATING7+ | 102 | 悬浮窗。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index d88507db221bc0c7ca65c949ec216c45c3ba0155..2a75a19e7ffee7e93200d0b37f0dacaf3db95bde 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -116,8 +116,8 @@ class MyAbility extends UIAbility { | --- | --- | --- | | WINDOW_MODE_UNDEFINED | 0 | 未定义窗口模式。 | | WINDOW_MODE_FULLSCREEN | 1 | 全屏模式。 | -| WINDOW_MODE_SPLIT_PRIMARY | 100 | 分屏多窗口主要模式。 | -| WINDOW_MODE_SPLIT_SECONDARY | 101 | 分屏多窗口次要模式。 | +| WINDOW_MODE_SPLIT_PRIMARY | 100 | 屏幕如果是水平方向表示左分屏,屏幕如果是竖直方向表示上分屏。 | +| WINDOW_MODE_SPLIT_SECONDARY | 101 | 屏幕如果是水平方向表示右分屏,屏幕如果是竖直方向表示下分屏。 | | WINDOW_MODE_FLOATING | 102 | 自由悬浮形式窗口模式。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md index 0a958c87ae5f3de3874043ec71a0b488cf9fdebc..683437d8aa022a04328e93b79574a5c94a76d028 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -1,25 +1,19 @@ # @ohos.app.ability.Configuration (Configuration) -定义环境变化信息。 +定义环境变化信息。Configuration是接口定义,仅做字段声明。 > **说明:** > > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -## 导入模块 - -```ts -import Configuration from '@ohos.app.ability.Configuration'; -``` - **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | language | string | 是 | 是 | 表示应用程序的当前语言。例如:zh。 | -| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | -| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | -| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | +| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:未设置(COLOR_MODE_NOT_SET),浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | +| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | 是 | 否 | 表示屏幕方向,取值范围:未设置(DIRECTION_NOT_SET),水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | +| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 是 | 否 | 表示屏幕分辨率,取值范围:未设置(SCREEN_DENSITY_NOT_SET),SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | | displayId | number | 是 | 否 | 表示应用所在的物理屏幕Id。 | | hasPointerDevice | boolean | 是 | 否 | 指示指针类型设备是否已连接,如键鼠、触控板等。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 9df1b173df66e5bb8e3a446e1a1305fd093275f6..a58d8d2c9e611d89a710460086710c2a47a7613b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -80,7 +80,7 @@ Extension生命周期回调,在销毁时回调,执行资源清理等操作 onRequest(want: Want, startId: number): void; -Extension生命周期回调,如果是startAbility拉起的服务,会在onCreate之后回调。每次拉起服务都会回调,startId会递增。 +Extension生命周期回调,如果是startAbility或者startServiceExtensionAbility拉起的服务,会在onCreate之后回调。每次拉起服务都会回调,startId会递增。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core 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 feaf6b09cf505a4292407b802543148db9e27fbf..21b53ffa610f263a90f41bc1be77780d64c18ac2 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 @@ -24,3 +24,32 @@ import StartOptions from '@ohos.app.ability.StartOptions'; | -------- | -------- | -------- | -------- | | [windowMode](js-apis-app-ability-abilityConstant.md#abilityconstantwindowmode) | number | 否 | 窗口模式。 | | displayId | number | 否 | 屏幕ID。默认是0,表示当前屏幕。 | + +**示例:** + + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + let id = missions[0].missionId; + + let startOptions = { + windowMode : 101, + displayId: 0 + }; + missionManager.moveMissionToFront(id, startOptions).then(() => { + console.log("moveMissionToFront is called "); + }); + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` 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 35c5597515c132ed5662aad69b159288ce542c25..c6a282f6ed3676297c7475fa681b57ffb2257a26 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 @@ -363,7 +363,7 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; var caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ + this.context.startAbilityByCall({ bundleName: "com.example.myservice", abilityName: "MainUIAbility", deviceId: "" @@ -444,7 +444,7 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa var caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ + this.context.startAbilityByCall({ bundleName: "com.example.myservice", abilityName: "MainUIAbility", deviceId: "" @@ -493,7 +493,7 @@ release(): void; var caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ + this.context.startAbilityByCall({ bundleName: "com.example.myservice", abilityName: "MainUIAbility", deviceId: "" @@ -533,7 +533,7 @@ release(): void; var caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ + this.context.startAbilityByCall({ bundleName: "com.example.myservice", abilityName: "MainUIAbility", deviceId: "" @@ -544,7 +544,7 @@ release(): void; console.log(' Caller OnRelease CallBack is called ' + str); }); } catch (error) { - console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + console.log('Caller.onRelease catch error, error.code: ' + JSON.stringify(error.code) + ' error.message: ' + JSON.stringify(error.message)); } }).catch((err) => { @@ -584,7 +584,7 @@ release(): void; var caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ + this.context.startAbilityByCall({ bundleName: "com.example.myservice", abilityName: "MainUIAbility", deviceId: "" @@ -606,6 +606,108 @@ release(): void; } ``` +## Caller.off + +off(type: "release", callback: OnReleaseCallback): void; + +取消注册通用组件服务端Stub(桩)断开监听通知。预留能力,当前暂未支持。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 监听releaseCall事件,固定为'release'。 | +| callback | [OnReleaseCallBack](#onreleasecallback) | 是 | 返回off回调结果。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +其他ID见[元能力子系统错误码](../errorcodes/errorcode-ability.md) + +**示例:** + + ```ts + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + let onReleaseCallBack = (str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }; + caller.on("release", onReleaseCallBack); + caller.off("release", onReleaseCallBack); + } catch (error) { + console.log('Caller.on or Caller.off catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + +## Caller.off + +off(type: "release"): void; + +取消注册通用组件服务端Stub(桩)断开监听通知。预留能力,当前暂未支持。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 监听releaseCall事件,固定为'release'。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +其他ID见[元能力子系统错误码](../errorcodes/errorcode-ability.md) + +**示例:** + + ```ts + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + let onReleaseCallBack = (str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }; + caller.on("release", onReleaseCallBack); + caller.off("release"); + } catch (error) { + console.error('Caller.on or Caller.off catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.error('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` ## Callee diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md index f6a99d431dbf0d43482dee2b200d536a009c1845..f28cc3d3b96e3bb499871978735187439686d8c4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md @@ -26,7 +26,7 @@ import Want from '@ohos.app.ability.Want'; | [entities](js-apis-app-ability-wantConstant.md#wantConstant.Entity) | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 | | uri | string | 否 | 表示携带的数据,一般配合type使用,指明待处理的数据类型。如果在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。 | -| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
- ohos.aafwk.callerPid:表示拉起方的pid。
- ohos.aafwk.param.callerToken:表示拉起方的token。
- ohos.aafwk.param.callerUid:表示[BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | +| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
- ohos.aafwk.callerPid:表示拉起方的pid。
- ohos.aafwk.param.callerToken:表示拉起方的token。
- ohos.aafwk.param.callerUid:表示[BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。
- component.startup.newRules:表示是否启用新的管控规则。
- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。
- ohos.dlp.params.sandbox:表示dlp文件才会有。 | | [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | 否 | 表示处理Want的方式。默认传数字。
例如通过wantConstant.Flags.FLAG_ABILITY_CONTINUATION表示是否以设备间迁移方式启动Ability。 | **示例:** @@ -122,7 +122,7 @@ import Want from '@ohos.app.ability.Want'; "abilityName": "FuncAbility", "moduleName": "entry", // moduleName非必选 "parameters": { - "keyFd":{"type":"FD", "value":fd} + "keyFd":{"type":"FD", "value":fd} // {"type":"FD", "value":fd}是固定用法,用于表示该数据是FD } }; this.context.startAbility(want, (error) => { 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 cf1636ce99912c031e86fdfb0b9e627f9f069388..4eedf15f0260de523570ff3fe237e36a648cc9c2 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 @@ -92,13 +92,13 @@ function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(err)); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); } ``` @@ -701,7 +701,7 @@ function getWantAgentCallback(err, data) { } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); } - //getUid回调 + //getWant回调 function getWantCallback(err, data) { if(err) { console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); @@ -710,7 +710,7 @@ function getWantAgentCallback(err, data) { } } try { - WantAgent.getWant(wantAgent, getBundleNameCallback); + WantAgent.getWant(wantAgent, getWantCallback); } catch(err) { console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } @@ -914,7 +914,7 @@ function getWantAgentCallback(err, data) { } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); } - //getUid回调 + //cancel回调 function cancelCallback(err, data) { if(err) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); @@ -923,7 +923,7 @@ function getWantAgentCallback(err, data) { } } try { - WantAgent.cancel(wantAgent, getBundleNameCallback); + WantAgent.cancel(wantAgent, cancelCallback); } catch(err) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } @@ -1128,7 +1128,7 @@ function getWantAgentCallback(err, data) { } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); } - //getUid回调 + //trigger回调 function triggerCallback(err, data) { if(err) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); @@ -1236,7 +1236,7 @@ function getWantAgentCallback(err, data) { } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); } - //getUid回调 + //equal回调 function equalCallback(err, data) { if(err) { console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); @@ -1448,7 +1448,7 @@ function getWantAgentCallback(err, data) { } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); } - //getUid回调 + //getOperationTypeCallback回调 function getOperationTypeCallback(err, data) { if(err) { console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); @@ -1457,7 +1457,7 @@ function getWantAgentCallback(err, data) { } } try { - WantAgent.getOperationTypeCallback(wantAgent, getBundleNameCallback); + WantAgent.getOperationTypeCallback(wantAgent, getOperationTypeCallback); } catch(err) { console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } @@ -1615,6 +1615,6 @@ try { | info | WantAgent | 是 | 触发的wantAgent。 | | want | Want | 是 | 存在的被触发的want。 | | finalCode | number | 是 | 触发wantAgent的请求代码。| -| finalData | string | 否 | 公共事件收集的最终数据。 | +| finalData | string | 是 | 公共事件收集的最终数据。 | | extraInfo | {[key: string]: any} | 否 | 额外数据。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md deleted file mode 100644 index a06734ef9ea765877b0f50e6ee64b2fbef03547f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ /dev/null @@ -1,115 +0,0 @@ -# @ohos.application.AbilityConstant (AbilityConstant) - -AbilityConstant提供Ability相关的枚举,包括设置初次启动原因、上次退出原因、迁移结果、窗口类型等。 - -> **说明:** -> -> 本模块首批接口从API version 9开始支持,从API version 9后续版本废弃,替换模块为[@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md)。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 - -## 导入模块 - -```ts -import AbilityConstant from '@ohos.application.AbilityConstant'; -``` - -## 属性 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| launchReason | [LaunchReason](#abilityconstantlaunchreason)| 是 | 是 | 指示启动原因。 | -| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | 是 | 是 | 表示最后退出原因。 | - -## AbilityConstant.LaunchReason - -初次启动原因。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | 未知的状态。 | -| START_ABILITY | 1 | 启动能力。 | -| CALL | 2 | 呼叫。 | -| CONTINUATION | 3 | 继续。 | -| APP_RECOVERY | 4 | 状态恢复。 | - - -## AbilityConstant.LastExitReason - -上次退出原因。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | 未知的状态。 | -| ABILITY_NOT_RESPONDING | 1 | 能力没有反应 | -| NORMAL | 2 | 正常的状态。 | - - -## AbilityConstant.OnContinueResult - -迁移结果。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| AGREE | 0 | 同意。 | -| REJECT | 1 | 拒绝。 | -| MISMATCH | 2 | 不匹配。| - -## AbilityConstant.WindowMode - -启动Ability时的窗口模式。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| --- | --- | --- | -| WINDOW_MODE_UNDEFINED | 0 | 未定义窗口模式。 | -| WINDOW_MODE_FULLSCREEN | 1 | 全屏模式。 | -| WINDOW_MODE_SPLIT_PRIMARY | 100 | 分屏多窗口主要模式。 | -| WINDOW_MODE_SPLIT_SECONDARY | 101 | 分屏多窗口次要模式。 | -| WINDOW_MODE_FLOATING | 102 | 自由悬浮形式窗口模式。 | - -## AbilityConstant.MemoryLevel - -内存级别的类型。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| --- | --- | --- | -| MEMORY_LEVEL_MODERATE | 0 | 内存占用适中。 | -| MEMORY_LEVEL_LOW | 1 | 内存占用低。 | -| MEMORY_LEVEL_CRITICAL | 2 | 内存占用高。 | - -## AbilityConstant.OnSaveResult - -保存应用数据的结果。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| ALL_AGREE | 0 | 同意保存状态。 | -| CONTINUATION_REJECT | 1 | 拒绝迁移保存状态。 | -| CONTINUATION_MISMATCH | 2 | 迁移不匹配。| -| RECOVERY_AGREE | 3 | 同意恢复保存状态。 | -| RECOVERY_REJECT | 4 | 拒绝恢复保存状态。| -| ALL_REJECT | 5 | 拒绝保存状态。| - -## AbilityConstant.StateType - -保存应用数据场景原因。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| CONTINUATION | 0 | 迁移保存状态。 | -| APP_RECOVERY | 1 | 应用恢复保存状态。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index 4d5b2ba0d9be7c4f01f700de31c1895fc9b5f70b..c776ad0b8b2ce35ebd4e83d1b36660edb9c58210 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,6 +1,6 @@ # @ohos.application.abilityDelegatorRegistry (AbilityDelegatorRegistry) -AbilityDelegatorRegistry模块提供用于存储已注册的AbilityDelegator和AbilityDelegatorArgs对象的全局寄存器的能力,包括获取应用程序的AbilityDelegator对象、获取单元测试参数AbilityDelegatorArgs对象。 +AbilityDelegatorRegistry模块提供用于存储已注册的AbilityDelegator和AbilityDelegatorArgs对象的全局寄存器的能力,包括获取应用程序的AbilityDelegator对象、获取单元测试参数AbilityDelegatorArgs对象。该模块中的接口只能用于测试框架中。 > **说明:** > diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md index f10bf6565e5fded4a7f9a447c23de17bf7d7cec4..23fdbd6b920d84212fbef244a8db5729b832cec4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -142,111 +142,4 @@ abilityManager.getAbilityRunningInfos().then((data) => { }).catch((err) => { console.log("getAbilityRunningInfos err: " + err) }); -``` - -## getExtensionRunningInfos9+ - -getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void - -获取关于运行扩展能力的信息(callback形式)。 - -**需要权限**: ohos.permission.GET_RUNNING_INFO - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -**参数**: - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | 是 | 获取消息数量的最大限制。 | -| callback | AsyncCallback\> | 是 | 被指定的回调方法。 | - -**示例**: - -```ts -var upperLimit = 0; - -abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); -}); -``` - -## getExtensionRunningInfos9+ - -getExtensionRunningInfos(upperLimit: number): Promise\> - -获取关于运行扩展能力的信息(Promise形式)。 - -**需要权限**: ohos.permission.GET_RUNNING_INFO - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -**参数**: - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | 是 | 获取消息数量的最大限制。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------- | ------- | -| Promise\> | 返回执行结果。 | - -**示例**: - -```ts -var upperLimit = 0; - -abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); -}).catch((err) => { - console.log("getAbilityRunningInfos err: " + err); -}) -``` - -## getTopAbility9+ - -getTopAbility(callback: AsyncCallback\): void; - -获取窗口焦点的ability接口(callback形式)。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -**参数**: - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | 被指定的回调方法。 | - -**示例**: - -```ts -abilityManager.getTopAbility((err,data) => { - console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); -}); -``` - -## getTopAbility9+ - -getTopAbility(): Promise\; - -获取窗口焦点的ability接口(Promise形式)。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------- | ------- | -| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| 返回执行结果。 | - -**示例**: - -```ts -abilityManager.getTopAbility().then((data) => { - console.log("getTopAbility data: " + JSON.stringify(data)); -}).catch((err) => { - console.log("getTopAbility err: " + err); -}) ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityStage.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityStage.md deleted file mode 100644 index 4717cc9388c56c7d4eeede9bbf0cdb2fdcf4fc7c..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityStage.md +++ /dev/null @@ -1,127 +0,0 @@ -# @ohos.application.AbilityStage (AbilityStage) - -AbilityStage是HAP的运行时类。 - -AbilityStage模块提供在HAP加载的时候,通知开发者,可以在此进行该HAP的初始化(如资源预加载,线程创建等)能力。 - -> **说明:** -> -> 本模块首批接口从API version 9 开始支持, 从API version 9废弃,替换模块为[@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md)。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 - -## 导入模块 - -```ts -import AbilityStage from '@ohos.application.AbilityStage'; -``` - -## AbilityStage.onCreate - -onCreate(): void - -当应用创建时调用。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**示例:** - - ```ts - class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage.onCreate is called") - } - } - ``` - - -## AbilityStage.onAcceptWant - -onAcceptWant(want: Want): string; - -启动一个specified ability时触发的事件。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | 是 | Want类型参数,传入需要启动的UIAbility的信息,如Ability名称,Bundle名称等。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| string | 用户返回一个UIAbility标识,如果之前启动过标识的UIAbility实例,不创建新的实例并拉回栈顶,否则创建新的实例并启动。 | - -**示例:** - - ```ts - class MyAbilityStage extends AbilityStage { - onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; - } - } - ``` - - -## AbilityStage.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -环境变化通知接口,发生全局配置变更时回调。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | 是 | 发生全局配置变更时触发回调,当前全局配置包括系统语言、深浅色模式。 | - -**示例:** - - ```ts - class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, language:' + config.language); - } - } - ``` - -## AbilityStage.onMemoryLevel - -onMemoryLevel(level: AbilityConstant.MemoryLevel): void; - -当系统已决定调整内存时调用。例如,当该功能在后台运行时,没有足够的内存来运行尽可能多的后台进程时可以使用。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | 是 | 回调返回内存微调级别,显示当前内存使用状态。| - -**示例:** - - ```ts - class MyAbilityStage extends AbilityStage { - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` - -## AbilityStage.context - -context: AbilityStageContext; - -AbilityStage的上下文对象。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -| 属性名 | 类型 | 说明 | -| ------- | ------------------------------------------------------------ | -------------------------- | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | AbilityStage的上下文对象。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md index 6ca4eff83fa5a83388d6d05299e122b62ef3e8ce..13ca6fa50ff4b962fb4b32c943cf9c89d88ab961 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-appManager.md @@ -30,7 +30,7 @@ static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void ```ts appManager.isRunningInStabilityTest((err, flag) => { - console.log('error:' + JSON.stringfy(err)); + console.log('error:' + JSON.stringify(err)); console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); }) ``` @@ -120,7 +120,7 @@ getAppMemorySize(): Promise\; | 类型 | 说明 | | -------- | -------- | - | Promise<number> | 应用程序内存大小。 | + | Promise<number> | 应用程序内存大小, 单位为M。 | **示例:** @@ -144,7 +144,7 @@ getAppMemorySize(callback: AsyncCallback\): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | 是 | 应用程序内存大小。 | + | callback | AsyncCallback<number> | 是 | 应用程序内存大小, 单位为M。 | **示例:** @@ -632,32 +632,4 @@ clearUpApplicationData(bundleName: string): Promise\; .catch((err) => { console.log('------------ clearUpApplicationData fail ------------', err); }) - ``` - -## ApplicationState9+ - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -| 名称 | 值 | 说明 | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | 当应用在创建中的时候处于的状态。 | -| STATE_FOREGROUND | 2 | 当应用切换到前台的时候处于的状态。 | -| STATE_ACTIVE | 3 | 当应用在获焦的时候处于的状态。 | -| STATE_BACKGROUND | 4 | 当应用处于后台不可见时处于的状态。 | -| STATE_DESTROY | 5 | 当应用在销毁的时候处于的状态。 | - -## ProcessState9+ - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -| 名称 | 值 | 说明 | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | 当进程在创建中的时候处于的状态。 | -| STATE_FOREGROUND | 2 | 当进程切换到前台的时候处于的状态。 | -| STATE_ACTIVE | 3 | 当进程在获焦的时候处于的状态。 | -| STATE_BACKGROUND | 4 | 当进程处于后台不可见时处于的状态。 | -| STATE_DESTROY | 5 | 当进程在销毁的时候处于的状态。 | \ No newline at end of file + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md index 3c845b46dec3e12eff340ca44185e2faf116bb58..bb877521aa7fa69441f96bc126607986bd4772bc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @@ -1,27 +1,17 @@ # @ohos.application.Configuration (Configuration) -定义环境变化信息。 +定义环境变化信息。Configuration是接口定义,仅做字段声明。 > **说明:** > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块从API version 9废弃,替换模块为[@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md) -## 导入模块 - -```ts -import Configuration from '@ohos.application.Configuration' -``` - **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | language8+ | string | 是 | 是 | 表示应用程序的当前语言。例如:zh。 | | colorMode8+ | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | -| direction9+ | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | -| screenDensity9+ | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | -| displayId9+ | number | 是 | 否 | 表示应用所在的物理屏幕Id。 | -| hasPointerDevice9+ | boolean | 是 | 否 | 指示指针类型设备是否已连接,如键鼠、触控板等。 | 具体字段描述参考ohos.application.Configuration.d.ts文件 @@ -44,10 +34,6 @@ export default class EntryAbility extends UIAbility { console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) let language = config.language; let colorMode = config.colorMode; - let direction = config.direction; - let screenDensity = config.screenDensity; - let displayId = config.displayId; - let hasPointerDevice = config.hasPointerDevice; } }; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md b/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md index f7908e521cbbe805352a7c305f00340ce8e9be20..43c5dd975a8ccf19622bfae531774001f2199f0e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -24,32 +24,3 @@ import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; | COLOR_MODE_DARK | 0 | 深色模式。 | | COLOR_MODE_LIGHT | 1 | 浅色模式。 | - -## ConfigurationConstant.Direction9+ - -使用时通过ConfigurationConstant.Direction获取。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| DIRECTION_NOT_SET | -1 | 未设置方向。 | -| DIRECTION_VERTICAL | 0 | 垂直方向。 | -| DIRECTION_HORIZONTAL | 1 | 水平方向。 | - - -## ConfigurationConstant.ScreenDensity9+ - -使用时通过ConfigurationConstant.ScreenDensity获取。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase - -| 名称 | 值 | 说明 | -| -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET | 0 | 未设置屏幕分辨率。 | -| SCREEN_DENSITY_SDPI | 120 | 屏幕分辨率为"sdpi"。 | -| SCREEN_DENSITY_MDPI | 160 | 屏幕分辨率为"mdpi"。 | -| SCREEN_DENSITY_LDPI | 240 | 屏幕分辨率为"ldpi"。 | -| SCREEN_DENSITY_XLDPI | 320 | 屏幕分辨率为"xldpi"。 | -| SCREEN_DENSITY_XXLDPI | 480 | 屏幕分辨率为"xxldpi"。 | -| SCREEN_DENSITY_XXXLDPI | 640 | 屏幕分辨率为"xxxldpi"。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-context.md b/zh-cn/application-dev/reference/apis/js-apis-application-context.md deleted file mode 100644 index c5253ad01b9b50bff483ae8f0ab7e7234f43dfd0..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-context.md +++ /dev/null @@ -1,41 +0,0 @@ -# @ohos.application.context (Context) - -Context模块将二级模块API组织在一起方便开发者进行导出。 - -> **说明:** -> -> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用 - -## 导入模块 - -```ts -import context from '@ohos.application.context' -``` - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase - -| 名称 | 读写属性 | 类型 | 必填 | 描述 | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| AbilityContext | 只读 | [AbilityContext](js-apis-ability-context.md) | 否 | AbilityContext二级模块。 | -| AbilityStageContext | 只读 | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | 否 | AbilityStageContext二级模块。 | -| ApplicationContext | 只读 | [ApplicationContext](js-apis-inner-application-applicationContext.md) | 否 | ApplicationContext二级模块。 | -| BaseContext | 只读 | [BaseContext](js-apis-inner-application-baseContext.md) | 否 | BaseContext二级模块。 | -| Context | 只读 | [Context](js-apis-inner-application-context.md) | 否 | Context二级模块。 | -| ExtensionContext | 只读 | [ExtensionContext](js-apis-inner-application-extensionContext.md) | 否 | ExtensionContext二级模块。 | -| FormExtensionContext | 只读 | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | 否 | FormExtensionContext二级模块。 | -| EventHub | 只读 | [EventHub](js-apis-inner-application-eventHub.md) | 否 | EventHub二级模块。 | -| PermissionRequestResult | 只读 | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | 否 | PermissionRequestResult二级模块。 | - -**示例:** -```ts -let abilityContext: context.AbilityContext; -let abilityStageContext: context.AbilityStageContext; -let applicationContext: context.ApplicationContext; -let baseContext: context.BaseContext; -let context: context.Context; -let extensionContext: context.ExtensionContext; -let formExtensionContext: context.FormExtensionContext; -let eventHub: context.EventHub; -let permissionRequestResult: context.PermissionRequestResult; -``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-extensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-extensionAbility.md deleted file mode 100644 index 807159d2145c83f533e8ea242820088d352f75ef..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-extensionAbility.md +++ /dev/null @@ -1,62 +0,0 @@ -# @ohos.application.ExtensionAbility (ExtensionAbility) - -ExtensionAbility模块提供对ExtensionAbility生命周期、上下文环境等调用管理的能力,包括ExtensionAbility创建、销毁、转储客户端信息等。 - -> **说明:** -> -> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 - -## 导入模块 - -```ts -import ExtensionAbility from '@ohos.application.ExtensionAbility'; -``` - -## ExtensionAbility.onConfigurationUpdated - -onConfigurationUpdated(newConfig: Configuration): void; - -当系统配置更新时调用。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | newConfig | [Configuration](js-apis-application-configuration.md) | 是 | 表示需要更新的配置信息。 | - -**示例:** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -## ExtensionAbility.onMemoryLevel - -onMemoryLevel(level: AbilityConstant.MemoryLevel): void; - -当系统已决定调整内存时调用。例如,当该功能在后台运行时,没有足够的内存来运行尽可能多的后台进程时可以使用。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | 是 | 回调返回内存微调级别,显示当前内存使用状态。| - -**示例:** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md deleted file mode 100644 index ea33780c83cc7194791dbbeff2841971c099068c..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md +++ /dev/null @@ -1,253 +0,0 @@ -# @ohos.application.ServiceExtensionAbility (ServiceExtensionAbility) - -ServiceExtensionAbility模块提供ServiceExtension服务扩展相关接口的能力。 - -> **说明:** -> -> 本模块首批接口从API version 9开始支持,从API version 9废弃,替换模块为[@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md)。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 - -## 导入模块 - -```ts -import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; -``` - -## 权限 - -无 - -## 属性 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | 是 | 否 | ServiceExtension的上下文环境,继承自ExtensionContext。 | - - -## ServiceExtensionAbility.onCreate - -onCreate(want: Want): void; - -Extension生命周期回调,在创建时回调,执行初始化业务逻辑操作。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - onCreate(want) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onDestroy - -onDestroy(): void; - -Extension生命周期回调,在销毁时回调,执行资源清理等操作。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## ServiceExtensionAbility.onRequest - -onRequest(want: Want, startId: number): void; - -Extension生命周期回调,如果是startAbility拉起的服务,会在onCreate之后回调。每次拉起服务都会回调,startId会递增。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | - | startId | number | 是 | 返回拉起次数。首次拉起初始值返回1,多次之后自动递增。 | - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - onRequest(want, startId) { - console.log('onRequest, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onConnect - -onConnect(want: Want): rpc.RemoteObject; - -Extension生命周期回调,如果是connectAbility拉起的服务,会在onCreate之后回调。返回一个RemoteObject对象,用于和客户端进行通信。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md)| 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | - -**返回值:** - - | 类型 | 说明 | - | -------- | -------- | - | rpc.RemoteObject | 一个RemoteObject对象,用于和客户端进行通信。 | - -**示例:** - - ```ts - import rpc from '@ohos.rpc' - class StubTest extends rpc.RemoteObject{ - constructor(des) { - super(des); - } - onConnect(code, data, reply, option) { - } - } - class ServiceExt extends ServiceExtension { - onConnect(want) { - console.log('onConnect , want:' + want.abilityName); - return new StubTest("test"); - } - } - ``` - - -## ServiceExtensionAbility.onDisconnect - -onDisconnect(want: Want): void; - -Extension的生命周期,断开服务连接时回调。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-want.md)| 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); - } - } - ``` - -## ServiceExtensionAbility.onReconnect - -onReconnect(want: Want): void; - -当新客户端在所有以前的客户端连接之后尝试连接到服务扩展时调用 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-want.md)| 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - onReconnect(want) { - console.log('onReconnect, want:' + want.abilityName); - } - } - ``` - -## ServiceExtensionAbility.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -当Extension更新配置信息时调用。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-application-configuration.md) | 是 | 表示需要更新的配置信息。 | - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -## ServiceExtensionAbility.dump - -dump(params: Array\): Array\; - -转储客户端信息时调用。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | params | Array\ | 是 | 表示命令形式的参数。| - -**示例:** - - ```ts - class ServiceExt extends ServiceExtension { - dump(params) { - console.log('dump, params:' + JSON.stringify(params)); - return ["params"] - } - } - ``` - diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-startOptions.md b/zh-cn/application-dev/reference/apis/js-apis-application-startOptions.md deleted file mode 100644 index 9f871ef8e00f2fc0129be0a2e3a468bd446e6d12..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-application-startOptions.md +++ /dev/null @@ -1,23 +0,0 @@ -# @ohos.application.StartOptions (StartOptions) - -StartOptions模块对系统的基本通信组件进行查询和设置的能力。 - -> **说明:** -> -> 本模块首批接口从API version 9 开始支持,从API version 9后续版本废弃,替换模块为[@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md)。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口仅可在Stage模型下使用。 - -## 导入模块 - -```ts -import StartOptions from '@ohos.application.StartOptions'; -``` - -## 属性 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | 否 | 窗口模式。 | -| displayId | number | 否 | 显示ID。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index e2481c7e2165fa819870b9bfbef9c28a09340f04..d0f20c015b2634014fb58d798197468c02c254bb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -31,12 +31,9 @@ onReceiveEvent(event: CommonEventData): void; **示例:** ```ts - var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") - { - onReceiveEvent(event){ - console.log('onReceiveEvent,event:' + event.code); - } - } - export default MyStaticSubscriberExtensionAbility - + class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log("onReceiveEvent, event: " + JSON.stringify(event)) + } + } ``` \ No newline at end of file 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 8ad2d331ceba9d768ccb249ce1f44b043e69b72e..fb8721cfc0a0afbffe42e8ef25d350af2c835989 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 @@ -4,7 +4,7 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 > **说明:** > -> 本模块首批接口从API version 8 开始支持,从API version 9废弃,替换模块为[Want](js-apis-app-ability-want.md)。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块首批接口从API version 8 开始支持,从API version 9废弃,替换模块为[@ohos.app.ability.Want](js-apis-app-ability-want.md)。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -25,7 +25,7 @@ import Want from '@ohos.application.Want'; | 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。 | +| 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)。 | | moduleName9+ | string | 否 | 表示待启动的Ability所属的模块(module)。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md index 49624d7f1f29fa28d5c81400b61388ecb6282b77..6013eb8cd4cf6ec626fd097fdedba537febb53d3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md +++ b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md @@ -84,7 +84,6 @@ import batteryInfo from '@ohos.batteryInfo'; | 名称 | 值 | 说明 | | -------------- | ------ | ---------------------------- | -| LEVEL_NONE | 0 | 表示电池电量等级未知。 | | LEVEL_FULL | 1 | 表示电池电量等级为满电量。 | | LEVEL_HIGH | 2 | 表示电池电量等级为高电量。 | | LEVEL_NORMAL | 3 | 表示电池电量等级为正常电量。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md index 9ad338c83c86b9ec5b04bf972fc4531e495077a8..f4d7e48663787ed4085aae8363ce98c32d8f0123 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -48,26 +48,21 @@ getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<Rd FA模型示例: ```js -// 获取context + import featureAbility from '@ohos.ability.featureAbility' + +// 获取context let context = featureAbility.getContext() -// 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1 } + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { if (err) { console.info("Get RdbStore failed, err: " + err) return - } - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return } console.log("Get RdbStore successfully.") }) @@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { Stage模型示例: ```ts -// 获取context -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 + } + + data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + if (err) { + console.info("Get RdbStore failed, err: " + err) + return + } + console.log("Get RdbStore successfully.") + }) } } - -// 获取context后调用getRdbStore -const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} -data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - if (err) { - console.info("Get RdbStore failed, err: " + err) - return - } - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return - } - console.log("Get RdbStore successfully.") -}) ``` ## data_rdb.getRdbStore @@ -143,24 +126,18 @@ getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> FA模型示例: ```js -// 获取context import featureAbility from '@ohos.ability.featureAbility' + +// 获取context let context = featureAbility.getContext() -// 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1 } + let promise = data_rdb.getRdbStore(context, STORE_CONFIG); promise.then(async (rdbStore) => { - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return - } console.log("Get RdbStore successfully.") }).catch((err) => { console.log("Get RdbStore failed, err: " + err) @@ -170,35 +147,23 @@ promise.then(async (rdbStore) => { Stage模型示例: ```ts -// 获取context -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 + } + + let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG); + promise.then(async (rdbStore) => { + console.log("Get RdbStore successfully.") + }).catch((err) => { + console.log("Get RdbStore failed, err: " + err) + }) } } - -// 获取context后调用getRdbStore -const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} -let promise = data_rdb.getRdbStore(context, STORE_CONFIG); -promise.then(async (rdbStore) => { - if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { - console.log("RdbStore status is ON_CREATE") - } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { - console.log("RdbStore status is ON_OPEN") - } else { - return - } - console.log("Get RdbStore successfully.") -}).catch((err) => { - console.log("Get RdbStore failed, err: " + err) -}) ``` ## data_rdb.deleteRdbStore @@ -230,11 +195,11 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void&g FA模型示例: ```js -// 获取context import featureAbility from '@ohos.ability.featureAbility' + +// 获取context let context = featureAbility.getContext() -// 获取context后调用deleteRdbStore data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { if (err) { console.info("Delete RdbStore failed, err: " + err) @@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { Stage模型示例: ```ts -// 获取context -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStore failed, err: " + err) + return + } + console.log("Delete RdbStore successfully.") + }) } } - -// 获取context后调用deleteRdbStore -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStore failed, err: " + err) - return - } - console.log("Delete RdbStore successfully.") -}) ``` ## data_rdb.deleteRdbStore @@ -302,11 +261,11 @@ deleteRdbStore(context: Context, name: string): Promise<void> FA模型示例: ```js -// 获取context import featureAbility from '@ohos.ability.featureAbility' + +// 获取context let context = featureAbility.getContext() -// 获取context后调用deleteRdbStore let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") promise.then(()=>{ console.log("Delete RdbStore successfully.") @@ -318,24 +277,18 @@ promise.then(()=>{ Stage模型示例: ```ts -// 获取context -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context; +import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ - context = this.context + let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") + promise.then(()=>{ + console.log("Delete RdbStore successfully.") + }).catch((err) => { + console.info("Delete RdbStore failed, err: " + err) + }) } } - -// 获取context后调用deleteRdbStore -let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ - console.log("Delete RdbStore successfully.") -}).catch((err) => { - console.info("Delete RdbStore failed, err: " + err) -}) ``` ## StoreConfig @@ -423,17 +376,6 @@ promise.then(()=>{ | ON_CONFLICT_IGNORE | 4 | 表示当冲突发生时,跳过包含违反约束的行并继续处理 SQL 语句的后续行。 | | ON_CONFLICT_REPLACE | 5 | 表示当冲突发生时,在插入或更新当前行之前删除导致约束违例的预先存在的行,并且命令会继续正常执行。 | -## OpenStatus10+ - -RdbStore的状态枚举。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -| 名称 | 值 | 说明 | -| --------- | ---- | --------------------------------------------------- | -| ON_CREATE | 0 | 表示RdbStore首次创建,处于ON_CREATE状态。 | -| ON_OPEN | 1 | 表示RdbStore非首次创建,处于ON_OPEN状态。 | - ## RdbPredicates 表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 @@ -1283,7 +1225,16 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) | 名称 | 类型 | 必填 | 说明 | | ------------ | ----------- | ---- | -------------------------------- | -| openStatus10+ | number | 是 | RdbStore的状态。值为0时,表示RdbStore首次创建,处于ON_CREATE状态。值为1时,表示RdbStore非首次创建,处于ON_OPEN状态。 | +| version10+ | number | 是 | 设置和获取数据库版本,值为大于0的正整数。 | + +**示例:** + +```js +// 设置数据库版本 +rdbStore.version = 3 +// 获取数据库版本 +console.info("Get RdbStore version is " + rdbStore.version) +``` ### insert diff --git a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md index f1bec7a514881cdee90afb7ab41d224b8ab661d5..73bec5e09525301cb9c639c6c6729cf1cacd97f3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md @@ -588,8 +588,9 @@ stopDeviceDiscovery(subscribeId: number): void **示例:** ```js - // 入参需要和startDeviceDiscovery接口传入的subscribeId配对使用 try { + // stopDeviceDiscovery和startDeviceDiscovery需配对使用,入参需要和startDeviceDiscovery接口传入的subscribeId值相等 + var subscribeId = 12345; dmInstance.stopDeviceDiscovery(subscribeId); } catch (err) { console.error("stopDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); @@ -630,7 +631,7 @@ publishDeviceDiscovery(publishInfo: PublishInfo): void "publishId": publishId, "mode": 0xAA, // 主动模式 "freq": 2, // 高频率 - "ranging": 1 // 支持发现时测距 + "ranging": true // 支持发现时测距 }; try { dmInstance.publishDeviceDiscovery(publishInfo); // 当有发布结果时,通过回调通知给应用程序 @@ -666,8 +667,9 @@ unPublishDeviceDiscovery(publishId: number): void **示例:** ```js - // 入参需要和publishDeviceDiscovery接口传入的publishId配对使用 try { + // unPublishDeviceDiscovery和publishDeviceDiscovery配对使用,入参需要和publishDeviceDiscovery接口传入的publishId值相等 + var publishId = 12345; dmInstance.unPublishDeviceDiscovery(publishId); } catch (err) { console.error("unPublishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); @@ -708,11 +710,19 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async var deviceInfo ={ "deviceId": "XXXXXXXX", "deviceName": "", - deviceType: 0x0E + "deviceType": 0x0E, + "networkId" : "xxxxxxx", + "range" : 0 }; + let extraInfo = { + 'targetPkgName': 'ohos.samples.xxx', + 'appName': 'xxx', + 'appDescription': 'xxx', + 'business': '0' + } let authParam = { - "authType": 1, // 认证类型: 1 - 无帐号PIN码认证 - "extraInfo": {} + 'authType': 1,// 认证类型: 1 - 无帐号PIN码认证 + 'extraInfo': extraInfo } try { dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { @@ -756,6 +766,13 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void ```js try { + var deviceInfo ={ + "deviceId": "XXXXXXXX", + "deviceName": "", + "deviceType": 0x0E, + "networkId" : "xxxxxxx", + "range" : 0 + }; dmInstance.unAuthenticateDevice(deviceInfo); } catch (err) { console.error("unAuthenticateDevice errCode:" + err.code + ",errMessage:" + err.message); @@ -792,7 +809,7 @@ verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, ```js let authInfo = { "authType": 1, - "token": xxxxxx, + "token": 123456, "extraInfo": {} } try { @@ -838,7 +855,7 @@ setUserOperation(operateAction: number, params: string): void; operateAction = 5 - pin码输入框确定操作 */ let operation = 0; - this.dmInstance.setUserOperation(operation, "extra") + dmInstance.setUserOperation(operation, "extra") } catch (err) { console.error("setUserOperation errCode:" + err.code + ",errMessage:" + err.message); } @@ -868,11 +885,8 @@ ui状态变更回调。 dmInstance.on('uiStateChange', (data) => { console.log("uiStateChange executed, dialog closed" + JSON.stringify(data)) var tmpStr = JSON.parse(data.param) - this.isShow = tmpStr.verifyFailed - console.log("uiStateChange executed, dialog closed" + this.isShow) - if (!this.isShow) { - this.destruction() - } + var isShow = tmpStr.verifyFailed + console.log("uiStateChange executed, dialog closed" + isShow) }); } catch (err) { console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); 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 9290088c53a09d04c8056fdb817d6ec80a373c99..3b61f968c98f5bd3ac708e912b8f39e7f776a029 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -2847,7 +2847,7 @@ try { ### get -get(key: string, callback: AsyncCallback): void +get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 获取指定键的值,使用callback异步回调。 @@ -2898,7 +2898,7 @@ try { ### get -get(key: string): Promise<boolean | string| number | Uint8Array> +get(key: string): Promise<boolean | string | number | Uint8Array> 获取指定键的值,使用Promise异步回调。 @@ -4849,7 +4849,7 @@ try { ### get -get(key: string, callback: AsyncCallback): void +get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 获取本设备指定键的值,使用callback异步回调。 @@ -4900,7 +4900,7 @@ try { ### get -get(key: string): Promise<boolean | string| number | Uint8Array> +get(key: string): Promise<boolean | string | number | Uint8Array> 获取本设备指定键的值,使用Promise异步回调。 @@ -4952,7 +4952,7 @@ try { ### get -get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void +get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 获取与指定设备ID和key匹配的string值,使用callback异步回调。 @@ -5004,7 +5004,7 @@ try { ### get -get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> +get(deviceId: string, key: string): Promise<boolean | string | number | Uint8Array> 获取与指定设备ID和key匹配的string值,使用Promise异步回调。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-environment.md b/zh-cn/application-dev/reference/apis/js-apis-file-environment.md index a3d891cf5660e8ece94b572669be80dd6f54a049..f6bb1c415116c14505e2cc211caa15e78c1ccc99 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-environment.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-environment.md @@ -30,9 +30,9 @@ getStorageDataDir():Promise<string> **示例:** ```js - environment.getStorageDataDir().then(function (path) { + environment.getStorageDataDir().then((path) => { console.info("getStorageDataDir successfully, Path: " + path); - }).catch(function (err) { + }).catch((err) => { console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -54,7 +54,7 @@ getStorageDataDir(callback:AsyncCallback<string>):void **示例:** ```js - environment.getStorageDataDir(function (error, path) { + environment.getStorageDataDir((err, path) => { if (err) { console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -80,9 +80,9 @@ getUserDataDir():Promise<string> **示例:** ```js - environment.getUserDataDir().then(function (path) { + environment.getUserDataDir().then((path) => { console.info("getUserDataDir successfully, Path: " + path); - }).catch(function (err) { + }).catch((err) => { console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -104,7 +104,7 @@ getUserDataDir(callback:AsyncCallback<string>): void **示例:** ```js - environment.getUserDataDir(function (err, path) { + environment.getUserDataDir((err, path) => { if (err) { console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code); } else { diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-fs.md b/zh-cn/application-dev/reference/apis/js-apis-file-fs.md index 0d4dce46885203594d419320d5aae0ff09208ad3..a0271c550005f13ed9f863c593649fa55da5d611 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-fs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-fs.md @@ -481,7 +481,7 @@ mkdirSync(path: string): void ## fs.open -open(path: string, flags?: number): Promise<File> +open(path: string, mode?: number): Promise<File> 打开文件,使用Promise异步回调。支持使用URI打开文件。 @@ -492,7 +492,7 @@ open(path: string, flags?: number): Promise<File> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | 是 | 文件的应用沙箱路径或文件URI。 | -| flags | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:
- OpenMode.READ_ONLY(0o0):只读打开。
- OpenMode.WRITE_ONLY(0o1):只写打开。
- OpenMode.READ_WRITE(0o2):读写打开。
给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:
- OpenMode.CREATE(0o100):若文件不存在,则创建文件。
- OpenMode.TRUNC(0o1000):如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。
- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- OpenMode.DIR(0o200000):如果path不指向目录,则出错。
- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。
- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | +| mode | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:
- OpenMode.READ_ONLY(0o0):只读打开。
- OpenMode.WRITE_ONLY(0o1):只写打开。
- OpenMode.READ_WRITE(0o2):读写打开。
给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:
- OpenMode.CREATE(0o100):若文件不存在,则创建文件。
- OpenMode.TRUNC(0o1000):如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。
- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- OpenMode.DIR(0o200000):如果path不指向目录,则出错。
- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。
- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | **返回值:** @@ -514,7 +514,7 @@ open(path: string, flags?: number): Promise<File> ## fs.open -open(path: string, flags?: number, callback: AsyncCallback<File>): void +open(path: string, mode?: number, callback: AsyncCallback<File>): void 打开文件,使用callback异步回调。支持使用URI打开文件。 @@ -525,7 +525,7 @@ open(path: string, flags?: number, callback: AsyncCallback<File>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 文件的应用沙箱路径或URI。 | -| flags | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:
- OpenMode.READ_ONLY(0o0):只读打开。
- OpenMode.WRITE_ONLY(0o1):只写打开。
- OpenMode.READ_WRITE(0o2):读写打开。
给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:
- OpenMode.CREATE(0o100):若文件不存在,则创建文件。
- OpenMode.TRUNC(0o1000):如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。
- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- OpenMode.DIR(0o200000):如果path不指向目录,则出错。
- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。
- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | +| mode | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:
- OpenMode.READ_ONLY(0o0):只读打开。
- OpenMode.WRITE_ONLY(0o1):只写打开。
- OpenMode.READ_WRITE(0o2):读写打开。
给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:
- OpenMode.CREATE(0o100):若文件不存在,则创建文件。
- OpenMode.TRUNC(0o1000):如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。
- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- OpenMode.DIR(0o200000):如果path不指向目录,则出错。
- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。
- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | **示例:** @@ -542,7 +542,7 @@ open(path: string, flags?: number, callback: AsyncCallback<File>): void ## fs.openSync -openSync(path: string, flags?: number): File +openSync(path: string, mode?: number): File 以同步方法打开文件。支持使用URI打开文件。 @@ -553,7 +553,7 @@ openSync(path: string, flags?: number): File | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | 是 | 打开文件的应用沙箱路径或URI。 | -| flags | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:
- OpenMode.READ_ONLY(0o0):只读打开。
- OpenMode.WRITE_ONLY(0o1):只写打开。
- OpenMode.READ_WRITE(0o2):读写打开。
给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:
- OpenMode.CREATE(0o100):若文件不存在,则创建文件。
- OpenMode.TRUNC(0o1000):如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。
- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- OpenMode.DIR(0o200000):如果path不指向目录,则出错。
- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。
- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | +| mode | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:
- OpenMode.READ_ONLY(0o0):只读打开。
- OpenMode.WRITE_ONLY(0o1):只写打开。
- OpenMode.READ_WRITE(0o2):读写打开。
给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:
- OpenMode.CREATE(0o100):若文件不存在,则创建文件。
- OpenMode.TRUNC(0o1000):如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。
- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- OpenMode.DIR(0o200000):如果path不指向目录,则出错。
- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。
- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-hash.md b/zh-cn/application-dev/reference/apis/js-apis-file-hash.md index 0405e3943eb4768af1a592889937b37796ba2cdd..a38e3189c58e52af35f5dae9a9ab3a7d136c1a7a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-hash.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-hash.md @@ -67,9 +67,9 @@ hash(path: string, algorithm: string): Promise<string> ```js let filePath = pathDir + "/test.txt"; - Hash.hash(filePath, "sha256").then(function (str) { + Hash.hash(filePath, "sha256").then((str) => { console.info("calculate file hash succeed:" + str); - }).catch(function (err) { + }).catch((err) => { console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -92,7 +92,7 @@ hash(path: string, algorithm: string, callback: AsyncCallback<string>): vo **示例:** ```js - Hash.hash(filePath, "sha256", function (err, str) { + Hash.hash(filePath, "sha256", (err, str) => { if (err) { console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); } else { diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md b/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md index 4d725ba3edf970a79ab274bfb9a3d9aac5f3decb..511211522f361c78bac6ceb98779fa216a3d5c6d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -66,9 +66,9 @@ setSecurityLabel(path:string, type:dataLevel):Promise<void> **示例:** ```js - securityLabel.setSecurityLabel(path, "s0").then(function () { + securityLabel.setSecurityLabel(path, "s0").then(() => { console.info("setSecurityLabel successfully"); - }).catch(function (err) { + }).catch((err) => { console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -92,7 +92,7 @@ setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void> **示例:** ```js - securityLabel.setSecurityLabel(path, "s0", function (err) { + securityLabel.setSecurityLabel(path, "s0", (err) => { if (err) { console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -145,9 +145,9 @@ getSecurityLabel(path:string):Promise<string> **示例:** ```js - securityLabel.getSecurityLabel(path).then(function (type) { + securityLabel.getSecurityLabel(path).then((type) => { console.log("getSecurityLabel successfully, Label: " + type); - }).catch(function (err) { + }).catch((err) => { console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -170,7 +170,7 @@ getSecurityLabel(path:string, callback:AsyncCallback<string>): void **示例:** ```js - securityLabel.getSecurityLabel(path, function (err, type) { + securityLabel.getSecurityLabel(path, (err, type) => { if (err) { console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); } else { diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-statvfs.md b/zh-cn/application-dev/reference/apis/js-apis-file-statvfs.md index 99b8602eef0638f89cb1f6d239a00b0893113df9..4922e899d6e91946b7c4435df269340d5ad017c8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-statvfs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-statvfs.md @@ -35,9 +35,9 @@ getFreeSize(path:string):Promise<number> ```js let path = "/dev"; - statfs.getFreeSize(path).then(function (number) { + statfs.getFreeSize(path).then((number) => { console.info("getFreeSize promise successfully, Size: " + number); - }).catch(function (err) { + }).catch((err) => { console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -61,7 +61,7 @@ getFreeSize(path:string, callback:AsyncCallback<number>): void ```js let path = "/dev"; - statfs.getFreeSize(path, function (err, number) { + statfs.getFreeSize(path, (err, number) => { if (err) { console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -94,9 +94,9 @@ getTotalSize(path: string): Promise<number> ```js let path = "/dev"; - statfs.getTotalSize(path).then(function (number) { + statfs.getTotalSize(path).then((number) => { console.info("getTotalSize promise successfully, Size: " + number); - }).catch(function (err) { + }).catch((err) => { console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -120,7 +120,7 @@ getTotalSize(path: string, callback: AsyncCallback<number>): void ```js let path = "/dev"; - statfs.getTotalSize(path, function(err, number) { + statfs.getTotalSize(path, (err, number) => { if (err) { console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); } else { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md index 8176bf1d9396389d698df23fd6d46d7767c3aca6..fa99cfe2bb037adcca104b0a3332da26c9456c37 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -10,3 +10,25 @@ | onDisconnect7+ | function | 是 | 断开连接时的回调函数。 | | onFailed7+ | function | 是 | 连接失败时的回调函数。 | +**示例:** + + ```ts + let want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + + let connectOptions = { + onConnect(elementName, remote) { + console.log('onConnect elementName: ' + elementName); + }, + onDisconnect(elementName) { + console.log('onDisconnect elementName: ' + elementName); + }, + onFailed(code) { + console.error('onFailed code: ' + code); + } + } + + let connection = this.context.connectAbility(want, connectOptions); + ``` \ 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 25fe8e84f6dc5cea8341a80a3ed85717d431b101..d15ffdfe503d482a78ee5a123f12bd433efe62da 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 @@ -4,7 +4,7 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 > **说明:** > -> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块首批接口从API version 6开始支持,从API version 9废弃,使用[@ohos.app.ability.Want](js-apis-app-ability-want.md)模块替代。后续版本的新增接口,采用上角标单独标记接口的起始版本。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase @@ -17,7 +17,7 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 | 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。 | +| 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)。 | | moduleName9+ | string | 否 | 表示待启动的Ability所属的模块(module)。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md index 065784e1a602dd45349871249de78927357a5fcd..13053095ec4607da64923e7427d4369e43db0df1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -19,9 +19,11 @@ import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getProcessInfo((err, data) => { - console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); - let pid = data.pid; - let processName = data.processName; + if (err.code != 0) { + console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + let pid = data.pid; + let processName = data.processName; + } }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index c5b4aae5a0e82d0bdccc8b93738baa8e59340e73..1224bc0b62dc439e42aa88edfc4dde577156bff2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -1,6 +1,6 @@ # AbilityStageContext -AbilityStageContext是AbilityStage的上下文环境,继承自[Context](js-apis-application-context.md)。 +AbilityStageContext是AbilityStage的上下文环境,继承自[Context](js-apis-inner-application-context.md)。 AbilityStageContext提供允许访问特定于abilityStage的资源的能力,包括获取AbilityStage对应的ModuleInfo对象、环境变化对象。 @@ -29,5 +29,5 @@ class MyAbilityStage extends AbilityStage { | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | 是 | 否 | AbilityStage对应的ModuleInfo对象。 | +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | 是 | 否 | AbilityStage对应的ModuleInfo对象。 | | config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 否 | 环境变化对象。 | 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 d4042cd5ebc208bed0b8e5c44fe702f4ebab469d..41dc3d57e5bd6782f1f8a2e32d27a6ddb41ab46e 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 @@ -15,9 +15,9 @@ ApplicationContext模块提供开发者应用级别的的上下文的能力, let applicationContext = this.context.getApplicationContext(); ``` -## ApplicationContext.registerAbilityLifecycleCallback +## ApplicationContext.on(type: "abilityLifecycle", callback: AbilityLifecycleCallback) -registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number**; +on(type: "abilityLifecycle", callback: AbilityLifecycleCallback): **number**; 注册监听应用内生命周期 @@ -27,6 +27,7 @@ registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number** | 参数名 | 类型 | 必填 | 说明 | | ------------------------ | -------- | ---- | ------------------------------ | +| type | "abilityLifecycle" | 是 | 监听事件的类型。 | | callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | 是 | 回调方法,返回注册监听事件的ID。 | **返回值:** @@ -47,49 +48,49 @@ export default class EntryAbility extends UIAbility { console.log("MyAbility onCreate") let AbilityLifecycleCallback = { onAbilityCreate(ability) { - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onAbilityCreate ability:" + ability); }, onWindowStageCreate(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + ability); + console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + windowStage); }, onWindowStageActive(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + console.log("AbilityLifecycleCallback onWindowStageActive ability:" + ability); + console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + windowStage); }, onWindowStageInactive(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + ability); + console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + windowStage); }, onWindowStageDestroy(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + ability); + console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + windowStage); }, onAbilityDestroy(ability) { - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + ability); }, onAbilityForeground(ability) { - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onAbilityForeground ability:" + ability); }, onAbilityBackground(ability) { - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onAbilityBackground ability:" + ability); }, onAbilityContinue(ability) { - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onAbilityContinue ability:" + ability); } } // 1.通过context属性获取applicationContext let applicationContext = this.context.getApplicationContext(); // 2.通过applicationContext注册监听应用内生命周期 - lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); + lifecycleId = applicationContext.on("abilityLifecycle", AbilityLifecycleCallback); console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); } } ``` -## ApplicationContext.unregisterAbilityLifecycleCallback +## ApplicationContext.off(type: "abilityLifecycle", callbackId: number, callback: AsyncCallback) -unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; +off(type: "abilityLifecycle", callbackId: **number**, callback: AsyncCallback<**void**>): **void**; 取消监听应用内生命周期 @@ -99,6 +100,7 @@ unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallb | 参数名 | 类型 | 必填 | 说明 | | ------------- | -------- | ---- | -------------------------- | +| type | "abilityLifecycle" | 是 | 取消监听事件的类型。 | | callbackId | number | 是 | 注册监听应用内生命周期的ID。 | | callback | AsyncCallback\ | 是 | 回调方法。 | @@ -112,17 +114,48 @@ var lifecycleId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("stage applicationContext: " + applicationContext); + applicationContext.off(type: "abilityLifecycle", lifecycleId, (error, data) => { console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); }); } } ``` -## ApplicationContext.registerEnvironmentCallback +## ApplicationContext.off(type: "abilityLifecycle", callbackId: number) -registerEnvironmentCallback(callback: EnvironmentCallback): **number**; +off(type: "abilityLifecycle", callbackId: **number**): **void**; + +取消监听应用内生命周期 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | -------- | ---- | -------------------------- | +| type | "abilityLifecycle" | 是 | 取消监听事件的类型。 | +| callbackId | number | 是 | 注册监听应用内生命周期的ID。 | + +**示例:** + +```ts +import Ability from "@ohos.app.ability.UIAbility"; + +var lifecycleId; + +export default class MyAbility extends Ability { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + console.log("stage applicationContext: " + applicationContext); + applicationContext.off(type: "abilityLifecycle", lifecycleId); + } +} +``` + +## ApplicationContext.on(type: "environment", callback: EnvironmentCallback) + +on(type: "environment", callback: EnvironmentCallback): **number**; 注册对系统环境变化的监听。使用callback异步回调。 @@ -132,6 +165,7 @@ registerEnvironmentCallback(callback: EnvironmentCallback): **number**; | 参数名 | 类型 | 必填 | 说明 | | ------------------------ | -------- | ---- | ------------------------------ | +| type | "environment" | 是 | 监听事件的类型。 | | callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | 是 | 回调方法,返回注册监听事件的ID。 | **返回值:** @@ -162,15 +196,15 @@ export default class EntryAbility extends UIAbility { // 1.获取applicationContext let applicationContext = globalThis.applicationContext; // 2.通过applicationContext注册监听应用内生命周期 - callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + callbackId = applicationContext.on("environment", EnvironmentCallback); console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); } } ``` -## ApplicationContext.unregisterEnvironmentCallback +## ApplicationContext.off(type: "environment", callbackId: number, callback: AsyncCallback) -unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; +off(type: "environment", callbackId: **number**, callback: AsyncCallback<**void**>): **void**; 取消对系统环境变化的监听。使用callback异步回调。 @@ -180,6 +214,7 @@ unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<* | 参数名 | 类型 | 必填 | 说明 | | ------------- | -------- | ---- | -------------------------- | +| type | "environment" | 是 | 取消监听事件的类型。 | | callbackId | number | 是 | 注册监听系统环境变化的ID。 | | callback | AsyncCallback\ | 是 | 回调方法。 | @@ -193,9 +228,149 @@ var callbackId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + applicationContext.off("environment", callbackId, (error, data) => { console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); }); } } +``` + +## ApplicationContext.off(type: "environment", callbackId: number) + +off(type: "environment", callbackId: **number**, callback: AsyncCallback<**void**>): **void**; + +取消对系统环境变化的监听。使用callback异步回调。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | -------- | ---- | -------------------------- | +| type | "environment" | 是 | 取消监听事件的类型。 | +| callbackId | number | 是 | 注册监听系统环境变化的ID。 | + +**示例:** + +```ts +import Ability from "@ohos.app.ability.UIAbility"; + +var callbackId; + +export default class MyAbility extends Ability { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.off("environment", callbackId); + } +} +``` + +## ApplicationContext.getProcessRunningInformation9+ + +getProcessRunningInformation(): Promise\>; + +获取有关运行进程的信息。 + +**需要权限**:ohos.permission.GET_RUNNING_INFO + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**系统API**: 此接口为系统接口,三方应用不支持调用。 + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise\> | 以Promise方式返回接口运行结果及有关运行进程的信息,可进行错误处理或其他自定义处理。 | + +**示例:** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.getProcessRunningInformation().then((data) => { + console.log("The process running information is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` + +## ApplicationContext.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +获取有关运行进程的信息。 + +**需要权限**:ohos.permission.GET_RUNNING_INFO + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**系统API**: 此接口为系统接口,三方应用不支持调用。 + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +|AsyncCallback\> | 以回调方式返回接口运行结果及有关运行进程的信息,可进行错误处理或其他自定义处理。 | + +**示例:** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.getProcessRunningInformation((err, data) => { + if (err.code !== 0) { + console.error("getProcessRunningInformation faile, err: " + JSON.stringify(err)); + } else { + console.log("The process running information is:" + JSON.stringify(data)); + } +}) +``` + +## ApplicationContext.killProcessesBySelf9+ + +killProcessesBySelf(): Promise; + +杀死应用所在的进程。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise\> | 以Promise方式返回杀死应用所在的进程结果。 | + +**示例:** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.killProcessesBySelf().then((data) => { + console.log("The process running information is:" + JSON.stringify(data)); +}).catch((error) => { + console.error("error:" + JSON.stringify(error)); +}); +``` + +## ApplicationContext.killProcessesBySelf9+ + +killProcessesBySelf(callback: AsyncCallback); + +杀死应用所在的进程。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +|AsyncCallback\ | 以callback方式返回杀死应用所在的进程结果。 | + +**示例:** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.killProcessesBySelf(err => { + if (err.code !== 0) { + console.error("killProcessesBySelf faile, err: " + JSON.stringify(err)); + } +}) ``` \ 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 7a6ca307c663546ec71690b09ccdb5da1c454115..d59f2a3549016e385b674bcb74e34c151cdbd9b4 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 @@ -1214,7 +1214,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback< | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| connection | number | 是 | 在connectAbility中返回的number。 | +| connection | number | 是 | 在connectServiceExtensionAbility中返回的number。 | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | **错误码:** @@ -1266,7 +1266,7 @@ disconnectServiceExtensionAbility(connection: number): Promise<void>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| connection | number | 是 | 在connectAbility中返回的number。 | +| connection | number | 是 | 在connectServiceExtensionAbility中返回的number。 | **返回值:** @@ -1288,7 +1288,7 @@ disconnectServiceExtensionAbility(connection: number): Promise<void>; **示例:** ```ts - // connection为connectAbility中的返回值 + // connection为connectServiceExtensionAbility中的返回值 var connection = 1; try { diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md index 8c0cbdd5ebb961644623f580f009407607935488..2feb49eca2b637434e9ed21bb79fcf4c1b64ea71 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -1,6 +1,6 @@ # TriggerInfo -作为[trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger)的入参定义触发WantAgent所需要的的信息。 +作为[trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger)的入参定义触发WantAgent所需要的信息。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md index 3f0d49e87c3a5b80e9ccbfa002caab0de4ce0e9e..89ce97b7c59ca5a281ce86f3c729a05ad02a07be 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -7,7 +7,7 @@ | 名称 | 类型 | 必填 | 说明 | | -------------- | ------------------------------- | ---- | ---------------------- | | wants | Array\ | 是 | 将被执行的动作列表。 | -| operationType | wantAgent.OperationType | 是 | 动作类型。 | +| operationType | [wantAgent.OperationType](js-apis-app-ability-wantAgent.md#operationtype) | 是 | 动作类型。 | | requestCode | number | 是 | 使用者定义的一个私有值。 | | wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | 否 | 动作执行属性。 | | extraInfo | {[key: string]: any} | 否 | 额外数据。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-pointer.md b/zh-cn/application-dev/reference/apis/js-apis-pointer.md index 014b704990f690340b4f2a9c206cc08abeb07cb7..6ae3701566fe2af3d482ffb5c3cd729d85be46f3 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-pointer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-pointer.md @@ -279,7 +279,7 @@ getPointerStyle(windowId: number, callback: AsyncCallback<PointerStyle>): import window from '@ohos.window'; window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { + win.getWindowProperties((error, properties) => { let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); @@ -322,7 +322,7 @@ getPointerStyle(windowId: number): Promise<PointerStyle> import window from '@ohos.window'; window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { + win.getWindowProperties((error, properties) => { let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); @@ -361,7 +361,7 @@ setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCal import window from '@ohos.window'; window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { + win.getWindowProperties((error, properties) => { let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); @@ -399,7 +399,7 @@ setPointerStyle(windowId: number, pointerStyle: PointerStyle): Promise<void&g import window from '@ohos.window'; window.getTopWindow((error, win) => { - win.getProperties((error, properties) => { + win.getWindowProperties((error, properties) => { let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-system-configuration.md index 5f1beafc9fa71efd83ee715b86813858c98fe9ab..3ab1617f8e9dcec885ee4503df291eba6e273f73 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @@ -49,5 +49,4 @@ static getLocale(): LocaleResponse | ---- | ------ | ---- | ---- | ---------------------------------------- | | language | string | 是 | 否 | 语言。例如:zh。 | | countryOrRegion | string | 是 | 否 | 国家或地区。例如:CN。 | -| dir | string | 是 | 否 | 文字布局方向。取值范围:
- ltr:从左到右;
- rtl:从右到左。 | -| unicodeSetting5+ | string | 是 | 否 | 语言环境定义的Unicode语言环境键集,如果此语言环境没有特定键集,则返回空集。
例如:{"nu":"arab"},表示当前环境下的数字采用阿拉伯语的数字。 | \ No newline at end of file +| dir | string | 是 | 否 | 文字布局方向。取值范围:
- ltr:从左到右;
- rtl:从右到左。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-storage.md b/zh-cn/application-dev/reference/apis/js-apis-system-storage.md index d35b15d1ff5afe4fef74655c11b1b44da7e39621..d7f1a842246dbcbb3c934b8c89cf0d705f0a8670 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-storage.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-storage.md @@ -51,7 +51,7 @@ export default { ## storage.set -get(options: SetStorageOptions): void +set(options: SetStorageOptions): void 修改缓存中索引对应的值。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md b/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md index bf2fe339f78f70f38c7159f457981ebbeaf56e8e..0784a5c5db881acacc773738a049ad035f86c1d1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @@ -160,8 +160,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + //getBundleName回调 + function getBundleNameCallback(err, data) { + console.info('==========================>getBundleNameCallback=======================>'); + } + WantAgent.getBundleName(wantAgent, getBundleNameCallback); } //WantAgentInfo对象 let wantAgentInfo = { @@ -192,12 +199,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -//getBundleName回调 -function getBundleNameCallback(err, data) { - console.info('==========================>getBundleNameCallback=======================>'); -} -WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -261,10 +262,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.getBundleName(wantAgent).then((data) => { - console.info('==========================>getBundleNameCallback=======================>'); + if (wantAgent) { + WantAgent.getBundleName(wantAgent).then((data) => { + console.info('==========================>getBundleNameCallback=======================>'); + }); + } }); ``` @@ -300,8 +302,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + //getUid回调 + function getUidCallback(err, data) { + console.info('==========================>getUidCallback=======================>'); + } + WantAgent.getUid(wantAgent, getUidCallback); } //WantAgentInfo对象 let wantAgentInfo = { @@ -332,12 +341,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -//getUid回调 -function getUidCallback(err, data) { - console.info('==========================>getUidCallback=======================>'); -} -WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -402,10 +405,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.getUid(wantAgent).then((data) => { - console.info('==========================>getUidCallback=======================>'); + if (wantAgent) { + WantAgent.getUid(wantAgent).then((data) => { + console.info('==========================>getUidCallback=======================>'); + }); + } }); ``` @@ -440,8 +444,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + //cancel回调 + function cancelCallback(err, data) { + console.info('==========================>cancelCallback=======================>'); + } + WantAgent.cancel(wantAgent, cancelCallback); } //WantAgentInfo对象 let wantAgentInfo = { @@ -472,12 +483,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -//cancel回调 -function cancelCallback(err, data) { - console.info('==========================>cancelCallback=======================>'); -} -WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -542,10 +547,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.cancel(wantAgent).then((data) => { - console.info('==========================>cancelCallback=======================>'); + if (wantAgent) { + WantAgent.cancel(wantAgent).then((data) => { + console.info('==========================>cancelCallback=======================>'); + }); + } }); ``` @@ -582,8 +588,19 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; + } + + //trigger回调 + function triggerCallback(data) { + console.info('==========================>triggerCallback=======================>'); + } + + var triggerInfo = { + code:0 } + WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) } //WantAgentInfo对象 let wantAgentInfo = { @@ -614,16 +631,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -//trigger回调 -function triggerCallback(data) { - console.info('==========================>triggerCallback=======================>'); -} - -var triggerInfo = { - code:0 -} -WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) ``` @@ -661,8 +668,15 @@ function getWantAgentCallback(err, data) { wantAgent1 = data; wantAgent2 = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + //equal回调 + function equalCallback(err, data) { + console.info('==========================>equalCallback=======================>'); + } + WantAgent.equal(wantAgent1, wantAgent2, equalCallback) } //WantAgentInfo对象 let wantAgentInfo = { @@ -693,12 +707,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -//equal回调 -function equalCallback(err, data) { - console.info('==========================>equalCallback=======================>'); -} -WantAgent.equal(wantAgent1, wantAgent2, equalCallback) ``` @@ -766,6 +774,11 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; + if (data) { + WantAgent.equal(wantAgent1, wantAgent2).then((data) => { + console.info('==========================>equalCallback=======================>'); + }); + } }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { @@ -827,11 +840,12 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + if (data) { + WantAgent.getOperationType(wantAgent, (OperationType) => { + console.log('----------- getOperationType ----------, OperationType: ' + OperationType); + }) + } }); - -WantAgent.getOperationType(wantAgent, (OperationType) => { - console.log('----------- getOperationType ----------, OperationType: ' + OperationType); -}) ``` ## WantAgent.getOperationType9+ @@ -901,7 +915,6 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { }); ``` - ## WantAgentFlags **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core @@ -940,5 +953,5 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { | info | WantAgent | 是 | 触发的wantAgent。 | | want | Want | 是 | 存在的被触发的want。 | | finalCode | number | 是 | 触发wantAgent的请求代码。| -| finalData | string | 否 | 公共事件收集的最终数据。 | +| finalData | string | 是 | 公共事件收集的最终数据。 | | extraInfo | {[key: string]: any} | 否 | 额外数据。 | 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 c072a4cf54fec80813302d637c748ca382a60306..3579acfe447e6c34457ea9337d0502357c9d5a43 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 @@ -51,7 +51,7 @@ | Normal | 普通按钮(默认不带圆角)。 | > **说明:** -> - 按钮圆角通过[通用属性borderRadius](ts-universal-attributes-border.md)设置(不支持通过border接口设置圆角)。 +> - 按钮圆角通过[通用属性borderRadius](ts-universal-attributes-border.md)设置(不支持通过border接口设置圆角),且只支持设置一个相同的圆角。 > - 当按钮类型为Capsule时,borderRadius设置不生效,按钮圆角始终为高度的一半。 > - 当按钮类型为Circle时,borderRadius即为按钮半径,若未设置borderRadius按钮半径则为宽、高中较小值的一半。 > - 按钮文本通过[通用文本样式](ts-universal-attributes-text-style.md)进行设置。 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 15d655ff27b9b2e468f2509b93b058f3279ad64c..22231ba443c6382fb645d04b9833424324be8e55 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 @@ -145,91 +145,3 @@ struct ShapeExample { ``` ![zh-cn_image_0000001184628104](figures/zh-cn_image_0000001184628104.png) - -### 示例2 - -```ts -// xxx.ets -@Entry -@Component -struct ShapeMeshExample { - @State columnVal: number = 0 - @State rowVal: number = 0 - @State count: number = 0 - @State verts: Array = [] - @State shapeWidth: number = 600 - @State shapeHeight: number = 600 - - build() { - Column() { - Shape() { - Rect() - .width('250px') - .height('250px') - .radiusWidth('10px') - .radiusHeight('10px') - .stroke('10px') - .margin({ left: '10px', top: '10px' }) - .strokeWidth('10px') - .fill(Color.Blue) - Rect() - .width('250px') - .height('250px') - .radiusWidth('10px') - .radiusHeight('10px') - .stroke('10px') - .margin({ left: '270px', top: '10px' }) - .strokeWidth('10px') - .fill(Color.Red) - } - .mesh(this.verts, this.columnVal, this.rowVal) - .width(this.shapeWidth + 'px') - .height(this.shapeHeight + 'px') - // 手指触摸Shape组件时会显示mesh扭曲效果 - .onTouch((event: TouchEvent) => { - var touchX = event.touches[0].x * 2 - var touchY = event.touches[0].y * 2 - this.columnVal = 20 - this.rowVal = 20 - this.count = (this.columnVal + 1) * (this.rowVal + 1) - var orig = [this.count * 2] - var index = 0 - for (var i = 0; i <= this.rowVal; i++) { - var fy = this.shapeWidth * i / this.rowVal - for (var j = 0; j <= this.columnVal; j++) { - var fx = this.shapeWidth * j / this.columnVal - orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx - orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy - index++; - } - } - for (var k = 0; k < this.count * 2; k += 2) { - var dx = touchX - orig[k + 0] - var dy = touchY - orig[k + 1] - var dd = dx * dx + dy * dy - var d = Math.sqrt(dd) - var pull = 80000 / (dd * d) - if (pull >= 1) { - this.verts[k + 0] = touchX - this.verts[k + 1] = touchY - } else { - this.verts[k + 0] = orig[k + 0] + dx * pull - this.verts[k + 1] = orig[k + 1] + dy * pull - } - } - }) - } - .width('600px') - .height('600px') - .border({ width: 3, color: Color.Black }) - } -} -``` - -示意图: - -![zh-cn_image1_0000001184628104](figures/zh-cn_image1_0000001184628104.png) - -手指触摸Shape组件时会显示mesh扭曲效果: - -![zh-cn_image2_0000001184628104](figures/zh-cn_image2_0000001184628104.png) \ No newline at end of file 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 ab47fc96adfd0e3f7bfa5b006be15dfe050f15dd..7d001c0c0781ca41d72d34398a668b563d46b30f 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 @@ -23,7 +23,7 @@ | 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箭头在弹窗处的偏移。箭头在气泡上下方时,默认居左;箭头在气泡左右侧时,默认居上。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。如果显示在屏幕边缘,气泡会自动左右偏移,数值为0时箭头始终指向绑定组件。 | | showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | ## CustomPopupOptions8+类型说明 @@ -34,10 +34,10 @@ | placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。
默认值:Placement.Bottom | | maskColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡遮障层的颜色。 | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 | -| enableArrow | boolean | 否 | 是否显示箭头。
从API Version 9开始,如果箭头所在方位侧的气泡长度不足以显示下箭头,则会默认不显示箭头。比如:placement设置为Left,但气泡高度小于箭头的宽度(32vp),则实际不会显示箭头。
默认值:true | +| enableArrow | boolean | 否 | 是否显示箭头。
从API Version 9开始,如果箭头所在方位侧的气泡长度不足以显示下箭头,则会默认不显示箭头。比如:placement设置为Left,但气泡高度小于箭头的宽度的两倍(64vp),则实际不会显示箭头。
默认值:true | | autoCancel | boolean | 否 | 页面有操作时,是否自动关闭气泡。
默认值:true | | onStateChange | (event: { isVisible: boolean }) => void | 否 | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 | -| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,默认居左;箭头在气泡左右侧时,默认居上。 | +| arrowOffset9+ | [Length](ts-types.md#length) | 否 | popup箭头在弹窗处的偏移。箭头在气泡上下方时,数值为0表示箭头居最左侧,偏移量为箭头至最左侧的距离,默认居中。箭头在气泡左右侧时,偏移量为箭头至最上侧的距离,默认居中。如果显示在屏幕边缘,气泡会自动左右偏移,数值为0时箭头始终指向绑定组件。 | | showInSubWindow9+ | boolean | 否 | 是否在子窗口显示气泡,默认值为false。 | diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 017c02bdd104a4ef9510da6aa0f4b3bec975f44d..ff1b771dc8b721871b0b4886a1361ccb534b4374 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -247,5 +247,5 @@ onWindowStageCreate() { 针对访问控制,有以下相关实例可供参考: -- [AbilityAccessCtrl:访问权限控制(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Safety/AbilityAccessCtrl) -- [为应用添加运行时权限(ArkTS)(API 9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/AccessPermission) \ No newline at end of file +- [AbilityAccessCtrl:访问权限控制(ArkTS)(Full SDK)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Safety/AbilityAccessCtrl) +- [为应用添加运行时权限(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/AccessPermission) \ No newline at end of file diff --git a/zh-cn/application-dev/security/accesstoken-overview.md b/zh-cn/application-dev/security/accesstoken-overview.md index 5aae9b27ec59c39aac848a0c3653a27cc393b5fe..aad84e46328813bf8c93ec6eeed26ece60f2123f 100644 --- a/zh-cn/application-dev/security/accesstoken-overview.md +++ b/zh-cn/application-dev/security/accesstoken-overview.md @@ -153,7 +153,7 @@ ATM (AccessTokenManager) 是OpenHarmony上基于AccessToken构建的统一的应 - 权限申请 - 开发者需要在配置文件中[声明目标权限](accesstoken-guidelines.md#权限申请声明)。 + 开发者需要在配置文件中[声明目标权限](accesstoken-guidelines.md#配置文件权限声明)。 - 权限授权 @@ -175,7 +175,7 @@ ATM (AccessTokenManager) 是OpenHarmony上基于AccessToken构建的统一的应 **注意事项:** - 每次执行需要目标权限的操作时,应用都必须检查自己是否已经具有该权限。 -- 如需检查用户是否已向您的应用授予特定权限,可以使用[verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md)函数,此方法会返回 [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md)或[PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md)。具体的示例代码可以查看[访问控制开发指导](accesstoken-guidelines.md)。 +- 如需检查用户是否已向您的应用授予特定权限,可以使用[checkAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md#checkaccesstoken9)函数,此方法会返回 [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md)或[PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md)。具体的示例代码可以查看[访问控制开发指导](accesstoken-guidelines.md)。 - user_grant权限授权要基于用户可知可控的原则,需要应用在运行时主动调用系统动态申请权限的接口,系统弹框由用户授权,用户结合应用运行场景的上下文,识别出应用申请相应敏感权限的合理性,从而做出正确的选择。 - 即使用户向应用授予过请求的权限,应用在调用受此权限管控的接口前,也应该先检查自己有无此权限,而不能把之前授予的状态持久化,因为用户在动态授予后还可以通过设置取消应用的权限。 diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index 80ee8bb659a5f8130bcb825de522c33e83a014bc..19970e2214611a716eacb2113febe2f409f9992c 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -1594,6 +1594,16 @@ **ACL使能**:TRUE +## ohos.permission.APP_TRACKING_CONSENT + +允许应用读取广告标识符。 + +**权限级别**:normal + +**授权方式**:user_grant + +**ACL使能**:TRUE + ## ohos.permission.RUN_ANY_CODE 允许应用运行未签名的代码。 diff --git a/zh-cn/application-dev/task-management/reminder-agent-development.md b/zh-cn/application-dev/task-management/reminder-agent-development.md index 20390299966d8d696129b7177fb14204e46bec59..cc57f01db881131f73ea7b11392005dd03fc0442 100644 --- a/zh-cn/application-dev/task-management/reminder-agent-development.md +++ b/zh-cn/application-dev/task-management/reminder-agent-development.md @@ -175,3 +175,9 @@ console.log("cancelReminder code: " + error.code + ", message: " + error.message); }; ``` + +## 相关实例 + +基于后台代理提醒的开发,有以下相关实例可供参考: + +- [闹钟(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) \ No newline at end of file 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 6ef14c79e61a3b67a9c5b63053a80fb919c316c1..53f345facae16f1885214e63bc7f43f6d3bb9561 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 @@ -25,6 +25,8 @@ 针对组件开发,有以下相关实例可供参考: +- [`JsComponentCollection`:组件集合(JS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/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) diff --git a/zh-cn/application-dev/ui/ui-ts-components-intro.md b/zh-cn/application-dev/ui/ui-ts-components-intro.md index 098791ee5e3a4787d7a85eee43b417a5f88007d5..343a6c790404c47b05b40f2ab2686c1312ec3388 100644 --- a/zh-cn/application-dev/ui/ui-ts-components-intro.md +++ b/zh-cn/application-dev/ui/ui-ts-components-intro.md @@ -15,6 +15,12 @@ ## 相关实例 +基于ArkTS的常用组件开发,有以下相关实例可供参考: + +- [`ComponentCollection`:组件集合(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/ComponentCollection) + +- [`OrangeShopping`:购物示例应用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/OrangeShopping) + - [`Canvas`:画布组件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) - [`Clock`:简单时钟(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) @@ -25,6 +31,8 @@ - [`QRCode`:二维码(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/QRCode) -- [基础组件Slider的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderApplicationEts) - - [`Gallery`:组件集合(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) + +- [List组件的使用之商品列表(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/List_HDC) + +- [List组件的使用之设置项(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/List_HDC) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-components-web.md b/zh-cn/application-dev/ui/ui-ts-components-web.md index 046c192db4ce6dd17655981a8b8502e13e8e9b95..1f7330eda0051c771f1a09fa6113d77adc22ce88 100644 --- a/zh-cn/application-dev/ui/ui-ts-components-web.md +++ b/zh-cn/application-dev/ui/ui-ts-components-web.md @@ -8,10 +8,12 @@ Web是提供网页显示能力的组件,具体用法请参考 [Web API](../ref ```ts // xxx.ets + import web_webview from '@ohos.web.webview'; + @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { Web({ src: 'https://www.example.com', controller: this.controller }) @@ -26,11 +28,13 @@ Web组件的使用需要添加丰富的页面样式和功能属性。设置heigh ```ts // xxx.ets +import web_webview from '@ohos.web.webview'; + @Entry @Component struct WebComponent { fileAccess: boolean = true; - controller: WebController = new WebController(); + controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { Text('Hello world!') @@ -54,13 +58,15 @@ struct WebComponent { ```ts // xxx.ets +import web_webview from '@ohos.web.webview'; + @Entry @Component struct WebComponent { @State progress: number = 0; @State hideProgress: boolean = true; fileAccess: boolean = true; - controller: WebController = new WebController(); + controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { Text('Hello world!') @@ -93,14 +99,17 @@ struct WebComponent { ```ts // xxx.ets +import web_webview from '@ohos.web.webview'; + @Entry @Component struct WebComponent { @State progress: number = 0; @State hideProgress: boolean = true; + @State webResult: string = '' fileAccess: boolean = true; // 定义Web组件的控制器controller - controller: WebController = new WebController(); + controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { Text('Hello world!') @@ -124,8 +133,23 @@ struct WebComponent { }) .onPageEnd(e => { // test()在index.html中定义 - this.controller.runJavaScript({ script: 'test()' }); - console.info('url: ', e.url); + try { + this.controller.runJavaScript( + 'test()', + (error, result) => { + if (error) { + console.info(`run JavaScript error: ` + JSON.stringify(error)) + return; + } + if (result) { + this.webResult = result + console.info(`The test() return value is: ${result}`) + } + }); + console.info('url: ', e.url); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } }) Text('End') .fontSize(20) @@ -160,10 +184,12 @@ struct WebComponent { 1、首先设置Web组件属性webDebuggingAccess为true。 ```ts // xxx.ets + import web_webview from '@ohos.web.webview'; + @Entry @Component struct WebComponent { - controller: WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -189,20 +215,30 @@ struct WebComponent { ```ts // xxx.ets +import web_webview from '@ohos.web.webview'; + @Entry @Component struct WebComponent { - controller: WebController = new WebController(); + controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { Row() { Button('onActive').onClick(() => { console.info("Web Component onActive"); - this.controller.onActive(); + try { + this.controller.onActive(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } }) Button('onInactive').onClick(() => { console.info("Web Component onInactive"); - this.controller.onInactive(); + try { + this.controller.onInactive(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } }) } Web({ src: $rawfile('index.html'), controller: this.controller }) @@ -231,3 +267,7 @@ struct WebComponent { 针对Web开发,有以下相关实例可供参考: - [`Web`:Web(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Web) + +- [Web组件的使用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebCookie) + +- [Web组件抽奖案例(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebComponent) diff --git a/zh-cn/application-dev/ui/ui-ts-overview.md b/zh-cn/application-dev/ui/ui-ts-overview.md index e7bf1744db4373eb141e219dd19ca003782b82d8..304ddc7382ecb17004bc0fb1c515ec831ad21660 100644 --- a/zh-cn/application-dev/ui/ui-ts-overview.md +++ b/zh-cn/application-dev/ui/ui-ts-overview.md @@ -76,12 +76,14 @@ ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get- - [`TransitionAnimation`:转场动画(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/TransitionAnimation) +- [基础组件Slider的使用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderExample) + +- [转场动画的使用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimation) + - [极简声明式UI范式(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) - [购物应用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) -- [转场动画的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimtaionEts) - - [弹窗(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) - [`UpgradePopup`:自定义弹窗(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/UpgradePopup) diff --git a/zh-cn/contribute/template/js-template.md b/zh-cn/contribute/template/js-template.md index b729a64b35bbb3d1d7d70f2732c63c5aa5eec6f0..ff323eff8e1797a33174e98fb6b0952d37bd1a84 100644 --- a/zh-cn/contribute/template/js-template.md +++ b/zh-cn/contribute/template/js-template.md @@ -104,7 +104,7 @@ import call from '@ohos.telephony.call'; **系统能力:** SystemCapability.xxx.xxx。(必选) -| 名称 | 类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 只读 | 必填 | 说明 | | ---------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------ | | pluggedType | [BatteryPluggedType](#batterypluggedtype) | 是 | 否 | 表示当前设备连接的充电器类型。 | | isBatteryPresent | boolean | 是 | 否 | 表示当前设备是否支持电池或者电池是否在位。 | @@ -161,15 +161,15 @@ import call from '@ohos.telephony.call'; | 参数名 | 类型 | 必填 | 说明 | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| parameterOne | number \| string \| [CustomType](#customtype) | 是 | 参数描述。给出取值范围、建议值。如果有固定格式,需要给出格式样例,尤其是URI。
自定义类型需要进行建链说明。 | -| callback | Callback\> | 否 | 参数描述。可选参数需要说明不填写该参数的后果。
如:不填该参数则取消该type对应的所有回调。
callback写法参考总体写作说明第14项。 | +| parameterOne | number \| string \| [CustomType](#classinterface) | 是 | 参数描述。给出取值范围、建议值。如果有固定格式,需要给出格式样例,尤其是URI。
自定义类型需要进行建链说明。 | +| callback | Callback\> | 否 | 参数描述。可选参数需要说明不填写该参数的后果。
如:不填该参数则取消该type对应的所有回调。
callback写法参考总体写作说明第14项。 | **返回值**:(可选,如不涉及可删除) | 类型 | 说明 | | ------------------------------------------ | ----------------------------------------------- | | string | 返回值描述。取到返回值之后,可以用来做什么。 | -| Promise\> | 返回值描述。Promise写法参考总体写作说明第14项。 | +| Promise\> | 返回值描述。Promise写法参考总体写作说明第14项。 | **错误码**:(可选,如不涉及可删除) @@ -227,7 +227,7 @@ import call from '@ohos.telephony.call'; | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | 是 | 事件描述,需要说明触发时机。如一个方法涉及多个事件,需要分开说明。
**示例1(单个):**
事件回调类型,支持的事件为`'play'`,当`play()`调用完成,音频开始播放,触发该事件。
**示例2(多个):**
事件回调类型,支持的事件包括:`'play'` \| `'dataLoad' `\|`'finish'`。
\- `'play'`:完成`play()`调用,音频开始播放,触发该事件。
\- `'dataLoad'`:完成音频数据加载后触发该事件,即src属性设置完成后触发该事件。
\- `'finish'`:完成音频播放后触发该事件。 | -| callback | Callback\<[CustomType](#CustomType)> | 否 | 参数描述。与[方法](#方法)要求一致。 | +| callback | Callback\<[CustomType](#classinterface)> | 否 | 参数描述。与[方法](#方法)要求一致。 | **返回值:**(可选,如不涉及可删除) @@ -261,15 +261,15 @@ import call from '@ohos.telephony.call'; > 2. 二级标题名为class、interface的名称。 > > 3. 如果该API中,既有属性,又有方法,需要先进行属性的写作,并使用“###”三级标题。 -> 如果该API中,只有属性,那么不需要新建三级标题,直接使用表格陈列属性,具体示例参考[CustomType](#CustomType)。 +> 如果该API中,只有属性,那么不需要新建三级标题,直接使用表格陈列属性。 -类描述/interface描述。如果有使用限制,需要在这个地方说明。比方说,是否有前提条件,是否需要通过什么方法先构造一个实例。 +类描述/interface描述。如果有使用限制,需要在这个地方说明。比方说,是否有前提条件,是否需要通过什么方法先构造一个实例。 ### 属性 > *写作说明* > -> 除标题使用三级标题外,其余要求同[属性](#属性)。 +> 除标题使用三级标题外,其余要求同[属性](#属性),如仅有属性,可删除。 ### Class/Interface中的方法 @@ -296,28 +296,13 @@ import call from '@ohos.telephony.call'; | ---- | ---- | -------------------------- | | NONE | 1 | 表示连接的充电器类型未知。 | -## CustomType - -> *写作说明* -> -> 可选,如果没有可删除此二级标题,对应d.ts中无方法的Interface。 - -仅有k-v键值对的自定义类型示例。 - -**系统能力:** SystemCapability.xxx.xxx(必选) - -| 名称 | 类型 | 必填 | 说明 | -| ------------ | ------------------- | ---- | ------------------------------------------------------------ | -| parameterUrl | string | 是 | 媒体输出URI。支持:
1. 协议类型为“internal”的相对路径,示例如下: 临时目录:internal://cache/test.mp4
2. 文件的绝对路径,示例如下: file:///data/data/ohos.xxx.xxx/files/test.mp4 | -| parameterOne | [CustomEnum](#枚举) | 否 | 属性描述,要求与参数说明类似。 | - ## Type > *写作说明* > > 1. 可选,如果没有可删除此二级标题,对应d.ts中的type联合类型。 > -> 2. 默认第一列为“类型”。如果全部为具体字符串,可将第一列修改为“取值”。 +> 2. 如果为取值范围为具体取值,如固定的字符串、枚举值等,需要说明其数据类型和指定取值;如果取值范围为指定类型,需说明是否取类型下任意值,还是有取值范围。 > > 3. 类型如果为自定义类型,需要建立链接到对应的interface或enum中。 @@ -325,14 +310,15 @@ import call from '@ohos.telephony.call'; **系统能力:** SystemCapability.xxx.xxx(必选) -| 类型 | 说明 | +| 取值范围 | 说明 | | -----------| ---------------------------- | -| number | 表示值类型为数字。 | -| string | 表示值类型为字符。 | +| number | 表示值类型为数字,可取任意值。 | +| string | 表示值类型为字符,可取任意值。 | ## 变更日志 | 变更说明 | 日期 | | ----------------------------------------------------------------------- | ------------ | +| 1. 修改属性的模板,将“可读”、“可写”、“必填”,统一为“只读”、“必填”。
2. 修改Type的模板,模板修改为“取值范围/说明”,并增加相关说明。
3. 删除自定义类型,合并进class和interface的模板中。 | 2023/02/01 | | 1. 总体写作说明整理为表格。
2. “图片路径”中,增加图片的引用方式说明。
3. 增加“文档结构”,对文档各节点顺序进行说明。
4. “权限说明”中,增加多权限的描述方式。
5. 增加@FAModelOnly/@StageModelOnly标记在文档的描述方式。
6. 增加异步接口说明(callback、Promise)。
7. 增加示例代码语言的标准和规范。
8. 增加文档链接的标准写法。
9. 增加模块描述的固定句式、示例。
10. 增加“on/off”等订阅方法的说明。
11. 修改@syscap的描述方式,除表格内的差异项,其余保持一致。
12. 修改@systemapi的描述方式,仅保留“该系统为系统接口。”。
13. 删除MR版本说明。 | 2022/6/24 | | 增加错误码说明。 | 2022/10/11 | | 1. 增加**常量const**、**类型type**的模板。
2. 修改自定义类型interface的表格,去除“可读、可写”,与d.ts保持一致,增加“必填”。
3. 针对同时存在起始版本和废弃版本的接口,增加废弃说明的模板。 |2022/11/22 | diff --git a/zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md b/zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md index 2a04bbdd940b8c9678f04bb94ab3e95dcc88bbbe..7f2d371bd0d812ca38f30519252e5d9571f4af81 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md @@ -44,7 +44,7 @@ 4. 参数填写 - 参数配置项可以参考:[productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json) + 参数配置项可以参考:productdefine/common/base/base_product.json ![参数填写](figures/kconfig参数输入.gif) @@ -99,7 +99,7 @@ ### 菜单列表缺失最新部件信息 -由于产品不断的更新迭代,全量部件列表[productdefine/common/base/base_product.json](https://gitee.com/openharmony/productdefine_common/blob/master/base/base_product.json)也会随之不断更新,从而导致Kconfig菜单缺少最新部件。 +由于产品不断的更新迭代,全量部件列表productdefine/common/base/base_product.json也会随之不断更新,从而导致Kconfig菜单缺少最新部件。 解决办法: diff --git "a/zh-cn/readme/\346\265\213\350\257\225\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\346\265\213\350\257\225\345\255\220\347\263\273\347\273\237.md" index 8b1063f4eb115087f3057adb19e5c5c3af681478..728661912d228e5f8004d537beefd2d44b1722a6 100755 --- "a/zh-cn/readme/\346\265\213\350\257\225\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\346\265\213\350\257\225\345\255\220\347\263\273\347\273\237.md" @@ -326,7 +326,7 @@ subsystem # 子系统 针对不同语言,下面提供不同的编译模板以供参考。 - **C++用例编译配置示例** - ``` + ```c++ import("//build/test.gni") @@ -414,8 +414,8 @@ subsystem # 子系统 > - ohos_performancetest:性能测试 > - ohos_securitytest:安全测试 > - ohos_reliabilitytest:可靠性测试 - > - ohos_distributedtest:分布式测试 - + > - ohos_distributedtest:分布式测试 + 7. 对目标测试用例文件进行条件分组 ``` @@ -425,10 +425,10 @@ subsystem # 子系统 } ``` > **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 - + - **JavaScript用例编译配置示例** - ``` + ```javascript import("//build/test.gni") diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md new file mode 100644 index 0000000000000000000000000000000000000000..04161710636b108e044c34d4d777b3ff88dc4ac7 --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta5.md @@ -0,0 +1,208 @@ +# OpenHarmony 3.2 Beta5 + + +## 版本概述 + +当前版本在OpenHarmony 3.2 Beta4的基础上,更新支持或优化增强的能力如下: + +**标准系统基础能力增强** + +webview启动性能优化;配置管理和对输入事件的支持等能力增强;模块化模式下可导入json文件并加载。 + +支持taskpool;hap包动态库不压缩加载;host版本TS2AOT-tool工具;编译器运行时支持应用内共享包。 + +支持安装/更新/卸载动态共享库;支持动态共享库打包和拆包;对未配置入口图标的应用,可在桌面显示默认图标;HAR共享包运行期能力可验证。 + +卡片本地数据库切换;常驻应用异常频繁重启保护;ServiceExtensionAbility支持异步onConnected生命周期。 + +支持本地帐号与域帐号绑定、认证,以及域帐号管理服务基础框架;支持禁止直接创建本地用户。 + +支持电源灯、light灯能力控制。 + +HDI驱动显示图层,可以实现对水平镜像和垂直镜像的支持。 + +**标准系统应用开发框架增强** + +工具链新增编译共享包流程。 + +ArkUI适配了根据资源名称获取资源的能力。 + +提供多级菜单和分组菜单的组件能力。 + +新增编译har包的流程。 + +新增适配hap编译流程的能力,hap编译时能识别.d.ets声明文件。 + +**标准系统分布式能力增强** + +支持BLE连接参数配置,连接过程优化。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.2 Beta5 | NA | +| Public SDK | Ohos_sdk_public 3.2.10.6 (API Version 9 Beta5) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。通过DevEco Studio默认获取的SDK为Public SDK。 | +| HUAWEI DevEco Studio(可选) | *待发布* | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | *待发布* | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee帐号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + +- 从版本分支获取源码。可获取该版本分支的最新源码,包括版本发布后在该分支的合入。 + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- 从版本发布Tag节点获取源码。可获取与版本发布时完全一致的源码。 + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +**方式二** + +通过repo + https 下载。 + +- 从版本分支获取源码。可获取该版本分支的最新源码,包括版本发布后在该分支的合入。 + ``` + repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony-3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- 从版本发布Tag节点获取源码。可获取与版本发布时完全一致的源码。 + ``` + repo init -u https://gitee.com/openharmony/manifest -b refs/tags/OpenHarmony-v3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + + +### 从镜像站点获取 + + **表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | **软件包容量** | +| --------------------------------------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -------- | +| 全量代码(标准、轻量和小型系统) | 3.2 Beta5 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/code-v3.2-Beta5.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/code-v3.2-Beta5.tar.gz.sha256) | 21.3 GB | +| Hi3861解决方案(二进制) | 3.2 Beta5 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/hispark_pegasus.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/hispark_pegasus.tar.gz.sha256) | 22.9 MB | +| Hi3516解决方案-LiteOS(二进制) | 3.2 Beta5 | [站点](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_LiteOS.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_LiteOS.tar.gz.sha256) | 293.6 MB | +| Hi3516解决方案-Linux(二进制) | 3.2 Beta5 | [站点](hispark_taurus_Linux.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_Linux.tar.gz.sha256) | 174.3 MB | +| RK3568标准系统解决方案(二进制) | 3.2 Beta5 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/dayu200_standard_arm32_20230201.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/dayu200_standard_arm32_20230201.tar.gz.sha256) | 3.9 GB | +| 标准系统Public SDK包(Mac) | 3.2.10.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-mac-public.tar.gz.sha256) | 674.5 MB | +| 标准系统Public SDK包(Mac-M1) | 3.2.10.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/L2-SDK-MAC-M1-PUBLIC.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/L2-SDK-MAC-M1-PUBLIC.tar.gz.sha256) | 634.5 MB | +| 标准系统Public SDK包(Windows\Linux) | 3.2.10.6 | [站点](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-windows_linux-public.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-windows_linux-public.tar.gz.sha256) | 1.6 GB | + + + +## 更新说明 + +本版本在OpenHarmony 3.2 Beta4的基础上有如下变更。 + + +### 特性变更 + + **表3** 版本特性变更表 + +| 子系统名称 | 标准系统 | 轻量、小型系统 | +| -------- | -------- | -------- | +| ArkUI | - 支持通过资源名称获取资源。
- 组件支持多级菜单和分组菜单。
- 编译能力增强。
主要涉及以下需求:
I683Z1 【新增功能】ArkUI适配根据资源名称获取资源
I68DBH 【基础能力】提供多级菜单和分组菜单能力
I68DRY【新增功能】新增编译har包的流程
I68DRY【新增功能】适配hap编译流程,hap编译时能识别.d.ets声明文件
I68DRY【新增功能】工具链新增编译共享包流程 | NA | +| Web子系统 | webview部件新增支持多项能力,包括:
- web页面的加载和显示支持历史记录和前进/后退、支持页面加载各类事件上报、webmessage支持arraybuffer类型、fetch支持自定义协议。
- webview的配置管理支持滚动条和滚动位置、支持网络加载拦截配置、支持判断页面中是否有image、支持获取源url/请求方法/网站图标、支持字体管理。
- 支持web上下文菜单中获取页面选中内容。
- 输入事件支持交互归一、支持原始输入事件。
- 新增支持若干W3C接口。
主要涉及以下需求:
I6BFPR 【功能增强】【webview部件】web页面的加载和显示 (支持历史记录和前进后退列表管理)
I6BFRC 【功能增强】【webview部件】支持W3C接口(html-部分用例)
I6BFS6 【功能增强】【webview部件】支持W3C接口(css-部分用例)
I6BFSK 【功能增强】【webview部件】web页面的加载和显示 (1.webmessage支持arraybuffer类型)
I6BFTS 【功能增强】【webview部件】支持W3C接口( 1.支持appmanifest等)
I6BFUD 【功能增强】【webview部件】web页面的加载和显示(1.fetch支持自定义协议)
I6BFUM 【功能增强】【webview部件】web页面支持状态回调 (1.支持页面加载各类事件上报)
I6BFV4 【功能增强】【webview部件】webview的配置管理 (1.支持滚动条和滚动位置 )
I6BFXF 【功能增强】【webview部件】webview的配置管理( 1.支持网络加载拦截配置 2.支持判断页面中是否有image 3.支持获取源url、请求方法以及网站图标)
I6BFXT 【功能增强】【webview部件】webview的配置管理(1.支持字体管理)
I6BFY9 【功能增强】【webview部件】输入事件支持(1.支持交互归一)
I6BG4H 【功能增强】【webview部件】输入事件支持(1.支持原始输入事件)
I6BG59 【功能增强】【webview部件】web页面内容选中和复制(1.支持web上下文菜单中获取页面选中内容) | NA | +| 安全 | - Mini设备支持认证会话取消能力
- HUKS支持RSA 签名增强方案
主要涉及以下需求:
I65VLX【功能增强】Mini设备支持认证会话取消能力
I611S5【新增规格】HUKS支持RSA 签名增强方案 | NA | +| 包管理 | - 隐式查询能力增强。
- 支持TS代码优化目录创建。
- 验签时支持provision中bundleName校验。
- 支持未配置入口图标的应用在桌面显示默认图标。
- 支持打包/拆包OpenHarmony动态共享库、支持安装/更新/卸载动态共享库、HAR共享包运行期能力验证等基础能力。
主要涉及以下需求:
I6BD9G【基础能力】隐式查询能力增强
I6BD9E【基础能力】支持TS代码优化目录创建
I6BD99【基础能力】验签时支持provision中bundleName校验
I6BD8Z【基础能力】支持未配置入口图标的应用在桌面显示默认图标
I6BD92【新增功能】支持打包/拆包OpenHarmony动态共享库
I6BD96【新增规格】支持安装/更新/卸载动态共享库
I6BD9I HAR共享包运行期能力验证 | NA | +| 编译运行时 | - 新增提供TS/JS高级语言任务池并发API-taskpool。
- 新增支持HOST侧TSAOT功能,tsc支持导出/导入声明文件(.d.ts/.d.ets)
主要涉及如下需求:
I65G6O 【基础能力】【闭源HAR包】tsc支持导出/导入声明文件(.d.ts/.d.ets)
I64QIR【taskpool】高级语言提供任务池并发API
I65HID【功能增强】支持host版本TS2AOT-tool工具 | NA | +| 泛Sensor服务 | 支持light单逻辑灯控制能力。
主要涉及以下需求:
I63TFA 【新增规格】 支持基本light单逻辑灯控制能力 | NA | +| 媒体 | 对播放音视频和录制音视频的接口进行了重构。
主要涉及以下需求:
I63GTA 【重构】播放音视频接口合一
I66VL5 【重构】录制音视频接口合一 | NA | +| 启动恢复 | 对NAPI模块隐藏符号,对依赖静态库模块修改为动态库依赖。
主要涉及以下需求:
I698CV 【符号优化】对NAPI模块隐藏符号,对依赖静态库模块修改为动态库依赖 | NA | +| 事件通知 | 本地通知数据库进行了切换。
主要涉及以下需求:
I67E9A 【基础能力】本地通知数据库切换 | NA | +| 图形图像 | 新增支持相机预览镜像。
主要涉及以下需求:
I6BDOH 【RenderService】【新增功能】支持相机预览镜像 | NA | +| 位置服务 | 新增支持网络定位框架能力。
主要涉及以下需求:
I5X4S9 【新增特性】【位置服务子系统】支持网络定位框架能力 | NA | +| 文件存储 | - 新增应用文件统一URI处理能力。
- 新增支持公共数据的临时授权和统一的打开入口。
主要涉及以下需求:
I687C8【新增能力】支持应用文件统一URI处理能力
I64U8W【基础能力】支持公共数据的临时授权和统一open入口 | NA | +| 元能力 | - 新增常驻进程重启优化。
- 支持卡片数据库切换。
- 支持异步onConnected等能力。
主要涉及以下需求:
I65M3F 【基础能力】执行ShellCommand命令管控
I65V83 【基础能力】ServiceExtensionAbility支持异步onConnected生命周期
I61H21 【基础能力】卡片本地数据库切换
I63UJ5 【元能力】【ability_runtime】API8及以前API 支持异常处理
I6BDCW 【基础能力】应用加载禁止加载data目录下的代码
I6BDDU 【基础能力】FA模型默认启动方式为Standard
I6BDE2 【基础能力】常驻应用异常频繁重启保护 | NA | + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +### Samples + + **表4** 新增Samples + +| 子系统 | 名称 | 简介 | 开发语言 | +| -------- | -------- | -------- | -------- | +| web | [JS注入与执行](https://gitee.com/openharmony/applications_app_samples/tree/master/Web/RunJsInWeb) | 本示例基于H5游戏,通过ArkUI的button实现对游戏实现基本控制,展示webview的JS注入与执行能力,及native应用与H5的通信能力。 | ArkTs | +| 媒体子系统 | [二维码扫描](https://gitee.com/openharmony/applications_app_samples/tree/master/media/QRCodeScan) | 本示例展示二维码扫描,从文件中选择二维码图片进行解析和读取,识别二维码信息。 | ArkTs | +| ArkUI | [一多设置典型页面](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Settings) | 本示例展示了设置应用的典型页面,其在小窗口和大窗口有不同的显示效果,体现一次开发、多端部署的能力。 | ArkTs | +| 文件管理 | [文件管理](https://gitee.com/openharmony/applications_app_samples/tree/master/FileManager/FileManager) | 本示例主要展示了文件管理相关的功能,使用[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/master/media/ScreenRecorder) | 该示例展示设备屏幕(含音频)录制功能。屏幕录制的主要工作是通过创建一个虚拟屏,捕获屏幕显示图形帧,完成视频编码并保存到文件中,帮助OEM设备厂家系统应用实现屏幕录制功能,也可以通过此应用抓取屏幕帧用于问题复现录制。 | ArkTs | +| 窗口子系统 | [屏幕探测](https://gitee.com/openharmony/applications_app_samples/tree/master/device/ScreenDetector) | 本示例实时监测连接的屏幕数量状态,支持创建至多5个虚拟屏幕,点击对应的屏幕矩形能显示该屏幕的相关属性。 | ArkTs | +| 元能力 | [Stage模型卡片小游戏](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormGame) | 本示例展示了如何通过Stage模型实现一个简单的游戏卡片。 | ArkTs | + + +请访问[Samples](https://gitee.com/openharmony/app_samples)仓了解更多信息。 + + +## 修复缺陷列表 + + **表5** 修复缺陷ISSUE列表 + +| ISSUE单 | 问题描述 | +| -------- | -------- | +| I5KMQX | 【RK3568】联系人到拨号子页签切换动作的完成时延要求未达标 | +| I5UFS1 | 组件das u-boot扫描发现新增漏洞CVE-2022-2347 | +| I5UDY5 | linux kernel漏洞:CVE-2022-41218 | +| I5YPMZ | linux kernel漏洞:CVE-2022-3344 | + + +## 遗留缺陷列表 + + **表6** 遗留缺陷列表 + +| ISSUE | 问题描述 | 影响 | 计划解决日期 | +| -------- | -------- | -------- | -------- | +| I6ATXO | 【RK3568】XTS执行测试,OpenGL测试套执行结果存在失败项 | 用例用于测试OpenGL接口,系统其他模块变更后用例未适配,但使用OpenGL接口的模块/应用不受影响,风险可控。 | 2023年2月5日 | +| I6B1IC | 【RK3568】【低概率1/10】【XTS】进程/vendor/bin/ispserver下的ispserver线程导致librkaiq.z.so出现cppcrash | 压测情况下,低概率出现ipserver线程cppcrash,出现crash后能自动重新启动ipserver线程,业务不受影响。 | 2023年2月5日 | +| I6BJ9Z
I6BJ82 | alloc_file_pseudo 内存泄漏问题跟踪 | accept4引用计数不平衡导致内存泄漏,selinux_netlbl_sock_genattr、new_inode_pseudo、inet_create 内存泄漏,上游社区无补丁,跟随上游社区补丁合入。 | 2023年3月30日 | +| I641A2
I64726 | 蓝牙模块存在静默配对问题,其他设备可以静默配对后通过蓝牙键盘、鼠标完全控制设备 | 蓝牙模块存在静默配对问题。在后续版本以需求跟踪解决。 | 2023年3月30日 | +| I6BRTS | 调用rdb::executeSql接口会引起内存泄漏风险 | 反复初始化调用rdb::executeSql接口出现少量内存泄露,此接口为应用初始化时调用,但不会多次调用,内存泄露影响可控。 | 2023年2月10日 | +| I6AZ4T | 带textinput输入框组件的应用存在内存泄漏风险 | 高频反复调用textinput框出现少量内存泄露,根因为调用三方库flutter库,内存未回收。需排查是否为开源flutter组件问题。 | 2023年2月10日 | + + \ No newline at end of file diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index 9488272e72b92c4f3a73baebd22faaa748bf1a91..de2478b990ec99ec4eeb16ad5117796ad1baee82 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -1,6 +1,7 @@ # OpenHarmony Release Notes ## OpenHarmony 3.x Releases +- [OpenHarmony v3.2 Beta5 (2023-01-31)](OpenHarmony-v3.2-beta5.md) - [OpenHarmony v3.2 Beta4 (2022-11-30)](OpenHarmony-v3.2-beta4.md) - [OpenHarmony v3.2 Beta3 (2022-09-30)](OpenHarmony-v3.2-beta3.md) - [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md)