diff --git a/CustomDialogPractice/AppScope/app.json5 b/CustomDialogPractice/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..fbc9ed53c2cbf741f7d10c2bbbb2f5f5ac2945db --- /dev/null +++ b/CustomDialogPractice/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.customdialogpractice", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/CustomDialogPractice/AppScope/resources/base/element/string.json b/CustomDialogPractice/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f361267f82ca7c88e1f751f90957d293e4fa0188 --- /dev/null +++ b/CustomDialogPractice/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "CustomDialogPractice" + } + ] +} diff --git a/CustomDialogPractice/AppScope/resources/base/media/Back.png b/CustomDialogPractice/AppScope/resources/base/media/Back.png new file mode 100644 index 0000000000000000000000000000000000000000..cb9a7891acdedd7eea9569da7ec35d747dacbcfa Binary files /dev/null and b/CustomDialogPractice/AppScope/resources/base/media/Back.png differ diff --git a/CustomDialogPractice/AppScope/resources/base/media/app_icon.png b/CustomDialogPractice/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..a39445dc87828b76fed6d2ec470dd455c45319e3 Binary files /dev/null and b/CustomDialogPractice/AppScope/resources/base/media/app_icon.png differ diff --git a/CustomDialogPractice/LICENSE b/CustomDialogPractice/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..338e5b0bc22082e0ffcc7121c2ed3897a3ddccb0 --- /dev/null +++ b/CustomDialogPractice/LICENSE @@ -0,0 +1,78 @@ + Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Apache License, Version 2.0 +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +1.You must give any other recipients of the Work or Derivative Works a copy of this License; and +2.You must cause any modified files to carry prominent notices stating that You changed the files; and +3.You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +4.If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/CustomDialogPractice/README.md b/CustomDialogPractice/README.md new file mode 100644 index 0000000000000000000000000000000000000000..92409377b5fd5165a97199933acf46b4ff5ac3b0 --- /dev/null +++ b/CustomDialogPractice/README.md @@ -0,0 +1,60 @@ +# **应用自定义弹窗开发实践** +## 介绍 +弹窗是应用开发需要实现的基础功能,通常用来展示用户当前需要或用户必须关注的信息或操作,可用于广告、中奖、警告、软件更新等与用户交互响应的操作。 +在应用开发中,经常需要实现自定义UI和功能要求,系统弹窗往往无法满足需求,此时就需要使用到自定义弹窗了。 + +合理选择不同的系统能力实现弹窗,有利于提升应用开发效率,实现更好的功能需求,因此了解自定义弹窗的选型和差异非常重要。在应用开发中,为了选择出 +合适的弹窗选型,从使用场景上,需要重点关注以下两点: + +* 弹窗与界面代码解耦 +在开发业务逻辑时,例如遇到一些网络请求失败的场景,需要触发相应的弹窗提醒用户进行操作,由于在任何页面都有可能触发对应的弹窗,此时弹窗不是与某个 +页面相关联,这个情况下,就需要弹窗与界面的解耦。 + +* 弹窗在界面跳转后保留 +在一些权限配置页,用户首次进入应用时会弹出权限配置弹窗,让用户进行操作,此时若点击跳转到隐私详情页面,返回后弹窗需要保留在页面上。 + +## 预览效果 +![](./screenshots/device/Effect.gif) + +## 工程目录 +``` +├──entry/src/main/ets // 代码区 +│ ├──entryability +│ │ └──EntryAbility.ets // 程序入口类 +│ ├──entrybackupability +│ │ └──EntryBackupAbility.ets +│ ├──pages +│ │ ├──CustomDialogDisplayAndExitAnimations.ets // 自定义弹窗显示和退出动画示例 +│ │ ├──CustomDialogNotDisappear.ets // 切换页面弹窗不消失示例 +│ │ ├──GlobalDialogDecoupledFromThePage.ets // 与页面解耦的全局弹窗示例 +│ │ ├──Index.ets // 入口文件 +│ │ ├──InterceptReturn01.ets // 拦截物理返回按钮、手势滑动关闭弹窗示例一 +│ │ └──InterceptReturn02.ets // 拦截物理返回按钮、手势滑动关闭弹窗示例二 +│ └──utils.ets +│ └──DialogComponent.ets // 自定义弹窗封装组件 +└──entry/src/main/resources // 应用资源目录 +``` +## 使用说明 +依次点击应用首页的5个按钮,进入后可以实现以下4个场景: +* 与页面解耦的全局弹窗示例(按钮1) +* 拦截物理返回按钮示例(按钮2、3) +* 切换页面弹窗不消失(按钮4) +* 自定义弹窗显示和退出动画示例(按钮5) + +## 实现说明 +* 全局弹窗可以通过UIContext.getPromptAction弹窗实现,具体参考[与页面解耦的全局弹窗](https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-custome-dialog-development-practice-V5#section7466312192919) +* 物理拦截通过弹窗的选项对象中的onWillDismiss交互式关闭回调函数,或者基于Navigation自定义弹窗,使用NavDestination的回调函数onBackPressed实现,具体参考[拦截物理返回按钮、手势滑动关闭弹窗](https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-custome-dialog-development-practice-V5#section111721345172917) +* 切换页面弹窗不消失,通过Navigation.Dialog弹窗实现,NavDestinationMode.DIALOG弹窗存在于路由栈中,可以实现切换页面弹窗不消失,具体参考[切换页面弹窗不消失](https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-custome-dialog-development-practice-V5#section690764913302) +* 自定义弹窗显示和退出动画,基于UIContext.getPromptAction弹窗实现,通过CustomDialogOptions自定义弹窗的内容,BaseDialogOptions弹窗选项transition参数可以设置弹窗显示和退出的过渡效果,具体参考[自定义弹窗显示和退出动画](https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-custome-dialog-development-practice-V5#section621242223120) + +## 相关权限 +无 + +## 约束与限制 +* 本示例仅支持标准系统上运行,支持设备:华为手机。 + +* HarmonyOS系统:HarmonyOS NEXT Release及以上。 + +* DevEco Studio版本:DevEco Studio NEXT Release及以上。 + +* HarmonyOS SDK版本:HarmonyOS NEXT Release SDK及以上。 \ No newline at end of file diff --git a/CustomDialogPractice/build-profile.json5 b/CustomDialogPractice/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c033ce4278fb0641d84107c3c134047ac487368e --- /dev/null +++ b/CustomDialogPractice/build-profile.json5 @@ -0,0 +1,35 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS", + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/.gitignore b/CustomDialogPractice/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d2ff20141ceed86d87c0ea5d99481973005bab2b --- /dev/null +++ b/CustomDialogPractice/entry/.gitignore @@ -0,0 +1,12 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +/.appanalyzer \ No newline at end of file diff --git a/CustomDialogPractice/entry/build-profile.json5 b/CustomDialogPractice/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..b695582d3680556f4cce2ec518f65720a9413ca3 --- /dev/null +++ b/CustomDialogPractice/entry/build-profile.json5 @@ -0,0 +1,28 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": true, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + } + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/hvigorfile.ts b/CustomDialogPractice/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6edcd90486dd5a853cf7d34c8647f08414ca7a3 --- /dev/null +++ b/CustomDialogPractice/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/CustomDialogPractice/entry/obfuscation-rules.txt b/CustomDialogPractice/entry/obfuscation-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..fdbb5b9852d7dd5f39bddaeb21ab5ee1f3346749 --- /dev/null +++ b/CustomDialogPractice/entry/obfuscation-rules.txt @@ -0,0 +1,22 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5 + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope +-enable-property-obfuscation +-enable-toplevel-obfuscation +-enable-filename-obfuscation +-enable-export-obfuscation \ No newline at end of file diff --git a/CustomDialogPractice/entry/oh-package.json5 b/CustomDialogPractice/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..248c3b7541a589682a250f86a6d3ecf7414d2d6a --- /dev/null +++ b/CustomDialogPractice/entry/oh-package.json5 @@ -0,0 +1,10 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": {} +} + diff --git a/CustomDialogPractice/entry/src/main/ets/entryability/EntryAbility.ets b/CustomDialogPractice/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..217744d8eb6d893e1138cd660209ce4d0441ac4f --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); + } +} diff --git a/CustomDialogPractice/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/CustomDialogPractice/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..6b744d7eaa66e51e79fc4e0896e251292ee767c5 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; + +export default class EntryBackupAbility extends BackupExtensionAbility { + async onBackup() { + hilog.info(0x0000, 'testTag', 'onBackup ok'); + } + + async onRestore(bundleVersion: BundleVersion) { + hilog.info(0x0000, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion)); + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/pages/CustomDialogDisplayAndExitAnimations.ets b/CustomDialogPractice/entry/src/main/ets/pages/CustomDialogDisplayAndExitAnimations.ets new file mode 100644 index 0000000000000000000000000000000000000000..c25234e7d305ba43b906ff26660d84e59971c5f1 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/pages/CustomDialogDisplayAndExitAnimations.ets @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { PromptAction } from '@kit.ArkUI'; + +@Component +export struct CustomDialogDisplayAndExitAnimations { + private promptAction: PromptAction = this.getUIContext().getPromptAction(); + private customDialogComponentId: number = 0; + @Consume('NavPathStack') pageStack: NavPathStack; + + @Builder + customDialogComponent() { + Column() { + Row() { + Text('Title') + .fontSize(20) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height(56) + .justifyContent(FlexAlign.Center) + + Text('This is a custom dialog box with different entrance and exit animations.') + .fontSize(14) + .width('100%') + + Button('CONFIRM') + .fontSize(16) + .fontColor('#0A59F7') + .backgroundColor(Color.White) + .onClick(() => { + this.promptAction.closeCustomDialog(this.customDialogComponentId); + }) + .width('100%') + .margin({ + top: 8, + bottom: 16 + }) + } + .padding({ + left: 24, + right: 24 + }) + .width('100%') + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + .backgroundColor(Color.White) + .borderRadius(32) + } + + build() { + NavDestination() { + Column() { + Row() { + Button('OPEN') + .fontSize(16) + .width('100%') + .borderRadius(20) + .margin({ bottom: 16 }) + .backgroundColor('#0A59F7') + .onClick(() => { + this.promptAction.openCustomDialog({ + builder: () => { + this.customDialogComponent(); + }, + alignment: DialogAlignment.Center, + maskColor: 'rgba(0, 0, 0, 0.2)', + // Set two animations, corresponding to the pop-up window display and hidden animation respectively. + transition: TransitionEffect.asymmetric( + TransitionEffect.OPACITY + .animation({ duration: 1000 }) + .combine( + TransitionEffect + .translate({ y: 1000 }) + .animation({ duration: 1000 })) + , + TransitionEffect.OPACITY + .animation({ delay: 1000, duration: 1000 }) + .combine( + TransitionEffect + .translate({ y: 1000 }) + .animation({ duration: 1000 })) + ) + }).then((dialogId: number) => { + this.customDialogComponentId = dialogId; + }) + }) + } + .width('100%') + .alignItems(VerticalAlign.Center) + } + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) + .justifyContent(FlexAlign.End) + } + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/pages/CustomDialogNotDisappear.ets b/CustomDialogPractice/entry/src/main/ets/pages/CustomDialogNotDisappear.ets new file mode 100644 index 0000000000000000000000000000000000000000..696f1df94dff52118c2c68f068bd92f9e4da817c --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/pages/CustomDialogNotDisappear.ets @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +export struct CustomDialogNotDisappear { + @Consume('NavPathStack') pageStack: NavPathStack; + + build() { + NavDestination() { + Column() { + Row() { + Button('OPEN') + .fontSize(16) + .width('100%') + .borderRadius(20) + .margin({ bottom: 16 }) + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('DialogPage', ''); + }) + } + .width('100%') + .alignItems(VerticalAlign.Center) + } + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) + .justifyContent(FlexAlign.End) + } + } +} + +@Component +export struct DialogPage { + @Consume('NavPathStack') pageStack: NavPathStack; + + build() { + NavDestination() { + Stack({ alignContent: Alignment.Center }) { + Column() { + Row() { + Text('Title') + .fontSize(20) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height(56) + .justifyContent(FlexAlign.Center) + + Text('This is a dialog content.') + .fontSize(14) + + Button('CONFIRM') + .fontSize(16) + .fontColor('#0A59F7') + .backgroundColor(Color.White) + .onClick(() => { + this.pageStack.pushPathByName('PageOne', 'PageOne Param'); + }) + .width('100%') + .margin({ + top: 8, + bottom: 16 + }) + } + .padding({ + left: 24, + right: 24 + }) + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + .backgroundColor(Color.White) + .borderRadius(32) + .margin({ + left: 16, + right: 16 + }) + } + .height('100%') + .width('100%') + } + .backgroundColor('rgba(0,0,0,0.2)') + .hideTitleBar(true) + .mode(NavDestinationMode.DIALOG) + } +} + +@Component +export struct PageOne { + @Consume('NavPathStack') pageStack: NavPathStack; + + build() { + NavDestination() { + Stack({ alignContent: Alignment.Center }) { + Column() { + Row() { + Image($r('app.media.Back')) + .width(40) + .height(40) + .margin({ right: 8 }) + .onClick(() => { + this.pageStack.pop(); + }) + + Text('Back') + .fontSize(20) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height(56) + .justifyContent(FlexAlign.Start) + } + .backgroundColor('#F1F3F5') + .padding({ + left: 16, + right: 16 + }) + .height('100%') + .width('100%') + } + .height('100%') + .width('100%') + } + .backgroundColor('#F1F3F5') + .hideTitleBar(true) + .mode(NavDestinationMode.DIALOG) + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/pages/GlobalDialogDecoupledFromThePage.ets b/CustomDialogPractice/entry/src/main/ets/pages/GlobalDialogDecoupledFromThePage.ets new file mode 100644 index 0000000000000000000000000000000000000000..f1697725e5bbd7076f06f5b9f55ed96e4491d2b1 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/pages/GlobalDialogDecoupledFromThePage.ets @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { buildText } from '../uitls/DialogComponent'; +import { PromptAction } from '@kit.ArkUI'; + +@Component +export struct GlobalDialogDecoupledFromThePage { + promptAction: PromptAction = this.getUIContext().getPromptAction(); + @State message: string = 'This is a dialog content.'; + @Consume('NavPathStack') pageStack: NavPathStack; + + @Builder + customDialogComponent() { + buildText({ message: this.message }) + } + + build() { + NavDestination() { + Column() { + Row() { + Button('OPEN') + .fontSize(16) + .width('100%') + .borderRadius(20) + .margin({ bottom: 16 }) + .backgroundColor('#0A59F7') + .onClick(() => { + this.promptAction.openCustomDialog({ + builder: () => { + this.customDialogComponent() + }, + alignment: DialogAlignment.Center, + maskColor: 'rgba(0, 0, 0, 0.2)', + }).then((dialogId: number) => { + AppStorage.setOrCreate('dialogId', dialogId); + }) + }) + } + .width('100%') + .alignItems(VerticalAlign.Center) + } + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) + .justifyContent(FlexAlign.End) + } + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/pages/Index.ets b/CustomDialogPractice/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..079a30e32815eca294ce4fc2550679a4e611aaa0 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { GlobalDialogDecoupledFromThePage } from '../pages/GlobalDialogDecoupledFromThePage'; +import { InterceptReturn01 } from '../pages/InterceptReturn01'; +import { InterceptReturn02, DialogPage1 } from '../pages/InterceptReturn02'; +import { CustomDialogNotDisappear, PageOne, DialogPage } from '../pages/CustomDialogNotDisappear'; +import { CustomDialogDisplayAndExitAnimations } from '../pages/CustomDialogDisplayAndExitAnimations'; + +@Entry +@Component +struct Index { + @Provide('NavPathStack') pageStack: NavPathStack = new NavPathStack(); + + @Builder + PagesMap(name: string) { + if (name === 'GlobalDialogDecoupledFromThePage') { + GlobalDialogDecoupledFromThePage() + } + else if (name === 'InterceptReturn01') { + InterceptReturn01() + } + else if (name === 'InterceptReturn02') { + InterceptReturn02() + } + else if (name === 'CustomDialogNotDisappear') { + CustomDialogNotDisappear() + } + else if (name === 'CustomDialogDisplayAndExitAnimations') { + CustomDialogDisplayAndExitAnimations() + } + else if (name === 'DialogPage') { + DialogPage() + } + else if (name === 'DialogPage1') { + DialogPage1() + } + else if (name === 'PageOne') { + PageOne() + } + } + + build() { + Navigation(this.pageStack) { + Column() { + Column({ space: 12 }) { + Button('Dialog Decoupled From The Page') + .width('100%') + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('GlobalDialogDecoupledFromThePage', ''); + }) + + Button('Intercept Return') + .width('100%') + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('InterceptReturn01', ''); + }) + + Button('Intercept Return') + .width('100%') + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('InterceptReturn02', ''); + }) + + Button('Dialog Not Disappear') + .width('100%') + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('CustomDialogNotDisappear', ''); + }) + + Button('Dialog Display And ExitAnimations') + .width('100%') + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('CustomDialogDisplayAndExitAnimations', ''); + }) + } + .width('100%') + .justifyContent(FlexAlign.End) + } + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) + .justifyContent(FlexAlign.End) + } + .title('Use of CustomDialog') + .height('100%') + .width('100%') + .navDestination(this.PagesMap) + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/pages/InterceptReturn01.ets b/CustomDialogPractice/entry/src/main/ets/pages/InterceptReturn01.ets new file mode 100644 index 0000000000000000000000000000000000000000..e18f8fa22f538a2892d3396a1e3a53ee576a0fa9 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/pages/InterceptReturn01.ets @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { PromptAction } from '@kit.ArkUI'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +@Component +export struct InterceptReturn01 { + private context: UIContext = this.getUIContext(); + private promptAction: PromptAction = this.getUIContext().getPromptAction(); + private customDialogComponentId: number = 0; + @Consume('NavPathStack') pageStack: NavPathStack; + + @Builder + customDialogComponent() { + Column() { + Row() { + Text('Title') + .fontSize(20) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height(56) + .justifyContent(FlexAlign.Center) + + Text('This is a dialog content.') + .fontSize(14) + + Button('CONFIRM') + .fontSize(16) + .fontColor('#0A59F7') + .backgroundColor(Color.White) + .onClick(() => { + this.context.getPromptAction().closeCustomDialog(this.customDialogComponentId); + }) + .width('100%') + .margin({ + top: 8, + bottom: 16 + }) + } + .padding({ + left: 24, + right: 24 + }) + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + .backgroundColor(Color.White) + .borderRadius(32) + .margin({ + left: 16, + right: 16 + }) + } + + build() { + NavDestination() { + Column() { + Row() { + Button('OPEN') + .fontSize(16) + .width('100%') + .borderRadius(20) + .margin({ bottom: 16 }) + .backgroundColor('#0A59F7') + .onClick(() => { + this.promptAction.openCustomDialog({ + builder: () => { + this.customDialogComponent() + }, + alignment: DialogAlignment.Center, + maskColor: 'rgba(0, 0, 0, 0.2)', + onWillDismiss: (dismissDialogAction: DismissDialogAction) => { + hilog.info(0xFF00, "testTag", JSON.stringify(dismissDialogAction.reason)); + } + }).then((dialogId: number) => { + this.customDialogComponentId = dialogId + }) + }) + } + .width('100%') + .alignItems(VerticalAlign.Center) + } + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) + .justifyContent(FlexAlign.End) + } + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/pages/InterceptReturn02.ets b/CustomDialogPractice/entry/src/main/ets/pages/InterceptReturn02.ets new file mode 100644 index 0000000000000000000000000000000000000000..d12af8d4869fec9cdcbdb85be890f183fbe5a0b2 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/pages/InterceptReturn02.ets @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Component +export struct InterceptReturn02 { + @Consume('NavPathStack') pageStack: NavPathStack; + + build() { + NavDestination() { + Column() { + Row() { + Button('OPEN') + .fontSize(16) + .width('100%') + .borderRadius(20) + .margin({ bottom: 16 }) + .backgroundColor('#0A59F7') + .onClick(() => { + this.pageStack.pushPathByName('DialogPage1', ''); + }) + } + .width('100%') + .alignItems(VerticalAlign.Center) + } + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) + .justifyContent(FlexAlign.End) + } + } +} + +@Component +export struct DialogPage1 { + @Consume('NavPathStack') pageStack: NavPathStack; + + build() { + NavDestination() { + Stack({ alignContent: Alignment.Center }) { + Column() { + Row() { + Text('Title') + .fontSize(20) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height(56) + .justifyContent(FlexAlign.Center) + + Text('This is a dialog content.') + .fontSize(14) + + Button('CONFIRM') + .fontSize(16) + .fontColor('#0A59F7') + .backgroundColor(Color.White) + .onClick(() => { + this.pageStack.pop(); + }) + .width('100%') + .margin({ + top: 8, + bottom: 16 + }) + } + .padding({ + left: 24, + right: 24 + }) + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + .backgroundColor(Color.White) + .borderRadius(32) + .margin({ + left: 16, + right: 16 + }) + } + .height('100%') + .width('100%') + } + .backgroundColor('rgba(0, 0, 0, 0.2)') + .hideTitleBar(true) + .mode(NavDestinationMode.DIALOG) + .onBackPressed((): boolean => { + return true; + }) + .borderColor(Color.White) + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/ets/uitls/DialogComponent.ets b/CustomDialogPractice/entry/src/main/ets/uitls/DialogComponent.ets new file mode 100644 index 0000000000000000000000000000000000000000..0ec6141548aff337236e7400324172798595adbe --- /dev/null +++ b/CustomDialogPractice/entry/src/main/ets/uitls/DialogComponent.ets @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { promptAction } from "@kit.ArkUI"; + +// DocsCode 1 +@Component +export struct buildText { + @Prop message: string = ''; + + build() { + Column() { + Row() { + Text('Title') + .fontSize(20) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height(56) + .justifyContent(FlexAlign.Center) + + Text(this.message) + .fontSize(14) + + Button('CONFIRM') + .fontSize(16) + .fontColor('#0A59F7') + .backgroundColor(Color.White) + .onClick(() => { + let dialogId = AppStorage.get('dialogId'); + promptAction.closeCustomDialog(dialogId) + }) + .width('100%') + .margin({ + top: 8, + bottom: 16 + }) + } + .padding({ + left: 24, + right: 24 + }) + .justifyContent(FlexAlign.Center) + .alignItems(HorizontalAlign.Center) + .backgroundColor(Color.White) + .borderRadius(32) + .margin({ left: 16, right: 16 }) + } +} + +// DocsCode 1 \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/module.json5 b/CustomDialogPractice/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..a1cea8b6a4560cee7bda7a2db52f310c035ab6c8 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/module.json5 @@ -0,0 +1,52 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone", + "tablet", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:layered_image", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "name": "EntryBackupAbility", + "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets", + "type": "backup", + "exported": false, + "metadata": [ + { + "name": "ohos.extension.backup", + "resource": "$profile:backup_config" + } + ], + } + ] + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/resources/base/element/color.json b/CustomDialogPractice/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/resources/base/element/string.json b/CustomDialogPractice/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f6442c29a01a3024d9616827cb112d63ee49f01b --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "CustomDialogPractice" + } + ] +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/resources/base/media/background.png b/CustomDialogPractice/entry/src/main/resources/base/media/background.png new file mode 100644 index 0000000000000000000000000000000000000000..f939c9fa8cc8914832e602198745f592a0dfa34d Binary files /dev/null and b/CustomDialogPractice/entry/src/main/resources/base/media/background.png differ diff --git a/CustomDialogPractice/entry/src/main/resources/base/media/foreground.png b/CustomDialogPractice/entry/src/main/resources/base/media/foreground.png new file mode 100644 index 0000000000000000000000000000000000000000..4483ddad1f079e1089d685bd204ee1cfe1d01902 Binary files /dev/null and b/CustomDialogPractice/entry/src/main/resources/base/media/foreground.png differ diff --git a/CustomDialogPractice/entry/src/main/resources/base/media/layered_image.json b/CustomDialogPractice/entry/src/main/resources/base/media/layered_image.json new file mode 100644 index 0000000000000000000000000000000000000000..fb49920440fb4d246c82f9ada275e26123a2136a --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/base/media/layered_image.json @@ -0,0 +1,7 @@ +{ + "layered-image": + { + "background" : "$media:background", + "foreground" : "$media:foreground" + } +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/resources/base/media/startIcon.png b/CustomDialogPractice/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b Binary files /dev/null and b/CustomDialogPractice/entry/src/main/resources/base/media/startIcon.png differ diff --git a/CustomDialogPractice/entry/src/main/resources/base/profile/backup_config.json b/CustomDialogPractice/entry/src/main/resources/base/profile/backup_config.json new file mode 100644 index 0000000000000000000000000000000000000000..78f40ae7c494d71e2482278f359ec790ca73471a --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/base/profile/backup_config.json @@ -0,0 +1,3 @@ +{ + "allowToBackupRestore": true +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/resources/base/profile/main_pages.json b/CustomDialogPractice/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/CustomDialogPractice/entry/src/main/resources/en_US/element/string.json b/CustomDialogPractice/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f6442c29a01a3024d9616827cb112d63ee49f01b --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "CustomDialogPractice" + } + ] +} \ No newline at end of file diff --git a/CustomDialogPractice/entry/src/main/resources/zh_CN/element/string.json b/CustomDialogPractice/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..163fe824a0f7388f25d7052a772747e7f0200ea1 --- /dev/null +++ b/CustomDialogPractice/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "CustomDialogPractice" + } + ] +} \ No newline at end of file diff --git a/CustomDialogPractice/hvigor/hvigor-config.json5 b/CustomDialogPractice/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..06b2783670a348f95533b352c1ceda909a842bbc --- /dev/null +++ b/CustomDialogPractice/hvigor/hvigor-config.json5 @@ -0,0 +1,22 @@ +{ + "modelVersion": "5.0.0", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} diff --git a/CustomDialogPractice/hvigorfile.ts b/CustomDialogPractice/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3cb9f1a87a81687554a76283af8df27d8bda775 --- /dev/null +++ b/CustomDialogPractice/hvigorfile.ts @@ -0,0 +1,6 @@ +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/CustomDialogPractice/oh-package.json5 b/CustomDialogPractice/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..1b8c11ffdf211f76b5774b08e8f5bb2cceb93c55 --- /dev/null +++ b/CustomDialogPractice/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "modelVersion": "5.0.0", + "description": "Please describe the basic information.", + "dependencies": {}, + "devDependencies": {} +} diff --git a/CustomDialogPractice/screenshots/device/Effect.gif b/CustomDialogPractice/screenshots/device/Effect.gif new file mode 100644 index 0000000000000000000000000000000000000000..951b10f11d1e73b80f9206ee9635f3661d1856a1 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/Effect.gif differ diff --git a/CustomDialogPractice/screenshots/device/image01.png b/CustomDialogPractice/screenshots/device/image01.png new file mode 100644 index 0000000000000000000000000000000000000000..ed1fc2d82d5a51b9ee720a0b9b0f6566e95364fb Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image01.png differ diff --git a/CustomDialogPractice/screenshots/device/image02.png b/CustomDialogPractice/screenshots/device/image02.png new file mode 100644 index 0000000000000000000000000000000000000000..a6e7629cabea6f4051d60199c11dd1f15f3b9880 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image02.png differ diff --git a/CustomDialogPractice/screenshots/device/image03.png b/CustomDialogPractice/screenshots/device/image03.png new file mode 100644 index 0000000000000000000000000000000000000000..b5d0dfb958c658f61d3e2cf6680477012b3ec426 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image03.png differ diff --git a/CustomDialogPractice/screenshots/device/image04.png b/CustomDialogPractice/screenshots/device/image04.png new file mode 100644 index 0000000000000000000000000000000000000000..3b2056c02728857fb917a0726d5e2c8c1010dcd1 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image04.png differ diff --git a/CustomDialogPractice/screenshots/device/image05.png b/CustomDialogPractice/screenshots/device/image05.png new file mode 100644 index 0000000000000000000000000000000000000000..163f026886a7f76bd033aa1d3570d7b37424b645 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image05.png differ diff --git a/CustomDialogPractice/screenshots/device/image06.png b/CustomDialogPractice/screenshots/device/image06.png new file mode 100644 index 0000000000000000000000000000000000000000..aa1e92d5c2dca4460f716c431f68e7f4d92bb5e5 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image06.png differ diff --git a/CustomDialogPractice/screenshots/device/image07.png b/CustomDialogPractice/screenshots/device/image07.png new file mode 100644 index 0000000000000000000000000000000000000000..2a76ff49d0e74ab26bb2bab9ee973c9798a9d462 Binary files /dev/null and b/CustomDialogPractice/screenshots/device/image07.png differ diff --git a/NdkQoS/AppScope/app.json5 b/NdkQoS/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..677efa72eb9db1e8570f0badac590daa4fed2dc4 --- /dev/null +++ b/NdkQoS/AppScope/app.json5 @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "bundleName": "com.example.qossample", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/NdkQoS/AppScope/resources/base/element/string.json b/NdkQoS/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..71f7d544aadc59a299e26532be96853152283cc3 --- /dev/null +++ b/NdkQoS/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "QoSSample" + } + ] +} diff --git a/NdkQoS/AppScope/resources/base/media/app_icon.png b/NdkQoS/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..cd45accb1dfd2fd0da16c732c72faa6e46b26521 Binary files /dev/null and b/NdkQoS/AppScope/resources/base/media/app_icon.png differ diff --git a/NdkQoS/README.md b/NdkQoS/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fbdd5003dda677fbfdd37bcc0c537fe79882b71 --- /dev/null +++ b/NdkQoS/README.md @@ -0,0 +1,72 @@ +# 基于QoS设置线程优先级 + +### 介绍 + +本示例中主要介绍开发者如何使用Native QoS的接口来设置、查询以及重置线程的QoS等级,并在界面上显示不同QoS等级的线程完成相同计算任务的时间。功能主要包括点击不同的按钮分别创建高、低QoS等级的线程来完成同样的复杂计算任务。在计算完成后,弹窗显示当前创建线程完成任务执行所花费的时间。 + +### 效果预览 + +![](./screenshots/device/qos-protect-critical-threads.gif) + +#### 使用说明 + +1. 安装编译生成的hap包,并打开应用。 + +2. 点击页面中间的“High level QoS test”按钮或者“Low level QoS test”按钮,页面将弹窗显示使用该QoS等级创建的线程完成计算任务所花费的时间。 + +### 工程目录 + +``` +├──entry/src/main +│ └──cpp // C++代码区 +│ ├──CMakeLists.txt // CMake配置文件 +│ ├──main.cpp // QoS调用相关逻辑实现 +│ └──types +│ └──libentry +│ └──index.d.ts // native侧暴露给ArkTS侧接口的声明 +├──ets // ets代码区 +│ ├──entryability +│ │ └──EntryAbility.ts // 程序入口类 +│ └──pages // 页面文件 +│ └──Index.ets // 主界面 +└──entry/src/main/resources // 应用资源目录 +``` + +### 具体实现 +通过在IDE中创建Native C++ 工程,在C++代码中定义对外接口为useHighQos和useLowQos,在ArkTS侧调用该接口可在系统中创建对应QoS等级的线程完成任务。 + +每次调用useHighQos或useLowQos时,会先在系统中启动若干线程模拟系统负载(如果之前已经启动了相关的线程,则不再重复启动)。系统负载模拟完成后,会单独启动一个新的、用于完成计算任务的线程,并根据ArkTS侧实际调用的接口,调用设置QoS等级的接口为线程设置不同的QoS等级。为了更加清楚地展示不同QoS等级之间的效果区别,本样例中将负载线程以及设置了QoS等级用于完成任务计算的线程都绑到同一个CPU核上。样例运行中,可以通过日志查看线程设置QoS等级的结果,如果设置成功则会查询该线程的QoS等级,并通过日志打印出来,以此判断是否符合预期。 + +新启动的线程会执行斐波那契数列某项数值的计算。当计算完成后,会重置该线程的QoS等级,然后返回整个计算完成的时间(单位毫秒)到ArkTS侧,并通过弹窗显示该时间。 + + +源码参考:[cpp目录](entry/src/main/cpp/main.cpp)下的文件。 + +涉及到的相关接口: + +| 接口名 | 描述 | +| -------- | -------- | +| OH_QoS_SetThreadQoS(QoS_Level level) | 设置当前任务的QoS等级 | +| OH_QoS_ResetThreadQoS() | 取消当前任务设置的QoS等级 | +| OH_QoS_GetThreadQoS(QoS_Level *level) | 获取当前任务的QoS等级 | + + +详细的接口说明请参考[NativeQoS](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/qos-guidelines-V5)。 + +### 相关权限 + +不涉及。 + +### 依赖 + +不涉及。 + +### 约束与限制 + +1.本示例仅支持标准系统上运行,支持设备:华为手机。 + +2.HarmonyOS系统:HarmonyOS NEXT Release及以上。 + +3.DevEco Studio版本:DevEco Studio NEXT Release及以上。 + +4.HarmonyOS SDK版本:HarmonyOS NEXT Release SDK及以上。 diff --git a/NdkQoS/build-profile.json5 b/NdkQoS/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..6acb5d20f296aac8ec2a19f839a7ecc032f9d2da --- /dev/null +++ b/NdkQoS/build-profile.json5 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS" + } + ], + "buildModeSet": [ + { + "name": "debug", + }, + { + "name": "release" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} diff --git a/NdkQoS/entry/build-profile.json5 b/NdkQoS/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..c55d07243fd079a446d490ef5f603debb4879b14 --- /dev/null +++ b/NdkQoS/entry/build-profile.json5 @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": "stageMode", + "buildOption": { + "externalNativeOptions": { + "path": "./src/main/cpp/CMakeLists.txt", + "arguments": "", + "cppFlags": "", + "abiFilters": [ + "arm64-v8a","x86_64" + ] + } + }, + "buildOptionSet": [ + { + "name": "release", + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": true, + "files": [ + "./obfuscation-rules.txt" + ] + } + } + }, + "nativeLib": { + "debugSymbol": { + "strip": true, + "exclude": [] + } + } + }, + ], + "targets": [ + { + "name": "default" + }, + { + "name": "ohosTest", + } + ] +} diff --git a/NdkQoS/entry/hvigorfile.ts b/NdkQoS/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6edcd90486dd5a853cf7d34c8647f08414ca7a3 --- /dev/null +++ b/NdkQoS/entry/hvigorfile.ts @@ -0,0 +1,6 @@ +import { hapTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/NdkQoS/entry/obfuscation-rules.txt b/NdkQoS/entry/obfuscation-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..985b2aeb7658286b17bd26eab8f217c3fe75ea8b --- /dev/null +++ b/NdkQoS/entry/obfuscation-rules.txt @@ -0,0 +1,18 @@ +# Define project specific obfuscation rules here. +# You can include the obfuscation configuration files in the current module's build-profile.json5. +# +# For more details, see +# https://gitee.com/openharmony/arkcompiler_ets_frontend/blob/master/arkguard/README.md + +# Obfuscation options: +# -disable-obfuscation: disable all obfuscations +# -enable-property-obfuscation: obfuscate the property names +# -enable-toplevel-obfuscation: obfuscate the names in the global scope +# -compact: remove unnecessary blank spaces and all line feeds +# -remove-log: remove all console.* statements +# -print-namecache: print the name cache that contains the mapping from the old names to new names +# -apply-namecache: reuse the given cache file + +# Keep options: +# -keep-property-name: specifies property names that you want to keep +# -keep-global-name: specifies names that you want to keep in the global scope \ No newline at end of file diff --git a/NdkQoS/entry/oh-package.json5 b/NdkQoS/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..54cb066266f9993f5a023f2ac5a8dfc5d2574643 --- /dev/null +++ b/NdkQoS/entry/oh-package.json5 @@ -0,0 +1,11 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "libentry.so": "file:./src/main/cpp/types/libentry" + } +} \ No newline at end of file diff --git a/NdkQoS/entry/src/main/cpp/CMakeLists.txt b/NdkQoS/entry/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9bcaac120f1c2f6fbb73c1c73691166589c054a7 --- /dev/null +++ b/NdkQoS/entry/src/main/cpp/CMakeLists.txt @@ -0,0 +1,15 @@ +# the minimum version of CMake. +cmake_minimum_required(VERSION 3.4.1) +project(rtbandwidth) + +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + +if(DEFINED PACKAGE_FIND_FILE) + include(${PACKAGE_FIND_FILE}) +endif() + +include_directories(${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include) + +add_library(entry SHARED main.cpp) +target_link_libraries(entry libace_napi.z.so libqos.so libhilog_ndk.z.so) \ No newline at end of file diff --git a/NdkQoS/entry/src/main/cpp/main.cpp b/NdkQoS/entry/src/main/cpp/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8132541db0caeabfd2d0a8e2e3a24a70e70769d0 --- /dev/null +++ b/NdkQoS/entry/src/main/cpp/main.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "napi/native_api.h" +#include "qos/qos.h" + +const unsigned int LOG_PRINT_DOMAIN = 0xFF00; +constexpr int DEPTH = 34; +constexpr int TASKS = 3; // Number of loaded threads +constexpr long long ONE = 1; +constexpr long long TWO = 2; +constexpr int BOUND = 20000; + +static bool g_addLoad = false; // if loaded threads is add +static double g_durationTime = 0; // Calculate task time consumption + +static int g_mask = 2; // bind cpu +static int *g_affinity = &g_mask; + +// DocsCode2 +// Perform Fibonacci sequence calculations +long long DoFib(double n) { + if (n == ONE) { + return ONE; + } + if (n == TWO) { + return TWO; + } + return DoFib(n - ONE) + DoFib(n - TWO); +} + +void SetQoS(QoS_Level level) { + // set QoS level + int ret = OH_QoS_SetThreadQoS(level); + if (!ret) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "QoS", "set qos level success."); + // query qos level + QoS_Level queryLevel = QOS_DEFAULT; + ret = OH_QoS_GetThreadQoS(&queryLevel); + if (!ret) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "QoS", "the qos level of current thread : %{public}d", + queryLevel); + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "get qos level failed."); + return; + } + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "get level qos failed!"); + return; + } + + // bind cpu + cpu_set_t mask; + CPU_SET(*g_affinity, &mask); + if (sched_setaffinity(0, sizeof(mask), &mask) != 0) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "bind qos thread failed"); + return; + } + auto startTime = std::chrono::system_clock::now(); + // Execute computational tasks + long long res = DoFib(DEPTH); + auto endTime = std::chrono::system_clock::now(); + g_durationTime = std::chrono::duration(endTime - startTime).count(); + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "QoS", "calculate res is: %{public}llu", res); + + // Reset QoS level + ret = OH_QoS_ResetThreadQoS(); + if (!ret) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "QoS", "reset qos level success."); + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "reset qos level failed!"); + return; + } + + // after reset QoS, query QoS again will fail + QoS_Level queryLevelTwo; + ret = OH_QoS_GetThreadQoS(&queryLevelTwo); + if (!ret) { + OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "QoS", "the qos level after: %{public}d", queryLevelTwo); + return; + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "querry qos level failed after reset."); + return; + } +} + +// DocsCode2 + +// DocsCode1 +// the Load task +void AddLoads(int n) { + if (!n) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "invalid input."); + return; + } + + // set QoS level + int ret = OH_QoS_SetThreadQoS(QoS_Level::QOS_BACKGROUND); + if (ret) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "set load thread QoS level failed."); + return; + } + + // bind cpu + cpu_set_t mask; + CPU_SET(*g_affinity, &mask); + if (sched_setaffinity(0, sizeof(mask), &mask) != 0) { + OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "QoS", "bind load thread failed"); + return; + } + // Perform load calculation + for (int i = 0; i < BOUND; i++) { + for (int j = 0; j < BOUND; j++) { + int x = (i + j) - n; + printf("%d", x); + } + } + // reset load flag + g_addLoad = false; +} +// DocsCode1 + +// DocsCode4 +static napi_value highQoSCalculate(napi_env env, napi_callback_info info) { + g_durationTime = 0; + // Simulate system load + if (!g_addLoad) { + std::vector loadThreads; + for (int i = 0; i < TASKS; i++) { + // Activate threads to execute load tasks + loadThreads.emplace_back(std::thread(AddLoads, TASKS)); + loadThreads[i].detach(); + } + g_addLoad = true; + } + // set QOS_USER_INTERACTIVE level + QoS_Level level = QoS_Level::QOS_USER_INTERACTIVE; + std::thread task(SetQoS, level); + task.join(); + + // Return calculation time + napi_value res; + napi_create_double(env, g_durationTime, &res); + return res; +} +// DocsCode4 + +// DocsCode3 +static napi_value lowQoSCalculate(napi_env env, napi_callback_info info) { + g_durationTime = 0; + // Simulate system load + if (!g_addLoad) { + std::vector loadThreads; + for (int i = 0; i < TASKS; i++) { + // Activate threads to execute load tasks + loadThreads.emplace_back(std::thread(AddLoads, TASKS)); + loadThreads[i].detach(); + } + g_addLoad = true; + } + + // set QOS_BACKGROUND level + QoS_Level level = QoS_Level::QOS_BACKGROUND; + std::thread task(SetQoS, level); + task.join(); + + // Return calculation time + napi_value res; + napi_create_double(env, g_durationTime, &res); + return res; +} +// DocsCode3 + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"useHighQos", nullptr, highQoSCalculate, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"useLowQos", nullptr, lowQoSCalculate, nullptr, nullptr, nullptr, napi_default, nullptr}}; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END + +static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); } \ No newline at end of file diff --git a/NdkQoS/entry/src/main/cpp/types/libentry/index.d.ts b/NdkQoS/entry/src/main/cpp/types/libentry/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec633cf8508d718521e36eef79f722f0ae8a8b95 --- /dev/null +++ b/NdkQoS/entry/src/main/cpp/types/libentry/index.d.ts @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const useHighQos: () => number; +export const useLowQos: () => number; \ No newline at end of file diff --git a/NdkQoS/entry/src/main/cpp/types/libentry/oh-package.json5 b/NdkQoS/entry/src/main/cpp/types/libentry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..8c49cae229917b627c5b40b536d6e8115b59f080 --- /dev/null +++ b/NdkQoS/entry/src/main/cpp/types/libentry/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libentry.so", + "types": "./index.d.ts", + "version": "", + "description": "Please describe the basic information." +} \ No newline at end of file diff --git a/NdkQoS/entry/src/main/ets/entryability/EntryAbility.ets b/NdkQoS/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..21b42ac664a4a101c79968e8bbda723310987c38 --- /dev/null +++ b/NdkQoS/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); + } + + onDestroy(): void { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage): void { + // Main window is created, set main page for this ability + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); + }); + } + + onWindowStageDestroy(): void { + // Main window is destroyed, release UI related resources + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + } + + onForeground(): void { + // Ability has brought to foreground + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); + } + + onBackground(): void { + // Ability has back to background + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); + } +}; diff --git a/NdkQoS/entry/src/main/ets/pages/Index.ets b/NdkQoS/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..cf8d1181a462390921444022526053869f1e009f --- /dev/null +++ b/NdkQoS/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import testNapi from 'libentry.so'; + +@CustomDialog +export struct CustomAlterDialog { + customAlterDialogCtl: CustomDialogController; + title: string = ''; + content: string = ''; + + build() { + Column() { + Text(this.title) + .fontColor($r('sys.color.font_primary')) + .height(56) + .fontSize(20) + .textAlign(TextAlign.Center) + .fontWeight(FontWeight.Bold) + + Column() { + Text(this.content) + .textAlign(TextAlign.Start) + .opacity(0.6) + .fontSize(14) + .fontColor(Color.Black) + .width('100%') + } + .layoutWeight(1) + .padding({ + left: 8, + right: 8 + }) + + Row({ space: 12 }) { + Button('OK') + .layoutWeight(1) + .height(40) + .onClick(() => { + this.customAlterDialogCtl.close(); + }) + } + .height(56) + .alignItems(VerticalAlign.Top) + } + .constraintSize({ + maxHeight: '80%' + }) + .height(140) + .width('calc(100% - 32vp)') + .padding({ + left: 16, + right: 16 + }) + .borderColor(Color.Red) + .borderRadius(32) + } +} + +@Entry +@Component +struct Index { + title: string = 'QoS Sample'; + @State message: string = ''; + customFaceDialogCtl: CustomDialogController = new CustomDialogController({ + builder: CustomAlterDialog({ title: this.title, content: this.message }), + alignment: DialogAlignment.Center, + autoCancel: true, + isModal: true, + customStyle: false + }); + + build() { + Row() { + Column({ space: 12 }) { + Blank() + Button('High level QoS test') + .height(40) + .width('100%') + .onClick(() => { + let ret: string = testNapi.useHighQos().toString(); + this.message = `High-level QoS time: ${ret} ms`; + this.customFaceDialogCtl.open(); + }) + + Button('Low level QoS test') + .height(40) + .width('100%') + .onClick(() => { + let ret: string = testNapi.useHighQos().toString(); + this.message = `Low-level QoS time: ${ret} ms`; + this.customFaceDialogCtl.open(); + }) + } + .height('100%') + .width('100%') + .padding(16) + .justifyContent(FlexAlign.Center) + } + .height('100%') + } +} \ No newline at end of file diff --git a/NdkQoS/entry/src/main/module.json5 b/NdkQoS/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..d8838feb856bb135d089c4aa3fe1973673f48259 --- /dev/null +++ b/NdkQoS/entry/src/main/module.json5 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:startIcon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ] + } +} diff --git a/NdkQoS/entry/src/main/resources/base/element/color.json b/NdkQoS/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/NdkQoS/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/NdkQoS/entry/src/main/resources/base/element/string.json b/NdkQoS/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f94595515a99e0c828807e243494f57f09251930 --- /dev/null +++ b/NdkQoS/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "label" + } + ] +} \ No newline at end of file diff --git a/NdkQoS/entry/src/main/resources/base/media/icon.png b/NdkQoS/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..cd45accb1dfd2fd0da16c732c72faa6e46b26521 Binary files /dev/null and b/NdkQoS/entry/src/main/resources/base/media/icon.png differ diff --git a/NdkQoS/entry/src/main/resources/base/media/startIcon.png b/NdkQoS/entry/src/main/resources/base/media/startIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..366f76459ffd4494ec40d0ddd5c59385b9c5da11 Binary files /dev/null and b/NdkQoS/entry/src/main/resources/base/media/startIcon.png differ diff --git a/NdkQoS/entry/src/main/resources/base/profile/main_pages.json b/NdkQoS/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/NdkQoS/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/NdkQoS/entry/src/main/resources/en_US/element/string.json b/NdkQoS/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f94595515a99e0c828807e243494f57f09251930 --- /dev/null +++ b/NdkQoS/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "label" + } + ] +} \ No newline at end of file diff --git a/NdkQoS/entry/src/main/resources/zh_CN/element/string.json b/NdkQoS/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..597ecf95e61d7e30367c22fe2f8638008361b044 --- /dev/null +++ b/NdkQoS/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "label" + } + ] +} \ No newline at end of file diff --git a/NdkQoS/hvigor/hvigor-config.json5 b/NdkQoS/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..2662c04148f9901f7fdcbc0436754f5e2a1766fd --- /dev/null +++ b/NdkQoS/hvigor/hvigor-config.json5 @@ -0,0 +1,22 @@ +{ + "modelVersion": "5.0.0", + "dependencies": { + }, + "execution": { + // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ + // "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */ + // "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */ + // "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */ + // "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */ + }, + "logging": { + // "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */ + }, + "debugging": { + // "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */ + }, + "nodeOptions": { + // "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/ + // "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/ + } +} \ No newline at end of file diff --git a/NdkQoS/hvigorfile.ts b/NdkQoS/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3cb9f1a87a81687554a76283af8df27d8bda775 --- /dev/null +++ b/NdkQoS/hvigorfile.ts @@ -0,0 +1,6 @@ +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} diff --git a/NdkQoS/oh-package.json5 b/NdkQoS/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..35a411e22c3bef2de10d8764b481781a44e8ae72 --- /dev/null +++ b/NdkQoS/oh-package.json5 @@ -0,0 +1,15 @@ +{ + "modelVersion": "5.0.0", + "name": "qossample", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + }, + "devDependencies": { + "@ohos/hypium": "1.0.15", + "@ohos/hamock": "1.0.0-rc" + } +} \ No newline at end of file diff --git a/NdkQoS/screenshots/device/qos-protect-critical-threads.gif b/NdkQoS/screenshots/device/qos-protect-critical-threads.gif new file mode 100644 index 0000000000000000000000000000000000000000..0c4184d0d144a1b39af2fdf5d1c5641057a49ec3 Binary files /dev/null and b/NdkQoS/screenshots/device/qos-protect-critical-threads.gif differ diff --git a/README.md b/README.md index 56e7772e21c162852a5a914ea7e1dc9ce50ad43d..3b06722b4bb793c352ce8c4e4a31518d7c4ddf89 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,9 @@ * [AppDataSecurity: 应用数据安全](AppDataSecurity) * [AppPrivacyProtection:应用隐私保护](AppPrivacyProtection) * [AvoidTimeComsume:主线程耗时操作优化指导](AvoidTimeComsume) +* [CustomDialogPractice:应用自定义弹窗开发实践](CustomDialogPractice) * [FuzzySceneOptimization:图像模糊动效优化](FuzzySceneOptimization) +* [NdkQoS:基于QoS设置线程优先级](NdkQoS) * [NetworkManagement:网络管理与状态监听](NetworkManagement) * [PreHttpRequestUseFiles:Image白块解决指导](PreHttpRequestUseFiles)