-
-
\ No newline at end of file
diff --git a/AdaptiveCapabilities/LICENSE b/AdaptiveCapabilities/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..18795a48d6b12fcdc1aa7bac9a9cb99f83815267
--- /dev/null
+++ b/AdaptiveCapabilities/LICENSE
@@ -0,0 +1,78 @@
+ Copyright (c) 2025 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/AdaptiveCapabilities/README.md b/AdaptiveCapabilities/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..875f5b6ed917faf9e7fbd2823b77466e9366f1d9
--- /dev/null
+++ b/AdaptiveCapabilities/README.md
@@ -0,0 +1,160 @@
+# 多设备自适应能力
+
+### 介绍
+
+本示例是[《一次开发,多端部署》中《自适应布局》与《多设备资源文件》](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-multi-device-adaptive-layout)的配套示例代码,展示了自适应布局、响应式布局、典型布局场景以及资源文件使用的能力。
+
+| 名称 | 简介 |
+| ------------ | ------------------------------------------------------------ |
+| 自适应布局 | 当外部容器大小发生变化时,元素可以**根据相对关系自动变化**以适应外部容器变化的布局能力。 |
+| 响应式布局 | 当外部容器大小发生变化时,元素可以**根据断点或特定的媒体特征(如屏幕方向、窗口宽高等)自动变化**以适应外部容器变化的布局能力。 |
+| 典型布局场景 | 应用开发中的典型场景,包括运行横幅、网格、侧边栏等。 |
+| 资源文件使用 | 根据当前的设备特征(如设备类型、屏幕密度等)或应用场景(如语言、国家、地区等),从resources目录下不同的资源限定词目录中获取相应的资源值。 |
+
+> 说明:
+>
+> * 自适应布局能力仅可以保证在外部容器大小在一定范围内变化时,容器内的元素布局合理。如果外部尺寸发生较大变化,需要借助响应式布局能力进一步适配(详见《一次开发,多端部署》中关于断点的介绍)。
+> * 为简化代码、突出重点及方便读者理解,本示例中的自适应布局部分未做多设备适配。此部分建议在DevEco自带的MatePadPro预览器中运行及查看效果,以获得最佳的体验。
+> * 响应式布局、典型布局场景、资源文件使用均做了多设备适配,推荐参考如下方式查看代码的运行效果:
+> * 将应用安装到不同类型的设备,查看运行效果。
+> * 通过创建不同屏幕尺寸多个预览器,或者通过拖拽的方式改变预览器的屏幕尺寸,查看不同情况下的运行效果。
+
+### 效果预览:
+
+| 首页 | 自适应布局 | 响应式布局 | 典型场景 |
+|-----------------------------------|-----------------------------------|-----------------------------------|-----------------------------------|
+|  |  |  |  |
+
+使用说明
+
+1. 启动应用,首页展示了自适应布局、响应式布局、典型布局场景和资源文件使用四个按钮。
+
+2. 点击"自适应布局"进入新页面,分别展示拉伸能力、缩放能力、隐藏能力、折行能力、均分能力、占比能力和延伸能力共7种自适应布局能力。
+
+3. 点击"响应式布局"进入新页面,分别展示断点、媒体查询和栅格布局3种响应式布局能力。
+
+4. 点击"典型布局场景"进入新页面,展示了如何通过自适应布局能力和响应式布局能力,实现应用开发中的典型场景。
+
+5. 点击"资源文件使用"进入新页面,展示字符串和图片资源的使用。
+
+### 工程目录
+```
+entry/src/main/ets
+|---common
+| |---BreakpointSystem.ets
+| |---ColorEntity.ets
+| |---DirectoryList.ets
+| |---GetValueOnBreakpoint.ets
+|---MainAbility
+| |---MainAbility.ts
+|---model
+| |---Logger.ts // 日志工具
+|---pages
+| |---Index.ets // 首页
+| |---atomicLayoutCapability
+| | |---equipartitionCapability
+| | | |---EquipartitionCapability.ets // 均分能力
+| | |---extensionCapability
+| | | |---ExtensionCapability1.ets // 延伸能力1
+| | | |---ExtensionCapability2.ets // 延伸能力2
+| | |---flexibleCapability
+| | | |---FlexibleCapability1.ets // 拉伸能力2
+| | | |---FlexibleCapability2.ets // 拉伸能力2
+| | |---hiddenCapability
+| | | |---HiddenCapability.ets // 隐藏能力
+| | |---proportionCapability
+| | | |---ProportionCapability.ets // 占比能力
+| | |---scaleCapability
+| | | |---ScaleCapability.ets // 缩放能力
+| | |---wrapCapability
+| | | |---WrapCapability.ets // 拆行能力
+| | |---AtomicLayoutCapabilityIndex.ets // 自适应布局
+| |---gridRow
+| | |---gridRow
+| | | |---GridRowSample1.ets // 栅格断点1
+| | | |---GridRowSample2.ets // 栅格断点2
+| | | |---GridRowSample3.ets // 栅格columns和gutter
+| | | |---GridRowSample4.ets // 栅格margin
+| | | |---GridRowSample5.ets // 栅格span
+| | | |---GridRowSample6.ets // 栅格offset
+| | | |---GridRowSample7.ets // 栅格order
+| | | |---GridRowSample8.ets // 栅格span/offset/order继承性
+| | | |---GridRowSample9.ets // 栅格嵌套
+| | | |---GridRowSample10.ets // 栅格对齐
+| | |---GridRowLayoutIndex.ets // 栅格布局
+| |---interactionNormCapability
+| | |---InteractionNormCapability.ets // 交互归一能力
+| |---resourceQualifier
+| | |---ResourceQualifier.ets // 资源文件使用
+| |---responsiveLayout
+| | |---ResponsiveLayoutIndex.ets
+| | |---breakpoint
+| | | |---Breakpoint.ets // 断点类
+| | | |---BreakpointSample.ets // 断点
+| | |---mediaQuery
+| | | |---MediaQuerySample.ets // 媒体查询
+| |---typicalScene
+| | |---banner
+| | | |---BannerSample.ets // 广告栏
+| | |---bigImage
+| | | |---BigImageSample.ets // 大图浏览
+| | |---diversion
+| | | |---DiversionSample.ets // 挪移布局
+| | |---header
+| | | |---HeaderSample.ets // 顶部布局
+| | |---indentation
+| | | |---IndentationSample.ets // 缩进布局
+| | |---multiLaneList
+| | | |---MultiLaneListSample.ets // 多列列表
+| | |---multiScene
+| | | |---data
+| | | | |---apliications
+| | | | | |---Apliications.ets
+| | | | |---home
+| | | | | |---Home.ets
+| | | |---pages
+| | | | |---apliications
+| | | | | |---Apliications.ets
+| | | | |---home
+| | | | | |---Home.ets
+| | | | |---player
+| | | | | |---Player.ets
+| | | | |---MultiScene.ets // 一多典型场景
+| | |---operationEntries
+| | | |---OperationEntriesSample.ets // 操作入口
+| | |---repeat
+| | | |---RepeatSample.ets // 重复布局
+| | |---responsiveGrid
+| | | |---ResponsiveGridSample.ets // 网格视图
+| | |---sidebar
+| | | |---SidebarSample.ets // 侧边栏
+| | |---tabs
+| | | |---TabsSample.ets // 页签布局
+| | |---TypicalSceneIndex.ets // 典型布局场景
+```
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机、平板。
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AdaptiveCapabilities
+git checkout
+```
\ No newline at end of file
diff --git a/AdaptiveCapabilities/README_zh.md b/AdaptiveCapabilities/README_zh.md
deleted file mode 100644
index b20c84abcf8743c0b612679e6dff9e2671688258..0000000000000000000000000000000000000000
--- a/AdaptiveCapabilities/README_zh.md
+++ /dev/null
@@ -1,181 +0,0 @@
-# 多设备自适应能力
-
-### 介绍
-
-本示例是[《一次开发,多端部署》](https://gitee.com/openharmony/docs/tree/master/zh-cn/application-dev/key-features/multi-device-app-dev)的配套示例代码,展示了[页面开发的一多能力](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/key-features/multi-device-app-dev/layout-intro.md),包括自适应布局、响应式布局、典型布局场景以及资源文件使用。
-
-| 名称 | 简介 |
-| ------------ | ------------------------------------------------------------ |
-| 自适应布局 | 当外部容器大小发生变化时,元素可以**根据相对关系自动变化**以适应外部容器变化的布局能力。 |
-| 响应式布局 | 当外部容器大小发生变化时,元素可以**根据断点或特定的媒体特征(如屏幕方向、窗口宽高等)自动变化**以适应外部容器变化的布局能力。 |
-| 典型布局场景 | 应用开发中的典型场景,包括运行横幅、网格、侧边栏等。 |
-| 资源文件使用 | 根据当前的设备特征(如设备类型、屏幕密度等)或应用场景(如语言、国家、地区等),从resources目录下不同的资源限定词目录中获取相应的资源值。 |
-
-> 说明:
->
-> * 自适应布局能力仅可以保证在外部容器大小在一定范围内变化时,容器内的元素布局合理。如果外部尺寸发生较大变化,需要借助响应式布局能力进一步适配(详见《一次开发,多端部署》中关于断点的介绍)。
-> * 为简化代码、突出重点及方便读者理解,本示例中的自适应布局部分未做多设备适配。此部分建议在DevEco自带的MatePadPro预览器中运行及查看效果,以获得最佳的体验。
-> * 响应式布局、典型布局场景、资源文件使用均做了多设备适配,推荐参考如下方式查看代码的运行效果:
-> * 将应用安装到不同类型的设备,查看运行效果。
-> * 将应用安装到开发板等设备中,开启设备的自由窗口能力,查看不同窗口尺寸下的运行效果。
-> * 通过创建不同屏幕尺寸多个预览器,或者通过拖拽的方式改变预览器的屏幕尺寸,查看不同情况下的运行效果。
-
-### 效果预览:
-
-| 首页 | 自适应布局 | 响应式布局 | 典型场景 |
-|------------------------------------|------------------------------------|------------------------------------|------------------------------------|
-|  |  |  |  |
-
-使用说明
-
-1. 启动应用,首页展示了自适应布局、响应式布局、典型布局场景和资源文件使用四个按钮。
-
-2. 点击"自适应布局"进入新页面,分别展示拉伸能力、缩放能力、隐藏能力、折行能力、均分能力、占比能力和延伸能力共7种自适应布局能力。
-
-3. 点击"响应式布局"进入新页面,分别展示断点、媒体查询和栅格布局3种响应式布局能力。
-
-4. 点击"典型布局场景"进入新页面,展示了如何通过自适应布局能力和响应式布局能力,实现应用开发中的典型场景。
-
-5. 点击"资源文件使用"进入新页面,展示字符串和图片资源的使用。
-
-### 工程目录
-```
-entry/src/main/ets/
-|---Application
-| |---AbilityStage.ts
-|---common
-| |---BreakpointSystem.ets
-| |---DirectoryList.ets
-| |---GetValueOnBreakpoint.ets
-|---MainAbility
-| |---MainAbility.ts
-|---model
-| |---Logger.ts // 日志工具
-|---pages
-| |---Index.ets // 首页
-| |---atomicLayoutCapability
-| | |---equipartitionCapability
-| | | |---EquipartitionCapability.ets // 均分能力
-| | |---extensionCapability
-| | | |---ExtensionCapability1.ets // 延伸能力1
-| | | |---ExtensionCapability2.ets // 延伸能力2
-| | |---flexibleCapability
-| | | |---FlexibleCapability1.ets // 拉伸能力2
-| | | |---FlexibleCapability2.ets // 拉伸能力2
-| | |---hiddenCapability
-| | | |---HiddenCapability.ets // 隐藏能力
-| | |---proportionCapability
-| | | |---ProportionCapability.ets // 占比能力
-| | |---scaleCapability
-| | | |---ScaleCapability.ets // 缩放能力
-| | |---wrapCapability
-| | | |---WrapCapability.ets // 拆行能力
-| | |---AtomicLayoutCapabilityIndex.ets // 自适应布局
-| |---gridRow
-| | |---gridRow
-| | | |---GridRowSample1.ets // 栅格断点1
-| | | |---GridRowSample2.ets // 栅格断点2
-| | | |---GridRowSample3.ets // 栅格columns和gutter
-| | | |---GridRowSample4.ets // 栅格margin
-| | | |---GridRowSample5.ets // 栅格span
-| | | |---GridRowSample6.ets // 栅格offset
-| | | |---GridRowSample7.ets // 栅格order
-| | | |---GridRowSample8.ets // 栅格span/offset/order继承性
-| | | |---GridRowSample9.ets // 栅格嵌套
-| | | |---GridRowSample10.ets // 栅格对齐
-| | |---GridRowLayoutIndex.ets // 栅格布局
-| |---interactionNormCapability
-| | |---InteractionNormCapability.ets // 交互归一能力
-| |---resourceQualifier
-| | |---ResourceQualifier.ets // 资源文件使用
-| |---responsiveLayout
-| | |---ResponsiveLayoutIndex.ets
-| | |---breakpoint
-| | | |---BreakpointSample.ets // 断点
-| | |---mediaQuery
-| | | |---MediaQuerySample.ets // 媒体查询
-| |---typicalScene
-| | |---banner
-| | | |---BannerSample.ets // 广告栏
-| | |---bigImage
-| | | |---BigImageSample.ets // 大图浏览
-| | |---diversion
-| | | |---DiversionSample.ets // 挪移布局
-| | |---header
-| | | |---HeaderSample.ets // 顶部布局
-| | |---indentation
-| | | |---IndentationSample.ets // 缩进布局
-| | |---multiLaneList
-| | | |---MultiLaneListSample.ets // 多列列表
-| | |---multiScene
-| | | |---data
-| | | | |---apliications
-| | | | | |---Apliications.ets
-| | | | |---home
-| | | | | |---Home.ets
-| | | |---pages
-| | | | |---apliications
-| | | | | |---Apliications.ets
-| | | | |---home
-| | | | | |---Home.ets
-| | | | |---player
-| | | | | |---Player.ets
-| | | | |---MultiScene.ets // 一多典型场景
-| | |---operationEntries
-| | | |---OperationEntriesSample.ets // 操作入口
-| | |---repeat
-| | | |---RepeatSample.ets // 重复布局
-| | |---responsiveGrid
-| | | |---ResponsiveGridSample.ets // 网格视图
-| | |---sidebar
-| | | |---SidebarSample.ets // 侧边栏
-| | |---tabs
-| | | |---TabsSample.ets // 页签布局
-| | |---TypicalSceneIndex.ets // 典型布局场景
-```
-### 具体实现
-
-* 该示例使用了路由跳转接口,实现了各个不同布局之间的页面跳转,通过MediaQueryListener方法查询媒体,matchMediaSync方法设置媒体查询的查询条件。
-* 源码链接:[BreakpointSystem.ets](entry/src/main/ets/common/BreakpointSystem.ets),[DirectoryList.ets](entry/src/main/ets/common/DirectoryList.ets)
-* 接口参考:[@ohos.router](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-arkui/js-apis-system-router.md),[@ohos.mediaquery](https://docs.openharmony.cn/pages/v4.1/zh-cn/application-dev/reference/apis-arkui/js-apis-mediaquery.md)
-
-### 相关权限
-
-不涉及。
-
-### 依赖
-
-不涉及。
-
-### 约束与限制
-
-1.本示例仅支持标准系统上运行,支持设备:RK3568。
-
-2.本示例为Stage模型,支持API12版本SDK,SDK版本号(API Version 12 Release),镜像版本号(5.0.0 Release)
-
-3.本示例需要使用DevEco Studio NEXT Release(Build Version: 5.0.3.900, built on October 8, 2024)及以上版本才可编译运行。
-
-4.本示例在开发板上运行时,可以修改开发板系统配置文件以使能应用窗口能力。
-
-````
-# 将开发板文件系统的权限配置为可读写
-hdc shell mount -o rw,remount /
-# 取出原始配置文件
-hdc file recv system/etc/window/resources/window_manager_config.xml C:\
-# 将文件中改为
-# 用修改后的文件替换系统中的原始文件
-hdc file send C:\window_manager_config.xml system/etc/window/resources/window_manager_config.xml
-# 重启后生效
-hdc shell reboot
-````
-
-### 下载
-
-如需单独下载本工程,执行如下命令:
-```
-git init
-git config core.sparsecheckout true
-echo code/SuperFeature/MultiDeviceAppDev/AdaptiveCapabilities/ > .git/info/sparse-checkout
-git remote add origin https://gitee.com/openharmony/applications_app_samples.git
-git pull origin master
-```
\ No newline at end of file
diff --git a/AdaptiveCapabilities/build-profile.json5 b/AdaptiveCapabilities/build-profile.json5
index a70b8401e6ef8f7476649db4057bcdefcb3bd8a4..7421eac5cace21b28ab5e96c79ba0520f672cdd1 100644
--- a/AdaptiveCapabilities/build-profile.json5
+++ b/AdaptiveCapabilities/build-profile.json5
@@ -20,7 +20,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.3(15)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/AdaptiveCapabilities/entry/src/main/ets/MainAbility/MainAbility.ets b/AdaptiveCapabilities/entry/src/main/ets/MainAbility/MainAbility.ets
index 9e22face6d821b460c80c8b4aa349ad5e7aedb43..3c0caaf6b201a77dae78fe25f7210199503a6b8d 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/MainAbility/MainAbility.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/MainAbility/MainAbility.ets
@@ -13,12 +13,19 @@
* limitations under the License.
*/
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
-import { hilog } from '@kit.PerformanceAnalysisKit';
import Logger from '../model/Logger';
+const DOMAIN = 0x0000;
+const TAG = 'EntryAbility';
+const FORMAT = '%{public}s';
+
export default class MainAbility extends UIAbility {
+ windowClass: window.Window | undefined = undefined;
+
onCreate() {
Logger.info('[Sample_AdaptiveCapabilities]', 'MainAbility onCreate');
}
@@ -30,15 +37,51 @@ export default class MainAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
Logger.info('[Sample_AdaptiveCapabilities]', 'onWindowStageCreate');
+
+
+ windowStage.getMainWindow((err: BusinessError, data) => {
+ const errCode: number = err.code;
+ if (errCode) {
+ hilog.error(DOMAIN, TAG, FORMAT,
+ `Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
+ return;
+ }
+ this.windowClass = data;
+ let isLayoutFullScreen = true;
+ try {
+ let promise = this.windowClass.setWindowLayoutFullScreen(isLayoutFullScreen).catch((err: BusinessError) => {
+ hilog.error(DOMAIN, TAG, FORMAT,
+ `Failed to set the window layout to full-screen mode. Cause code: ${err.code},message: ${err.message}`);
+ });
+ promise.then(() => {
+ hilog.info(DOMAIN, TAG, FORMAT, 'Succeeded in setting the window layout to full-screen mode.');
+ }).catch((err: BusinessError) => {
+ hilog.error(DOMAIN, TAG, FORMAT,
+ `Failed to set the window layout to full-screen mode. Cause code: ${err.code},message: ${err.message}`);
+ });
+ } catch (err) {
+ hilog.error(DOMAIN, TAG, FORMAT,
+ `Failed to set the window layout to full-screen mode. Cause code: ${err.code},message: ${err.message}`);
+ }
+ this.windowClass.setSpecificSystemBarEnabled('navigationIndicator', false).catch((err: BusinessError) => {
+ hilog.error(DOMAIN, TAG, FORMAT,
+ `Failed to set the system bar to be invisible. Cause code: ${err.code},message: ${err.message}`);
+ });
+ });
+
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
- hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
+ hilog.error(DOMAIN, TAG, FORMAT, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
- hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
- let windowObj = windowStage.getMainWindowSync();
- AppStorage.setOrCreate('windowObj', windowObj);
- AppStorage.setOrCreate('uiContext', windowObj.getUIContext());
+ hilog.info(DOMAIN, TAG, FORMAT, 'Succeeded in loading the content.');
+ try {
+ let windowObj = windowStage.getMainWindowSync();
+ AppStorage.setOrCreate('windowObj', windowObj);
+ AppStorage.setOrCreate('uiContext', windowObj.getUIContext());
+ } catch (err) {
+ hilog.error(DOMAIN, TAG, FORMAT, `Failed. Cause code: ${err.code}, message: ${err.message}`);
+ }
});
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/common/DirectoryList.ets b/AdaptiveCapabilities/entry/src/main/ets/common/DirectoryList.ets
index b8597f236f652fb34d73fe3a6a48b469de33f482..5a3a9c3f8dd7c5c088b2bb90e8a0f7c72d739166 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/common/DirectoryList.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/common/DirectoryList.ets
@@ -13,6 +13,13 @@
* limitations under the License.
*/
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+
+const DOMAIN = 0x0000;
+const TAG = 'DirectoryList';
+const FORMAT = '%{public}s';
+
class DirectoryItem {
title: Resource | string = '';
uri: string = '';
@@ -39,17 +46,23 @@ struct DirectoryList {
.width('90%')
.height(55)
.margin(12)
- .backgroundColor('#007DFF')
+ .backgroundColor($r('sys.color.brand'))
.onClick(() => {
this.getUIContext().getRouter().pushUrl({
url: item.uri
+ }).catch((err: BusinessError) => {
+ hilog.error(DOMAIN, TAG, FORMAT, `pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
});
}, (item: DirectoryItem) => JSON.stringify(item));
}
}
.width('100%')
- .padding({ left: 10, right: 10, bottom: 100 });
+ .padding({
+ left: 10,
+ right: 10,
+ bottom: 100
+ })
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/common/GetValueOnBreakpoint.ets b/AdaptiveCapabilities/entry/src/main/ets/common/GetValueOnBreakpoint.ets
index a1a8b8cb9932a4744dbb01d8e22127b50d6cefb9..8b7422683ad6420897dad1dfba0015d18da54982 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/common/GetValueOnBreakpoint.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/common/GetValueOnBreakpoint.ets
@@ -14,6 +14,11 @@
*/
import { window } from '@kit.ArkUI';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+
+const DOMAIN = 0x0000;
+const TAG = 'GetValueOnBreakpoint';
+const FORMAT = '%{public}s';
export class Breakpoints {
xs: number = 0;
@@ -22,7 +27,7 @@ export class Breakpoints {
lg: number = 0;
}
-// 全局断点接口
+// Global breakpoint interface
export default function getValueOnBreakpoint(breakpointsLabels: string[], breakpoints: Breakpoints): string {
if (breakpointsLabels.length < 4) {
return '';
@@ -31,17 +36,22 @@ export default function getValueOnBreakpoint(breakpointsLabels: string[], breakp
if (windowObj == undefined) {
return '';
}
- let uiContext = AppStorage.get('uiContext') as UIContext;
- let windowWidthVp = uiContext.px2vp(windowObj.getWindowProperties().windowRect.width);
let newBreakpoint: string = '';
- if (windowWidthVp < breakpoints.sm) {
- newBreakpoint = breakpointsLabels[0];
- } else if (windowWidthVp < breakpoints.md) {
- newBreakpoint = breakpointsLabels[1];
- } else if (windowWidthVp < breakpoints.lg) {
- newBreakpoint = breakpointsLabels[2];
- } else {
- newBreakpoint = breakpointsLabels[3];
+ try {
+ let uiContext = AppStorage.get('uiContext') as UIContext;
+ let windowWidthVp = uiContext.px2vp(windowObj.getWindowProperties().windowRect.width);
+ if (windowWidthVp < breakpoints.sm) {
+ newBreakpoint = breakpointsLabels[0];
+ } else if (windowWidthVp < breakpoints.md) {
+ newBreakpoint = breakpointsLabels[1];
+ } else if (windowWidthVp < breakpoints.lg) {
+ newBreakpoint = breakpointsLabels[2];
+ } else {
+ newBreakpoint = breakpointsLabels[3];
+ }
+ } catch (err) {
+ hilog.error(DOMAIN, TAG, FORMAT,
+ `Failed to obtain the window properties. Cause code: ${err.code}, message: ${err.message}`);
}
return newBreakpoint;
}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/model/Logger.ts b/AdaptiveCapabilities/entry/src/main/ets/model/Logger.ts
index c9fb06f0ee72131e8c26928e2d357bc7b31da7e5..679e6ace6921f025a5e166a4c24d91b0841dab0c 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/model/Logger.ts
+++ b/AdaptiveCapabilities/entry/src/main/ets/model/Logger.ts
@@ -13,12 +13,12 @@
* limitations under the License.
*/
-import hilog from '@ohos.hilog'
+import { hilog } from '@kit.PerformanceAnalysisKit';
class Logger {
- private domain: number
- private prefix: string
- private format: string = "%{public}s, %{public}s"
+ private domain: number;
+ private prefix: string;
+ private format: string = '%{public}s, %{public}s';
constructor(prefix: string) {
this.prefix = prefix
@@ -26,19 +26,19 @@ class Logger {
}
debug(...args: any[]) {
- hilog.debug(this.domain, this.prefix, this.format, args)
+ hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: any[]) {
- hilog.info(this.domain, this.prefix, this.format, args)
+ hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: any[]) {
- hilog.warn(this.domain, this.prefix, this.format, args)
+ hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: any[]) {
- hilog.error(this.domain, this.prefix, this.format, args)
+ hilog.error(this.domain, this.prefix, this.format, args);
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/Index.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/Index.ets
index 88e18fc7b660835267562054b4477c8c9c840d1b..e0d1661de004873c4a92933e6396c219a248cc71 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/Index.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/Index.ets
@@ -13,19 +13,35 @@
* limitations under the License.
*/
-import { DirectoryItem, DirectoryList } from '../common/DirectoryList'
+import { DirectoryItem, DirectoryList } from '../common/DirectoryList';
@Entry
@Component
struct Index {
private directory: DirectoryItem[] = [
- { title: $r('app.string.atomic_capability'), uri: 'pages/atomicLayoutCapability/AtomicLayoutCapabilityIndex', id:'AtomicLayoutCapabilityIndex' },
- { title: $r('app.string.responsive_layout'), uri: 'pages/responsiveLayout/ResponsiveLayoutIndex', id:'ResponsiveLayoutIndex' },
- { title: $r('app.string.typical_scenario'), uri: 'pages/typicalScene/TypicalSceneIndex', id:'TypicalSceneIndex' },
- { title: $r('app.string.resource_qualifier'), uri: 'pages/resourceQualifier/ResourceQualifier', id:'ResourceQualifier' },
- { title: $r('app.string.interaction_norm_capability'), uri: 'pages/interactionNormCapability/InteractionNormCapability', id:'InteractionNormCapability' }
- ]
- @State inSetValue: number = 40
+ {
+ title: $r('app.string.atomic_capability'),
+ uri: 'pages/atomicLayoutCapability/AtomicLayoutCapabilityIndex',
+ id: 'AtomicLayoutCapabilityIndex'
+ },
+ {
+ title: $r('app.string.responsive_layout'),
+ uri: 'pages/responsiveLayout/ResponsiveLayoutIndex',
+ id: 'ResponsiveLayoutIndex'
+ },
+ { title: $r('app.string.typical_scenario'), uri: 'pages/typicalScene/TypicalSceneIndex', id: 'TypicalSceneIndex' },
+ {
+ title: $r('app.string.resource_qualifier'),
+ uri: 'pages/resourceQualifier/ResourceQualifier',
+ id: 'ResourceQualifier'
+ },
+ {
+ title: $r('app.string.interaction_norm_capability'),
+ uri: 'pages/interactionNormCapability/InteractionNormCapability',
+ id: 'InteractionNormCapability'
+ }
+ ];
+ @State inSetValue: number = 40;
build() {
Column() {
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/equipartitionCapability/EquipartitionCapability.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/equipartitionCapability/EquipartitionCapability.ets
index 0653e5e8dd2092366811f1b1f53ca146b4f1e991..54a3b6a6010ba0ced5c964f7b89652e9ec38f5c9 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/equipartitionCapability/EquipartitionCapability.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/equipartitionCapability/EquipartitionCapability.ets
@@ -58,29 +58,29 @@ struct EquipartitionCapability {
Column() {
// Distribute remaining space evenly along the main axis of the parent container.
Flex({ justifyContent: FlexAlign.SpaceEvenly }) {
- ForEach(this.list, (item: number) => {
+ ForEach(this.list, () => {
this.Item();
- }, (item: number, index: number) => JSON.stringify(item) + index)
+ }, (item: number, index: number) => item.toString() + index)
}
// Distribute remaining space evenly along the main axis of the parent container.
Flex({ justifyContent: FlexAlign.SpaceEvenly }) {
- ForEach(this.list, (item: number) => {
+ ForEach(this.list, () => {
this.Item();
- }, (item: number, index: number) => JSON.stringify(item) + index)
+ }, (item: number, index: number) => item.toString() + index)
}
}
.width(this.rate * 100 + '%')
.height(222)
.padding({ top: 16 })
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.font_on_primary'))
.borderRadius(16)
this.slider()
}
.width('100%')
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability1.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability1.ets
index b8a4642810cbdd8f3367e58836f05c44847b6869..a4e446597da12c9c77b84658a30a26e6e1844078 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability1.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability1.ets
@@ -37,7 +37,7 @@ struct ExtensionCapability1 {
// Implement extension capability through Scroll and Row(or Column) components.
Scroll() {
Row({ space: 10 }) {
- ForEach(this.appList, (item: number, index: number) => {
+ ForEach(this.appList, () => {
Column() {
Image($r('app.media.icon'))
.width(48)
@@ -54,7 +54,7 @@ struct ExtensionCapability1 {
}
.width(80)
.height(102)
- }, (item: number, index: number) => JSON.stringify(item) + index)
+ }, (item: number, index: number) => item.toString() + index)
}
.padding({ top: 16, left: 10 })
.height(118)
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability2.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability2.ets
index 3449c076596229e60badb39f509ffacdb37d21ab..a18b6ce0dd34d06e0ca3b567a7d51ab254440c26 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability2.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/extensionCapability/ExtensionCapability2.ets
@@ -37,7 +37,7 @@ struct ExtensionCapability2 {
Row({ space: 10 }) {
// Implement extension capability through List component.
List({ space: 10 }) {
- ForEach(this.appList, (item: number, index: number) => {
+ ForEach(this.appList, () => {
ListItem() {
Column() {
Image($r('app.media.icon'))
@@ -58,7 +58,7 @@ struct ExtensionCapability2 {
}
.width(80)
.height(102)
- }, (item: number, index: number) => JSON.stringify(item) + index)
+ }, (item: number, index: number) => item.toString() + index)
}
.padding({ top: 16, left: 10 })
.listDirection(Axis.Horizontal)
@@ -77,5 +77,4 @@ struct ExtensionCapability2 {
.alignItems(VerticalAlign.Center)
}
}
-
// [End ExtensionCapability2]
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability1.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability1.ets
index 328654b8c3a6c116a0bdc67cba2ebc79efd09e8e..02a38165bb3c7d3e36ea8ad1062628b6377bf670 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability1.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability1.ets
@@ -38,7 +38,7 @@ struct FlexibleCapability1 {
Row()
.width(150)
.height(400)
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.flexGrow(0)
.flexShrink(1)
Image($r('app.media.illustrator'))
@@ -51,7 +51,7 @@ struct FlexibleCapability1 {
Row()
.width(150)
.height(400)
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.flexGrow(0)
.flexShrink(1)
}
@@ -61,7 +61,7 @@ struct FlexibleCapability1 {
}
.width('100%')
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability2.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability2.ets
index af45d4445d8cbf65f2e99a440570dd16cf4a4bc5..a81c541c3ca6592eba0cb17b5d89d0bfcc8bc3f5 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability2.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/flexibleCapability/FlexibleCapability2.ets
@@ -49,14 +49,14 @@ struct FlexibleCapability2 {
.height(55)
.borderRadius(12)
.padding({ left: 13, right: 13 })
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.width(this.rate * 100 + '%')
this.slider()
}
.width('100%')
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/hiddenCapability/HiddenCapability.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/hiddenCapability/HiddenCapability.ets
index 21e12b397fc3a1014948ae6ce34a94d6c4df7273..c1c5c7591e3264799fc5c6211a8c011cdd1cdb77 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/hiddenCapability/HiddenCapability.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/hiddenCapability/HiddenCapability.ets
@@ -87,14 +87,14 @@ struct HiddenCapability {
.width(this.rate * 100 + '%')
.height(96)
.borderRadius(16)
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.justifyContent(FlexAlign.Center)
this.slider()
}
.width('100%')
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/proportionCapability/ProportionCapability.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/proportionCapability/ProportionCapability.ets
index 40cbb0e1718bbd8005bc65d0e4fbcaf8255f3f81..ae9065fbeb8e945649f0e824cc319d0cad863040 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/proportionCapability/ProportionCapability.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/proportionCapability/ProportionCapability.ets
@@ -46,7 +46,7 @@ struct ProportionCapability {
.justifyContent(FlexAlign.Center)
Column() {
- Image($r("app.media.pause"))
+ Image($r('app.media.pause'))
.width(48)
.height(48)
}
@@ -67,13 +67,13 @@ struct ProportionCapability {
.width(this.rate * 100 + '%')
.height(96)
.borderRadius(16)
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
this.slider()
}
.width('100%')
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/scaleCapability/ScaleCapability.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/scaleCapability/ScaleCapability.ets
index e42983cd1c13996bcc0065697cc48cf6fd8b7754..f497d1148621f7c6783e00eb6f36b5afc54be369 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/scaleCapability/ScaleCapability.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/scaleCapability/ScaleCapability.ets
@@ -64,7 +64,7 @@ struct ScaleCapability {
// Decorative border (purely for visual demonstration purposes).
.border({ width: 2, color: '#66F1CCB8' })
}
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.height(this.sliderHeight)
.width(this.sliderWidth)
.alignItems(HorizontalAlign.Center)
@@ -74,10 +74,9 @@ struct ScaleCapability {
}
.height('100%')
.width('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
-
// [End ScaleCapability]
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/wrapCapability/WrapCapability.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/wrapCapability/WrapCapability.ets
index 4ab7da14b28bf3b7cc8969ff9d9b45b09c4dabdc..d1443628822c2245a56e603fcac60404d2ac4466 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/wrapCapability/WrapCapability.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/atomicLayoutCapability/wrapCapability/WrapCapability.ets
@@ -46,14 +46,14 @@ struct WrapCapabilitySample {
justifyContent: FlexAlign.Center,
wrap: FlexWrap.Wrap
}) {
- ForEach(this.imageList, (item: Resource, index: number) => {
+ ForEach(this.imageList, (item: Resource) => {
Image(item)
.width(192)
.height(138)
.padding(10)
- }, (item: Resource, index: number) => JSON.stringify(item) + index)
+ }, (item: Resource, index: number) => item.toString() + index)
}
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.padding(20)
.width(this.rate * 100 + '%')
.borderRadius(16)
@@ -62,10 +62,9 @@ struct WrapCapabilitySample {
}
.width('100%')
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
-
// [End WrapCapabilitySample]
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample1.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample1.ets
index 09ec20165e9b1fe49953d9c6e0e546e29ef79773..8bc12df347b151abe43aa6b9b85b6f2b210f6a9f 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample1.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample1.ets
@@ -21,15 +21,14 @@ struct GridRowSample1 {
@State currentBreakpoint: string = 'md';
build() {
- GridRow({ breakpoints: { value: ['600vp', '700vp', '800vp', '900vp', '1000vp'] } }) {
+ GridRow({ breakpoints: { value: ['320vp', '600vp', '840vp', '1440vp'] } }) {
GridCol({
span: {
xs: 12,
sm: 12,
md: 12,
lg: 12,
- xl: 12,
- xxl: 12
+ xl: 12
}
}) {
Row() {
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample10.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample10.ets
index 1a9c686d87e35c8f7195a1bf542204846e10cf5f..bca08648a36d769a9be3c7186212c4fff1f86a8c 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample10.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample10.ets
@@ -35,10 +35,8 @@ struct GridRowSample10 {
build() {
Column({ space: 5 }) {
-
Column() {
GridRow({ columns: this.layoutColumns, direction: GridRowDirection.Row }) {
-
// The non-rendering component support the Height attribute of GridRow
GridCol({ span: 0 })
.height('100%')
@@ -48,7 +46,8 @@ struct GridRowSample10 {
Text('1')
.height('100%')
.fontSize(24);
- }.height('33.3%')
+ }
+ .height('33.3%')
.backgroundColor('#ff00ff94')
.alignSelf(this.col1Align);
@@ -56,17 +55,19 @@ struct GridRowSample10 {
Text('2')
.height('100%')
.fontSize(24);
- }.height('33.3%')
+ }
+ .height('33.3%')
.backgroundColor('#ff53e8ff')
.alignSelf(this.col2Align);
- }.width('100%')
+ }
+ .width('100%')
.height('100%');
- }.width('100%')
+ }
+ .width('100%')
.height('50%')
.border({ width: 1, color: '#ff00ffe9' });
Column() {
-
// Radio Groups
Row() {
Text($r('app.string.Radio_GridRow_All_LCR'))
@@ -95,7 +96,8 @@ struct GridRowSample10 {
}
.layoutWeight(1)
.justifyContent(FlexAlign.End);
- }.width('100%')
+ }
+ .width('100%')
.height('25%')
.justifyContent(FlexAlign.SpaceAround)
.margin({ top: '1%' });
@@ -127,7 +129,8 @@ struct GridRowSample10 {
}
.layoutWeight(1)
.justifyContent(FlexAlign.End);
- }.width('100%')
+ }
+ .width('100%')
.height('25%')
.justifyContent(FlexAlign.SpaceAround)
.margin({ top: '1%' });
@@ -159,7 +162,8 @@ struct GridRowSample10 {
}
.layoutWeight(1)
.justifyContent(FlexAlign.End);
- }.width('100%')
+ }
+ .width('100%')
.height('25%')
.justifyContent(FlexAlign.SpaceAround)
.margin({ top: '1%' });
@@ -199,7 +203,7 @@ struct GridRowSample10 {
}
.width('100%')
.height('30%')
- .padding({left: 10, right: 10});
+ .padding({ left: 10, right: 10 });
}
.width('100%')
.height('100%')
@@ -222,7 +226,6 @@ enum VerDirection {
const COL1_POSITIONS = [0, 2, 4]; // The values of the first component
class GridColController {
-
moveAllInHor(pos: HorDirection, inst: GridRowSample10) {
switch (pos) {
case HorDirection.LEFT:
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample2.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample2.ets
index 6c97bac14c566b592f63d6ad3381355023414274..bebf930dbe9e851d85643bebdf3b93ea272f1a8d 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample2.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample2.ets
@@ -26,12 +26,12 @@ struct GridRowSample2 {
Column() {
}
.width('100%')
- .backgroundColor('#19000000')
+ .backgroundColor($r('sys.color.comp_background_secondary'))
- // Content area, resizable range: [550vp, 50vp].
+ // Content area.
GridRow({
breakpoints: {
- value: ['100vp', '200vp', '300vp', '400vp', '500vp'],
+ value: ['320vp', '600vp', '840vp', '1440vp'],
reference: BreakpointsReference.ComponentSize
}
}) {
@@ -41,8 +41,7 @@ struct GridRowSample2 {
sm: 12,
md: 12,
lg: 12,
- xl: 12,
- xxl: 12
+ xl: 12
}
}) {
Row() {
@@ -57,7 +56,7 @@ struct GridRowSample2 {
}
}
.onBreakpointChange((currentBreakpoint: string) => {
- this.currentBreakpoint = currentBreakpoint
+ this.currentBreakpoint = currentBreakpoint;
})
.width('100%')
}
@@ -70,5 +69,4 @@ struct GridRowSample2 {
.maxSideBarWidth(600)
}
}
-
// [End GridRowSample2]
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample3.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample3.ets
index da436162568192530ea418b16d2fc487366c2253..e12642649ff3bb0eab3b971788516e49d7b41216 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample3.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample3.ets
@@ -30,7 +30,10 @@ struct GridRowSample3 {
// Config the values of columns and gutter at different breakpoints.
GridRow({
columns: { sm: 4, md: 8, lg: 12 },
- gutter: { x: { sm: 8, md: 16, lg: 24 }, y: { sm: 8, md: 16, lg: 24 } }
+ gutter: {
+ x: { sm: 8, md: 16, lg: 24 },
+ y: { sm: 8, md: 16, lg: 24 }
+ }
}) {
ForEach(this.bgColors, (bgColor: ResourceColor) => {
GridCol({ span: { sm: 2, md: 2, lg: 2 } }) {
@@ -39,7 +42,7 @@ struct GridRowSample3 {
.backgroundColor(bgColor)
.height(30)
}
- })
+ }, (bgColor: ResourceColor) => bgColor.toString())
}
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample4.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample4.ets
index 345a82bf4a87f00714fd28cf10a2f8b614f06bc8..d0acd0eb09d652e0f43b06424ab3017a98cc3d4e 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample4.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample4.ets
@@ -37,19 +37,22 @@ struct GridRowSample4 {
.height('100%')
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
- .backgroundColor('#19000000')
+ .backgroundColor($r('sys.color.comp_background_secondary'))
}
}
.height(50)
.borderWidth(2)
.borderColor('#F1CCB8')
- .padding({ left: this.gridMargin, right: this.gridMargin })
+ .padding({
+ left: this.gridMargin,
+ right: this.gridMargin
+ })
// Configure the left and right spacing values of grid components at different breakpoints using breakpoint change events.
.onBreakpointChange((currentBreakpoint: string) => {
- if (currentBreakpoint === 'lg' || currentBreakpoint === 'md') {
- this.gridMargin = 24;
- } else {
+ if (currentBreakpoint === 'xs' || currentBreakpoint === 'sm') {
this.gridMargin = 12;
+ } else {
+ this.gridMargin = 24;
}
})
@@ -69,13 +72,16 @@ struct GridRowSample4 {
.height('100%')
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
- .backgroundColor('#19000000')
+ .backgroundColor($r('sys.color.comp_background_secondary'))
}
}
.height(50)
.borderWidth(2)
.borderColor('#F1CCB8')
- .margin({ left: this.gridMargin, right: this.gridMargin })
+ .margin({
+ left: this.gridMargin,
+ right: this.gridMargin
+ })
}
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample5.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample5.ets
index ef4ea734a8137ecee7f11791db397427e771af56..65f23c6207f55b1eb5eb80886914716da6bde030 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample5.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample5.ets
@@ -29,17 +29,19 @@ struct GridRowSample5 {
];
build() {
- GridRow() {
+ GridRow({ columns: { sm: 12, md: 12, lg: 12 } }) {
ForEach(this.elements, (item: ColorArr) => {
GridCol({ span: { sm: 6, md: item.index % 3 === 0 ? 0 : 4, lg: 3 } }) {
Row() {
- Text(`${item.index}`).fontSize(24)
+ Text(`${item.index}`)
+ .fontSize(24)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color)
.height(30)
+ .width('100%')
}
- }, (item: ColorArr, index: number) => JSON.stringify(item) + index)
+ }, (item: ColorArr, index: number) => (item.index + index).toString())
}
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample6.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample6.ets
index 71ec27bf8700625bf6be023f788a8f1570754db4..f723300a6f2776f93f1fe5be90219825d53ff656 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample6.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample6.ets
@@ -29,7 +29,7 @@ struct GridRowSample6 {
];
build() {
- GridRow() {
+ GridRow({ columns: { sm: 12, md: 12, lg: 12 } }) {
ForEach(this.elements, (item: ColorArr) => {
GridCol({
span: { sm: 6, md: 4, lg: 3 },
@@ -42,8 +42,9 @@ struct GridRowSample6 {
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color)
.height(30)
+ .width('100%')
}
- }, (item: ColorArr, index: number) => JSON.stringify(item) + index)
+ }, (item: ColorArr, index: number) => (item.index + index).toString())
}
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample7.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample7.ets
index adff56075934b97097af2e9cdc5c9a4e03af9764..a662b9ee7f32ea2109c435ae8d9201b41b1e7d25 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample7.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample7.ets
@@ -29,7 +29,7 @@ struct GridRowSample7 {
];
build() {
- GridRow() {
+ GridRow({ columns: { sm: 12, md: 12, lg: 12 } }) {
ForEach(this.elements, (item: ColorArr) => {
GridCol({
span: { sm: 6, md: 4, lg: 3 },
@@ -42,8 +42,9 @@ struct GridRowSample7 {
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color)
.height(30)
+ .width('100%')
}
- }, (item: ColorArr, index: number) => JSON.stringify(item) + index)
+ }, (item: ColorArr, index: number) => (item.index + index).toString())
}
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample8.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample8.ets
index c956269e0d80292105f25efb79f5081a2f923e02..46f53f025d18007817fa179ee6d4508676760346 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample8.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample8.ets
@@ -29,7 +29,7 @@ struct GridRowSample8 {
];
build() {
- GridRow() {
+ GridRow({ columns: { sm: 12, md: 12, lg: 12 } }) {
ForEach(this.elements, (item: ColorArr) => {
// If the values of the three parameters are not configured at the md breakpoint, they will inherit the values from the sm breakpoint.
GridCol({
@@ -44,8 +44,9 @@ struct GridRowSample8 {
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color)
.height(30)
+ .width('100%')
}
- }, (item: ColorArr, index: number) => JSON.stringify(item) + index)
+ }, (item: ColorArr, index: number) => (item.index + index).toString())
}
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample9.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample9.ets
index 033277b51ee5194005e670d2f2828c69420e1978..0dea8e5a37b29377d5efbac66a947b16be7e9ff3 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample9.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/gridRow/gridRow/GridRowSample9.ets
@@ -29,13 +29,13 @@ struct GridRowSample9 {
];
build() {
- GridRow() {
+ GridRow({ columns: { sm: 12, md: 12, lg: 12 } }) {
GridCol({
span: { sm: 12, md: 10, lg: 8 },
offset: { sm: 0, md: 1, lg: 2 }
}) {
- GridRow() {
- ForEach(this.elements, (item : ColorArr) => {
+ GridRow({ columns: { sm: 12, md: 12, lg: 12 } }) {
+ ForEach(this.elements, (item: ColorArr) => {
GridCol({ span: { sm: 6, md: 4, lg: 3 } }) {
Row() {
Text(`${item.index}`)
@@ -44,10 +44,11 @@ struct GridRowSample9 {
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color)
.height(30)
+ .width('100%')
}
}, (item: ColorArr, index: number) => JSON.stringify(item) + index)
}
- .backgroundColor('#19000000')
+ .backgroundColor($r('sys.color.comp_background_secondary'))
.height('100%')
}
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/interactionNormCapability/InteractionNormCapability.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/interactionNormCapability/InteractionNormCapability.ets
index 65a0aff726007e5507a5181e09945c4e538ead12..4e66f0305fe8f7b174bc3795512fd91e2bf7430c 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/interactionNormCapability/InteractionNormCapability.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/interactionNormCapability/InteractionNormCapability.ets
@@ -12,7 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-import { IntentionCode } from '@ohos.multimodalInput.intentionCode';
+
+import { IntentionCode } from '@kit.InputKit';
import Logger from '../../model/Logger';
@Entry
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/resourceQualifier/ResourceQualifier.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/resourceQualifier/ResourceQualifier.ets
index e358b8449b5bab647568f35fc60fc9b133b28c10..5f47c2ad069a21c55b97d196595e3272de2a74b9 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/resourceQualifier/ResourceQualifier.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/resourceQualifier/ResourceQualifier.ets
@@ -22,7 +22,7 @@ struct ResourceQualifier {
Text($r('app.string.my_string'))
.fontSize(60)
.fontColor($r('app.color.my_color'))
- Image($r("app.media.my_image"))
+ Image($r('app.media.my_image'))
.width(100)
.height(100)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/ResponsiveLayoutIndex.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/ResponsiveLayoutIndex.ets
index 04acf013a61a1ac92c6938ddbb5288e5c57aeadc..066068a91ed26e28c0337dd54fa936229dd905a5 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/ResponsiveLayoutIndex.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/ResponsiveLayoutIndex.ets
@@ -13,15 +13,23 @@
* limitations under the License.
*/
-import { DirectoryItem, DirectoryList } from '../../common/DirectoryList'
+import { DirectoryItem, DirectoryList } from '../../common/DirectoryList';
@Entry
@Component
struct ResponsiveLayoutIndex {
private responsiveLayout: DirectoryItem[] = [
- { title: $r('app.string.breakpoint'), uri: 'pages/responsiveLayout/breakpoint/BreakpointSample', id:'BreakpointSample' },
- { title: $r('app.string.media_query'), uri: 'pages/responsiveLayout/mediaQuery/MediaQuerySample', id:'MediaQuerySample' },
- { title: $r('app.string.grid_layout'), uri: 'pages/gridRow/GridRowLayoutIndex', id:'GridRowLayoutIndex' }
+ {
+ title: $r('app.string.breakpoint'),
+ uri: 'pages/responsiveLayout/breakpoint/BreakpointSample',
+ id: 'BreakpointSample'
+ },
+ {
+ title: $r('app.string.media_query'),
+ uri: 'pages/responsiveLayout/mediaQuery/MediaQuerySample',
+ id: 'MediaQuerySample'
+ },
+ { title: $r('app.string.grid_layout'), uri: 'pages/gridRow/GridRowLayoutIndex', id: 'GridRowLayoutIndex' }
]
build() {
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/Breakpoint.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/Breakpoint.ets
index 363d668bed8ebeae4ad6886491750b881bf040c5..e91a66e21d1cd3c933f685dc3e021da2a65b6e01 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/Breakpoint.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/Breakpoint.ets
@@ -13,7 +13,7 @@
* limitations under the License.
*/
-import { mediaquery } from "@kit.ArkUI";
+import { mediaquery } from '@kit.ArkUI';
// [Start MediaQuery]
export type BreakpointType = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
@@ -70,7 +70,7 @@ export class BreakpointSystem {
if (mediaQueryResult.matches) {
this.updateAllState(breakpoint.name);
}
- })
+ });
})
}
@@ -79,7 +79,7 @@ export class BreakpointSystem {
}
public stop() {
- this.breakpoints.forEach((breakpoint: Breakpoint, index) => {
+ this.breakpoints.forEach((breakpoint: Breakpoint) => {
if (breakpoint.mediaQueryListener) {
breakpoint.mediaQueryListener.off('change');
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/BreakpointSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/BreakpointSample.ets
index 814c5121699c610c392fa0c0c67336fec3dd0292..40c0ea39981b115228f89cef03cfea58fe6053cb 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/BreakpointSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/responsiveLayout/breakpoint/BreakpointSample.ets
@@ -19,7 +19,7 @@ import { BreakpointSystem, BreakpointState } from './Breakpoint';
@Entry
@Component
struct BreakpointSample {
- @State compStr: BreakpointState = BreakpointState.of({ sm: "sm", md: "md", lg: "lg" })
+ @State compStr: BreakpointState = BreakpointState.of({ sm: 'sm', md: 'md', lg: 'lg' })
@State compImg: BreakpointState = BreakpointState.of({
sm: $r('app.media.sm_new'),
md: $r('app.media.md_new'),
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/TypicalSceneIndex.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/TypicalSceneIndex.ets
index dfd625a816df96862bb831a9d116de905b25b2d8..d27011cf6e7c69005045b75cce6e2ddb460c5be8 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/TypicalSceneIndex.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/TypicalSceneIndex.ets
@@ -13,7 +13,7 @@
* limitations under the License.
*/
-import { DirectoryItem, DirectoryList } from '../../common/DirectoryList'
+import { DirectoryItem, DirectoryList } from '../../common/DirectoryList';
@Entry
@Component
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/banner/BannerSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/banner/BannerSample.ets
index e61b41763a181eb1c4d0a5aef7d3436f8dc1062e..0d20f3a829896b695ded830193862cf50bda01ec 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/banner/BannerSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/banner/BannerSample.ets
@@ -17,7 +17,7 @@ import { BreakpointSystem, BreakPointType } from '../../../common/BreakpointSyst
@Entry
@Component
-export default struct Banner {
+struct Banner {
private bannerArr: Array = [
$r('app.media.banner1'),
$r('app.media.banner2'),
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/diversion/DiversionSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/diversion/DiversionSample.ets
index 8bb3746b6b685668d8e3c1afe4480e27028f5fe0..1c52407761ab4ae2a8b837e4129ca550d3a30d02 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/diversion/DiversionSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/diversion/DiversionSample.ets
@@ -13,12 +13,18 @@
* limitations under the License.
*/
+import { hilog } from '@kit.PerformanceAnalysisKit';
+
+const DOMAIN = 0x0000;
+const TAG = 'DiversionSample';
+const FORMAT = '%{public}s';
+
@Entry
@Component
struct DiversionSample {
- @State currentBreakpoint: string = 'md'
- @State imgHeight: number = 0
- @State textHeight: number = 0
+ @State currentBreakpoint: string = 'md';
+ @State imgHeight: number = 0;
+ @State textHeight: number = 0;
build() {
Row() {
@@ -35,7 +41,8 @@ struct DiversionSample {
.justifyContent(FlexAlign.Center)
}
.onAreaChange((oldArea: Area, newArea: Area) => {
- this.imgHeight = newArea.height as number
+ hilog.info(DOMAIN, TAG, FORMAT, `oldArea: ${oldArea}, newArea: ${newArea}, newArea: ${this.imgHeight}`);
+ this.imgHeight = newArea.height as number;
})
GridCol({ span: { sm: 12, md: 6, lg: 6 } }) {
@@ -50,7 +57,8 @@ struct DiversionSample {
.fontWeight(FontWeight.Medium)
}
.onAreaChange((oldArea: Area, newArea: Area) => {
- this.textHeight = newArea.height as number
+ hilog.info(DOMAIN, TAG, FORMAT, `oldArea: ${oldArea}, newArea: ${newArea}, newArea: ${this.imgHeight}`);
+ this.textHeight = newArea.height as number;
})
.padding({ left: 24, right: 24 })
.justifyContent(FlexAlign.Center)
@@ -62,6 +70,6 @@ struct DiversionSample {
})
}
.height('100%')
- .backgroundColor('#F1F3f5')
+ .backgroundColor($r('sys.color.background_secondary'))
}
}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/header/HeaderSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/header/HeaderSample.ets
index 1e5ec3af53a3da42d88643b95be71630d8f4993b..5e7d5fa6d84fca5b776bc014b0ff6d027adaee51 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/header/HeaderSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/header/HeaderSample.ets
@@ -15,7 +15,7 @@
@Entry
@Component
-export default struct Header {
+struct Header {
@State needWrap: boolean = true
build() {
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/indentation/IndentationSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/indentation/IndentationSample.ets
index ce0cfef1951593d9557fedd7fc55200d3437e181..f61222a6f910139ea29cd1c13b64b69926a3b3f8 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/indentation/IndentationSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/indentation/IndentationSample.ets
@@ -19,7 +19,7 @@ struct IndentationSample {
build() {
Row() {
GridRow() {
- ForEach([0, 1, 2, 4], (item:number, index) => {
+ ForEach([0, 1, 2, 4], (item: number, index) => {
GridCol({
span: { sm: 10, md: 8, lg: 8 },
offset: {
@@ -38,7 +38,7 @@ struct IndentationSample {
.height('100%')
.alignItems((VerticalAlign.Center))
.justifyContent(FlexAlign.Center)
- .backgroundColor('#F1F3f5')
+ .backgroundColor($r('sys.color.background_secondary'))
}
}
@@ -73,8 +73,13 @@ struct ItemContent {
}
.height(128)
.borderRadius(24)
- .backgroundColor('#FFFFFF')
- .padding({ top: 12, bottom: 12, left: 18, right: 18 })
+ .backgroundColor($r('sys.color.comp_background_primary'))
+ .padding({
+ top: 12,
+ bottom: 12,
+ left: 18,
+ right: 18
+ })
.margin({ bottom: 12 })
}
}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiLaneList/MultiLaneListSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiLaneList/MultiLaneListSample.ets
index 63a3dffe2130d97b4c43ada2391f5508448abdc6..e9f25265012d52d6f25f6ff3f791982ecffd1757 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiLaneList/MultiLaneListSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiLaneList/MultiLaneListSample.ets
@@ -13,9 +13,9 @@
* limitations under the License.
*/
-import { BreakpointSystem, BreakPointType } from '../../../common/BreakpointSystem'
+import { BreakpointSystem, BreakPointType } from '../../../common/BreakpointSystem';
-class ListItemInfo {
+class ListItemInfo {
name: Resource = $r('app.string.playlist_collection');
image: Resource = $r('app.media.1');
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/applications/Applications.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/applications/Applications.ets
index e2426f354d5e9e348fac8a99f58221915c2df3d0..ed9553d923024dd2b71a2d60ce060ae463cc3eda 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/applications/Applications.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/applications/Applications.ets
@@ -48,4 +48,4 @@ export const ApplicationsData: Resource [] = [
$r('app.string.multiScene_application'),
$r('app.string.multiScene_application'),
$r('app.string.multiScene_application')
-]
\ No newline at end of file
+];
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/home/Home.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/home/Home.ets
index 384ea15f603e6a81c49044ac7e744585c0911a25..9e593a5d7b04f1e2219d415a65f1d3b556225f4f 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/home/Home.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/data/home/Home.ets
@@ -21,31 +21,31 @@ export interface Articles {
export const ArticlesData: Articles[] = [
{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title1'),
disc: $r('app.string.multiScene_title1_disc')
},
{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title2'),
disc: $r('app.string.multiScene_title2_disc')
},
{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title3'),
disc: $r('app.string.multiScene_title3_disc')
},
{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title4'),
disc: $r('app.string.multiScene_title4_disc')
},
{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title5'),
disc: $r('app.string.multiScene_title5_disc')
},{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title5'),
disc: $r('app.string.multiScene_title5_disc')
},{
@@ -54,7 +54,7 @@ export const ArticlesData: Articles[] = [
disc: $r('app.string.multiScene_title6_disc')
},
{
- icon: $r("app.media.icon"),
+ icon: $r('app.media.icon'),
title: $r('app.string.multiScene_title7'),
disc: $r('app.string.multiScene_title7_disc')
},
@@ -73,7 +73,7 @@ export const ArticlesData: Articles[] = [
title: $r('app.string.multiScene_title10'),
disc: $r('app.string.multiScene_title10_disc')
}
-]
+];
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/MultiScene.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/MultiScene.ets
index b48607d53018936b3cc615054db475512a1b8ebb..7c39391695ad5ac06140565fb24bdba9e9f24acc 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/MultiScene.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/MultiScene.ets
@@ -13,7 +13,7 @@
* limitations under the License.
*/
-import mediaquery from '@ohos.mediaquery';
+import { mediaquery } from '@kit.ArkUI';
import { HomePage } from './home/Home';
import { Applications } from './applications/Applications';
import { Play } from './player/Player';
@@ -50,12 +50,12 @@ struct DiversionSample {
NavigationTitle() {
Column() {
Text($r('app.string.multiScene_header_title'))
- .fontColor('#182431')
+ .fontColor($r('sys.color.font_primary'))
.fontSize(30)
.lineHeight(41)
.fontWeight(700)
Text($r('app.string.multiScene_header_subtitle'))
- .fontColor('#182431')
+ .fontColor($r('sys.color.font_primary'))
.fontSize(14)
.lineHeight(19)
.opacity(0.4)
@@ -126,7 +126,7 @@ struct DiversionSample {
.titleMode(NavigationTitleMode.Full)
}
.height('100%')
- .backgroundColor('#F1F3f5')
+ .backgroundColor($r('sys.color.background_secondary'))
}
}
}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/applications/Applications.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/applications/Applications.ets
index 00dc45b2be56044a93aa312ccfa442f03b128905..60a7e1f1c4a36414d41704d4601ea48bfd6aca66 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/applications/Applications.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/applications/Applications.ets
@@ -46,7 +46,7 @@ export struct Applications {
}.width('80%')
}
.width('90%')
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.borderRadius(16)
.padding({ top: 12 })
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/home/Home.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/home/Home.ets
index ca041d9163384e4fde88287788e1a1dee33fb89f..a15b626c7256dc0a6c976262ee17c3c74b11a94a 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/home/Home.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/home/Home.ets
@@ -13,40 +13,47 @@
* limitations under the License.
*/
+import { hilog } from '@kit.PerformanceAnalysisKit';
import { ArticlesData, Articles } from '../../data/home/Home';
+const DOMAIN = 0x0000;
+const TAG = 'DirectoryList';
+const FORMAT = '%{public}s';
+
@Component
export struct HomePage {
private swiperController: SwiperController = new SwiperController()
private bannerArr: Array = [
- $r('app.media.banner1'),
- $r('app.media.banner2'),
- $r('app.media.banner3'),
- $r('app.media.banner4'),
- $r('app.media.banner5'),
- $r('app.media.banner6')
- ]
- @State imgHeight: number = 0
- @State textHeight: number = 0
- @State spaceBottom: number = 0
- @State currentBreakpoint: string = 'md'
+ $r('app.media.banner1'),
+ $r('app.media.banner2'),
+ $r('app.media.banner3'),
+ $r('app.media.banner4'),
+ $r('app.media.banner5'),
+ $r('app.media.banner6')
+ ];
+ @State imgHeight: number = 0;
+ @State textHeight: number = 0;
+ @State spaceBottom: number = 0;
+ @State currentBreakpoint: string = 'md';
constructor() {
super()
}
- @Builder Item(article: Articles) {
+ @Builder
+ Item(article: Articles) {
Flex() {
Row() {
Image(article.icon)
- }.width(43)
+ }
+ .width(43)
.height(43)
.borderRadius(12)
Column() {
Row() {
Text(article.title)
- .fontColor('#182431')
+ .fontColor($r('sys.color.font_primary'))
.fontSize(20)
}
.width('100%')
@@ -54,7 +61,7 @@ export struct HomePage {
Row() {
Text(article.disc)
.fontSize(15)
- .fontColor('#182431')
+ .fontColor($r('sys.color.font_primary'))
.opacity(0.4)
}
.width('100%')
@@ -63,8 +70,13 @@ export struct HomePage {
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.SpaceAround)
}
- .padding({ top: 13, bottom: 13, left: 13, right: 13 })
- .backgroundColor('#FFFFFF')
+ .padding({
+ top: 13,
+ bottom: 13,
+ left: 13,
+ right: 13
+ })
+ .backgroundColor($r('sys.color.comp_background_primary'))
.borderRadius(25)
}
@@ -79,7 +91,8 @@ export struct HomePage {
ForEach(this.bannerArr, (item: Resource) => {
Image(item)
})
- }.width('100%')
+ }
+ .width('100%')
}
.width('100%')
.aspectRatio(1.5)
@@ -89,29 +102,30 @@ export struct HomePage {
.justifyContent(FlexAlign.Center)
}
.onAreaChange((oldArea: Area, newArea: Area) => {
- this.imgHeight = newArea.height as number
- console.log(String(this.imgHeight))
+ this.imgHeight = newArea.height as number;
+ hilog.info(DOMAIN, TAG, FORMAT, `oldArea: ${oldArea}, newArea: ${newArea}, newArea: ${this.imgHeight}`);
})
GridCol({ span: { sm: 12, md: 6, lg: 6 } }) {
Column() {
List({ space: 10, initialIndex: 0 }) {
- ForEach(ArticlesData, (item : Articles) => {
+ ForEach(ArticlesData, (item: Articles) => {
ListItem() {
this.Item(item)
}
})
}
- .listDirection(Axis.Vertical) // 排列方向
- .edgeEffect(EdgeEffect.Spring) // 滑动到边缘无效果
+ .listDirection(Axis.Vertical) // orientation
+ .edgeEffect(EdgeEffect.Spring) // There is no effect when sliding to the edge.
.onScrollIndex((firstIndex: number, lastIndex: number) => {
- console.info('first' + firstIndex)
- console.info('last' + lastIndex)
+ hilog.info(DOMAIN, TAG, FORMAT, `first: ${firstIndex}`);
+ hilog.info(DOMAIN, TAG, FORMAT, `last: ${lastIndex}`);
})
.width('100%')
}
.onAreaChange((oldArea: Area, newArea: Area) => {
- this.textHeight = newArea.height as number
+ hilog.info(DOMAIN, TAG, FORMAT, `oldArea: ${oldArea}, newArea: ${newArea}`);
+ this.textHeight = newArea.height as number;
})
.padding({ left: 15, right: 15 })
.justifyContent(FlexAlign.Center)
@@ -120,14 +134,14 @@ export struct HomePage {
}
.onBreakpointChange((breakPoint: string) => {
- this.currentBreakpoint = breakPoint
+ this.currentBreakpoint = breakPoint;
if (breakPoint === 'sm') {
- this.spaceBottom = 20
+ this.spaceBottom = 20;
} else {
- this.spaceBottom = 0
+ this.spaceBottom = 0;
}
})
-
- }.width('100%')
+ }
+ .width('100%')
}
}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/player/Player.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/player/Player.ets
index f2a64bb302e2008e856ab948191f56f5110e07b2..5c6f1d05e15dccfe56e28c501031dc94dea5134d 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/player/Player.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/multiScene/pages/player/Player.ets
@@ -24,41 +24,57 @@ export struct Play {
.width(200)
.height(200)
.objectFit(ImageFit.Contain)
- }.margin({ bottom: 10 })
+ }
+ .margin({ bottom: 10 })
}
GridCol({ span: { sm: 12, md: 6, lg: 6 } }) {
Row() {
Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.favorite')).width(48).height(48)}
+ Image($r('app.media.favorite'))
+ .width(48)
+ .height(48)
+ }
.width(48)
.height(48)
.displayPriority(1)
.backgroundColor('white')
Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.down')).width(48).height(48)}
- .width(48)
- .height(48)
- .displayPriority(2)
- .backgroundColor('white')
+ Image($r('app.media.down'))
+ .width(48)
+ .height(48)
+ }
+ .width(48)
+ .height(48)
+ .displayPriority(2)
+ .backgroundColor('white')
Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.pause')).width(48).height(48)}
+ Image($r('app.media.pause'))
+ .width(48)
+ .height(48)
+ }
.width(48)
.height(48)
.displayPriority(3)
.backgroundColor('white')
Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.next')).width(48).height(48)}
+ Image($r('app.media.next'))
+ .width(48)
+ .height(48)
+ }
.width(48)
.height(48)
.displayPriority(2)
.backgroundColor('white')
Button({ type: ButtonType.Circle, stateEffect: true }) {
- Image($r('app.media.list')).width(48).height(48)}
+ Image($r('app.media.list'))
+ .width(48)
+ .height(48)
+ }
.width(48)
.height(48)
.displayPriority(1)
@@ -68,10 +84,11 @@ export struct Play {
.height('100%')
.height(90)
.borderRadius(16)
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.comp_background_primary'))
.justifyContent(FlexAlign.Center)
}
}
- }.width('80%')
+ }
+ .width('80%')
}
}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/operationEntries/OperationEntriesSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/operationEntries/OperationEntriesSample.ets
index 8116bbb4d01bd38efb762b8744eb83c10f5758e8..a9e814f4ca14f4836e856db41adeebb977ba187e 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/operationEntries/OperationEntriesSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/operationEntries/OperationEntriesSample.ets
@@ -20,7 +20,7 @@ class OperationItem {
@Entry
@Component
-export default struct OperationEntries {
+struct OperationEntries {
private listData: Array = [
{ name: $r('app.string.operation1'), icon: $r('app.media.self_fm') },
{ name: $r('app.string.operation2'), icon: $r('app.media.singer') },
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/repeat/RepeatSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/repeat/RepeatSample.ets
index 5814dc6a58c92bcaa34d923910610db8045cc67f..1f21b9378af96b3637935cb9c07fcad0058743d0 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/repeat/RepeatSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/repeat/RepeatSample.ets
@@ -58,7 +58,7 @@ struct RepeatSample {
.scrollBar(BarState.Off)
}
.height('100%')
- .backgroundColor('#F1F3F5')
+ .backgroundColor($r('sys.color.background_secondary'))
.padding({ left: 30, right: 30 })
}
}
@@ -99,7 +99,7 @@ struct RepeatItemContent {
right: 37
})
.height(70)
- .backgroundColor('#FFFFFF')
+ .backgroundColor($r('sys.color.background_secondary'))
.margin({ bottom: 12 })
.borderRadius(24)
}
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/responsiveGrid/ResponsiveGridSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/responsiveGrid/ResponsiveGridSample.ets
index 24cad3738f359413f1f4ae3e000646c2d605a0b4..f573f49bc79df1dc09df3545e6bb895cc3e02325 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/responsiveGrid/ResponsiveGridSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/responsiveGrid/ResponsiveGridSample.ets
@@ -22,7 +22,7 @@ class GridItemInfo {
@Entry
@Component
-export default struct ResponsiveGrid {
+struct ResponsiveGrid {
private data: Array = [
{ name: $r('app.string.playlist_collection'), image: $r('app.media.1') },
{ name: $r('app.string.playlist_collection'), image: $r('app.media.2') },
diff --git a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/sidebar/SidebarSample.ets b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/sidebar/SidebarSample.ets
index 450d07df7b96e5a7c6a5fbc95dc17759974bbb3a..cc694571e4c5e067a1913e4112476755c50f6b05 100644
--- a/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/sidebar/SidebarSample.ets
+++ b/AdaptiveCapabilities/entry/src/main/ets/pages/typicalScene/sidebar/SidebarSample.ets
@@ -17,19 +17,19 @@ import { BreakpointSystem } from '../../../common/BreakpointSystem'
class ImageData {
label: string = '';
- imageSrc: Resource = $r("app.media.my_image_moon");
+ imageSrc: Resource = $r('app.media.my_image_moon');
}
const images: ImageData[] = [
- { label: 'moon', imageSrc: $r("app.media.my_image_moon") },
- { label: 'sun', imageSrc: $r("app.media.my_image") }
+ { label: 'moon', imageSrc: $r('app.media.my_image_moon') },
+ { label: 'sun', imageSrc: $r('app.media.my_image') }
]
@Entry
@Component
struct SideBarSample {
@StorageLink('currentBreakpoint')
- private currentBreakpoint: string = "md"
+ private currentBreakpoint: string = 'md'
private breakpointSystem: BreakpointSystem = new BreakpointSystem()
@State showSideBar: boolean = false
@State selectIndex: number = 0
@@ -54,7 +54,7 @@ struct SideBarSample {
.fontWeight(FontWeight.Bold)
.borderRadius(5)
.margin(20)
- .backgroundColor('#ffffff')
+ .backgroundColor($r('sys.color.background_secondary'))
.textAlign(TextAlign.Center)
.width(180)
.height(36)
@@ -71,7 +71,8 @@ struct SideBarSample {
Column() {
this.itemBuilder(0)
this.itemBuilder(1)
- }.backgroundColor('#F1F3F5')
+ }
+ .backgroundColor($r('sys.color.background_secondary'))
.justifyContent(FlexAlign.Center)
Column() {
diff --git a/AdaptiveCapabilities/entry/src/main/module.json5 b/AdaptiveCapabilities/entry/src/main/module.json5
index bc90a1ccfd576e02355978e0aea277a11a316a2f..10ac59cce18741c6d637accae7fbaa0c4c210a1d 100644
--- a/AdaptiveCapabilities/entry/src/main/module.json5
+++ b/AdaptiveCapabilities/entry/src/main/module.json5
@@ -20,7 +20,7 @@
"description": "$string:entry_desc",
"mainElement": "MainAbility",
"deviceTypes": [
- "default",
+ "phone",
"tablet"
],
"deliveryWithInstall": true,
diff --git a/AdaptiveCapabilities/entry/src/main/resources/en-tablet/element/string.json b/AdaptiveCapabilities/entry/src/main/resources/en-tablet/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..4d6296d1f109607f2c9c41eef623097183dbac51
--- /dev/null
+++ b/AdaptiveCapabilities/entry/src/main/resources/en-tablet/element/string.json
@@ -0,0 +1,8 @@
+{
+ "string": [
+ {
+ "name": "my_string",
+ "value": "tablet"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/entry/src/main/resources/zh-tablet/element/string.json b/AdaptiveCapabilities/entry/src/main/resources/zh-tablet/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..c64ff816b94ae3ea64a55b975a1d6278d2393560
--- /dev/null
+++ b/AdaptiveCapabilities/entry/src/main/resources/zh-tablet/element/string.json
@@ -0,0 +1,8 @@
+{
+ "string": [
+ {
+ "name": "my_string",
+ "value": "平板"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/AdaptiveCapabilities/hvigorfile.js b/AdaptiveCapabilities/hvigorfile.js
deleted file mode 100644
index 5f2735e3deeaf655828407544bbed9365c258278..0000000000000000000000000000000000000000
--- a/AdaptiveCapabilities/hvigorfile.js
+++ /dev/null
@@ -1,2 +0,0 @@
-// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
-module.exports = require('@ohos/hvigor-ohos-plugin').appTasks
\ No newline at end of file
diff --git a/AdaptiveCapabilities/hvigorfile.ts b/AdaptiveCapabilities/hvigorfile.ts
new file mode 100644
index 0000000000000000000000000000000000000000..20a8c119149bca149dc03919c5c1c022cd4ff077
--- /dev/null
+++ b/AdaptiveCapabilities/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/AdaptiveCapabilities/screenshots/devices/img1.jpeg b/AdaptiveCapabilities/screenshots/devices/img1.jpeg
deleted file mode 100644
index e6d546db94e47d373678db4770ab1a50c916ce80..0000000000000000000000000000000000000000
Binary files a/AdaptiveCapabilities/screenshots/devices/img1.jpeg and /dev/null differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img1.png b/AdaptiveCapabilities/screenshots/devices/img1.png
new file mode 100644
index 0000000000000000000000000000000000000000..1a42afd8ff6f474e08f45723666c59e783b31315
Binary files /dev/null and b/AdaptiveCapabilities/screenshots/devices/img1.png differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img2.jpeg b/AdaptiveCapabilities/screenshots/devices/img2.jpeg
deleted file mode 100644
index 4f223e22a334e7bc0c82097b1c3848c15fe788e9..0000000000000000000000000000000000000000
Binary files a/AdaptiveCapabilities/screenshots/devices/img2.jpeg and /dev/null differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img2.png b/AdaptiveCapabilities/screenshots/devices/img2.png
new file mode 100644
index 0000000000000000000000000000000000000000..a9fe4929aad4a50542ea97b095c55d6b6290b4cb
Binary files /dev/null and b/AdaptiveCapabilities/screenshots/devices/img2.png differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img3.jpeg b/AdaptiveCapabilities/screenshots/devices/img3.jpeg
deleted file mode 100644
index 3f3e50c290b9dea54adbb8c6e63c7666502800f0..0000000000000000000000000000000000000000
Binary files a/AdaptiveCapabilities/screenshots/devices/img3.jpeg and /dev/null differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img3.png b/AdaptiveCapabilities/screenshots/devices/img3.png
new file mode 100644
index 0000000000000000000000000000000000000000..55e17cea6ed5e6f9008cdfd82d106e3e39adbd44
Binary files /dev/null and b/AdaptiveCapabilities/screenshots/devices/img3.png differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img4.jpeg b/AdaptiveCapabilities/screenshots/devices/img4.jpeg
deleted file mode 100644
index d44d75046d0c5f9fcf196ecdffd731e857b55e25..0000000000000000000000000000000000000000
Binary files a/AdaptiveCapabilities/screenshots/devices/img4.jpeg and /dev/null differ
diff --git a/AdaptiveCapabilities/screenshots/devices/img4.png b/AdaptiveCapabilities/screenshots/devices/img4.png
new file mode 100644
index 0000000000000000000000000000000000000000..03ca6a54e5a267d907f1171efecac95bd521130d
Binary files /dev/null and b/AdaptiveCapabilities/screenshots/devices/img4.png differ
diff --git a/ApiUsingStandards/README.md b/ApiUsingStandards/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b50c899981d12d082da345b18238bd10f949df45
--- /dev/null
+++ b/ApiUsingStandards/README.md
@@ -0,0 +1,66 @@
+# 易错API的使用规范
+
+### 介绍
+
+本示例是《易错API的使用规范》最佳实践中的代码示例片段。
+
+### 使用说明
+
+不涉及。
+
+
+### 工程目录
+
+```
+├──entry/src/main/ets
+│ ├──cpp
+│ │ ├──CMakeList.txt // CMake文件
+│ │ ├──napi_init.cpp // napi初始化
+│ │ └──callbackTest.cpp // callback测试类
+│ ├──cpp/types/libentry
+│ │ ├──oh-package.json5 // lib打包信息
+│ │ └──Index.d.ts // lib接口索引
+│ ├──entryability
+│ │ └──EntryAbility.ets // 入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 数据备份类
+│ └──pages
+│ ├──animate1.ets // 示例页面
+│ ├──animate2.ets // 示例页面
+│ ├──AVImageGenerator.ets // 示例页面
+│ ├──camera.ets // 示例页面
+│ ├──Index.ets // 示例页面
+│ ├──playStateCallback.ets // 示例页面
+│ └──StyleExample.ets // 示例页面
+└──entry/src/main/resources // 应用资源目录
+```
+
+
+### 具体实现
+
+1. 主要配套文档介绍易错API的使用规范。
+
+### 相关权限
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ApiUsingStandards
+git checkout
+```
\ No newline at end of file
diff --git a/ApiUsingStandards/build-profile.json5 b/ApiUsingStandards/build-profile.json5
index 03ac3a3ae9dd397844173066e5d5ee21b49455a1..492123c253881f5bbd9bc76553bfb74e842dfb40 100644
--- a/ApiUsingStandards/build-profile.json5
+++ b/ApiUsingStandards/build-profile.json5
@@ -5,7 +5,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.4(16)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/ApiUsingStandards/entry/src/main/cpp/callbackTest.cpp b/ApiUsingStandards/entry/src/main/cpp/callbackTest.cpp
index b032fcf4a3c369ce62a86fd54915c1a84b66d2cd..23bcd8ccd3b15052ea968f96978ad5505da0f033 100644
--- a/ApiUsingStandards/entry/src/main/cpp/callbackTest.cpp
+++ b/ApiUsingStandards/entry/src/main/cpp/callbackTest.cpp
@@ -1,8 +1,18 @@
-//
-// Created on 2025/5/30.
-//
-// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
-// please include "napi/native_api.h".
+/*
+ * Copyright (c) 2025 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 "napi/native_api.h"
#include "uv.h"
#define LOG_DOMAIN 0X0202
diff --git a/ApiUsingStandards/entry/src/main/cpp/napi_init.cpp b/ApiUsingStandards/entry/src/main/cpp/napi_init.cpp
index 85330e3e84d1f6c8a82e544fb315483ca597d23d..d0e1aafcb6b5c3252ef439d9d9d54e8c082fda1d 100644
--- a/ApiUsingStandards/entry/src/main/cpp/napi_init.cpp
+++ b/ApiUsingStandards/entry/src/main/cpp/napi_init.cpp
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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 "napi/native_api.h"
static napi_value Add(napi_env env, napi_callback_info info)
diff --git a/ApiUsingStandards/entry/src/main/ets/entryability/EntryAbility.ets b/ApiUsingStandards/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..d6c8a8e454f830409bd59e18826cd56e0412125c 100644
--- a/ApiUsingStandards/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ApiUsingStandards/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,12 +1,33 @@
+/*
+ * Copyright (c) 2025 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, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
+import { BusinessError } from '@kit.BasicServicesKit';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (e) {
+ let err = e as BusinessError;
+ hilog.error(DOMAIN, 'testTag', `failed code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ApiUsingStandards/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/ApiUsingStandards/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
index 8e4de99282050bad799ac892eb85ac5449364a51..0a97e21bd7a15599af76a806695860ff1eb0ebfe 100644
--- a/ApiUsingStandards/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
+++ b/ApiUsingStandards/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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';
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/AVImageGenerator.ets b/ApiUsingStandards/entry/src/main/ets/pages/AVImageGenerator.ets
index 8387d06974d2362bfba54a0d3d13ac30c88ac4c5..ce2700bea80461f986af0948f73d1a949b81e4db 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/AVImageGenerator.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/AVImageGenerator.ets
@@ -1,8 +1,23 @@
+/*
+ * Copyright (c) 2025 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 { media } from '@kit.MediaKit'
import { image } from '@kit.ImageKit'
import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
import { display } from '@kit.ArkUI';
-import { common } from '@kit.AbilityKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
class AVImageGeneratorClass {
pixelMap: image.PixelMap[] = [];
@@ -17,53 +32,46 @@ class AVImageGeneratorClass {
videoHeight: number = 0;
// [Start av_image_generator_class]
- async fetchFrame() {
- await this.fetchMeta()
+ async fetchFrame(): Promise {
+ await this.fetchMeta();
if (canIUse("SystemCapability.Multimedia.Media.AVImageGenerator")) {
- this.pixelMap = new Array
- let avImageGenerator: media.AVImageGenerator = await media.createAVImageGenerator()
+ this.pixelMap = new Array;
+ let avImageGenerator: media.AVImageGenerator = await media.createAVImageGenerator();
// raw fd
- avImageGenerator.fdSrc = fs.openSync(this.rootPath + this.testFilename)
+ avImageGenerator.fdSrc = fs.openSync(this.rootPath + this.testFilename);
for (let i = 0; i < 6; i++) {
- console.info(`time real ${this.diffTime[i]}`)
- let pixelMap = await avImageGenerator.fetchFrameByTime(this.diffTime[i], this.seekOption,
- { width: this.pixelMapWidth, height: this.pixelMapHeight })
- this.pixelMap.push(pixelMap)
+ let pixelMap: image.PixelMap = await avImageGenerator.fetchFrameByTime(this.diffTime[i], this.seekOption,
+ { width: this.pixelMapWidth, height: this.pixelMapHeight });
+ this.pixelMap.push(pixelMap);
if (i == 0) {
- this.pixelLcd = pixelMap
- let rate = pixelMap.getImageInfoSync().size.height / pixelMap.getImageInfoSync().size.width
+ this.pixelLcd = pixelMap;
+ let rate: number = pixelMap.getImageInfoSync().size.height / pixelMap.getImageInfoSync().size.width;
this.lcdHeight =
- display.getDefaultDisplaySync().width / 2 / display.getDefaultDisplaySync().densityPixels * rate
+ display.getDefaultDisplaySync().width / 2 / display.getDefaultDisplaySync().densityPixels * rate;
}
- let imageInfo: image.ImageInfo = pixelMap.getImageInfoSync()
- console.info(`colorFormat ${imageInfo.pixelFormat} width ${imageInfo.size.width} height ${imageInfo.size.height} isHdr ${imageInfo.isHdr}`)
+ let imageInfo: image.ImageInfo = pixelMap.getImageInfoSync();
+ hilog.info(0x0000, 'testTag',
+ `colorFormat ${imageInfo.pixelFormat} width ${imageInfo.size.width} height ${imageInfo.size.height} isHdr ${imageInfo.isHdr}`);
}
}
}
- async fetchMeta() {
+ async fetchMeta(): Promise {
if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) {
- console.info(`typeof ${typeof media.createAVMetadataExtractor()}`)
- let avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor()
-
-
+ let avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
let fd: number = fs.openSync(this.rootPath + this.testFilename).fd;
let fileSize: number = fs.statSync(this.rootPath + this.testFilename).size;
-
-
let dataSrc: media.AVDataSrcDescriptor = {
fileSize: fileSize,
callback: (buffer, len, pos) => {
if (buffer == undefined || len == undefined || pos == undefined) {
- console.error(`dataSrc callback param invalid`)
- return -1
+ return -1;
}
let options: ReadOptions = {
offset: pos,
length: len
}
- let num = fs.readSync(fd, buffer, options)
- console.info('readAt end, num: ' + num)
+ let num: number = fs.readSync(fd, buffer, options);
if (num > 0 && fileSize >= pos) {
return num;
}
@@ -71,44 +79,36 @@ class AVImageGeneratorClass {
}
}
-
- avMetadataExtractor.dataSrc = dataSrc
-
-
- let metadata: media.AVMetadata
-
-
+ avMetadataExtractor.dataSrc = dataSrc;
+ let metadata: media.AVMetadata;
try {
- metadata = await avMetadataExtractor.fetchMetadata()
+ metadata = await avMetadataExtractor.fetchMetadata();
} catch (error) {
- console.info('error code ' + error.code)
- return
+ hilog.error(0x0000, 'testTag', 'error code ' + error.code);
+ return;
}
-
-
- console.info(`metadata ${JSON.stringify(metadata)}`)
if (metadata.duration) {
- console.info(`fetchMetadata success duration ${metadata.duration}`)
- let duration = parseInt(metadata.duration) * 1000
- let pick = duration / 5
- this.diffTime[0] = 0
- this.diffTime[5] = duration
- let time = pick
+ let duration: number = parseInt(metadata.duration) * 1000;
+ let pick: number = duration / 5;
+ this.diffTime[0] = 0;
+ this.diffTime[5] = duration;
+ let time: number = pick;
for (let i = 1; i < 5; i++) {
- this.diffTime[i] = time
- time += pick
+ this.diffTime[i] = time;
+ time += pick;
}
}
if (metadata.videoHeight && metadata.videoWidth) {
- let rate = Number(metadata.videoHeight) / Number(metadata.videoWidth)
+ let rate: number = Number(metadata.videoHeight) / Number(metadata.videoWidth);
if (metadata.videoOrientation && Number(metadata.videoOrientation) % 180) {
rate = 1 / rate;
}
this.videoHeight =
- display.getDefaultDisplaySync().width / 6 / display.getDefaultDisplaySync().densityPixels * rate
+ display.getDefaultDisplaySync().width / 6 / display.getDefaultDisplaySync().densityPixels * rate;
}
- await avMetadataExtractor.release()
+ await avMetadataExtractor.release();
}
}
+
// [End av_image_generator_class]
}
\ No newline at end of file
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/Index.ets b/ApiUsingStandards/entry/src/main/ets/pages/Index.ets
index 0738f87946f68a3e67f70b0397ea1c8a4ab75500..71b23174229cd3cf4b127d77e25069eb7a1f3c4a 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/Index.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/Index.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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 testNapi from 'libentry.so';
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/StyleExample.ets b/ApiUsingStandards/entry/src/main/ets/pages/StyleExample.ets
index e5f00680b35ed2e1176294eb7b1fe59acc4756a4..9082508ea1fa4ef3e3ca26458ddc90aaf9be0816 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/StyleExample.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/StyleExample.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
// [Start style_example]
// xxx.ets
@Entry
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/animate1.ets b/ApiUsingStandards/entry/src/main/ets/pages/animate1.ets
index 7c11c06a61ce5bc9db0d707e0fb4824d073f34f6..9054e23ed408b46a94c47fe31c0227e02b1b2588 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/animate1.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/animate1.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
// [Start animate_to1]
class MyData {
str: string;
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/animate2.ets b/ApiUsingStandards/entry/src/main/ets/pages/animate2.ets
index 3bc6493f1b8d0d1a915492476089d79c5c431210..663bcbbd95200b1055f9dd754a48bbdbbbe306f1 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/animate2.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/animate2.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
// [Start animate_to2]
class MyData {
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/camera.ets b/ApiUsingStandards/entry/src/main/ets/pages/camera.ets
index 5006ccb5997d640aa4bde9607e8f95a7ad660963..0e31101aef0778563fc1916350e2df96b7d7e3e5 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/camera.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/camera.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 易错API的使用规范
*/
@@ -7,11 +22,12 @@ import { camera } from '@kit.CameraKit';
class cameraClass {
cameraManager: camera.CameraManager | undefined = undefined;
- getCameraManager(context: Context) {
+ getCameraManager(context: Context): void {
this.cameraManager = camera.getCameraManager(context);
}
- async addInput(cameraManager: camera.CameraManager, camera: camera.CameraDevice, session: camera.Session) {
+ async addInput(cameraManager: camera.CameraManager, camera: camera.CameraDevice,
+ session: camera.Session): Promise {
let cameraInput: camera.CameraInput | undefined = undefined;
// [Start add_input]
cameraInput = cameraManager.createCameraInput(camera);
@@ -22,11 +38,11 @@ class cameraClass {
}
async addOutput(cameraManager: camera.CameraManager, camera: camera.CameraDevice, session: camera.Session,
- cameraOutputCapability: camera.CameraOutputCapability) {
+ cameraOutputCapability: camera.CameraOutputCapability): Promise {
let previewOutput: camera.CameraOutput | undefined = undefined;
let cameraInput: camera.CameraInput | undefined = undefined;
let profile: camera.Profile = cameraOutputCapability.previewProfiles[0];
- let surfaceId = 'xxx';
+ let surfaceId: string = 'xxx';
// [Start add_output]
previewOutput = cameraManager.createPreviewOutput(profile, surfaceId);
cameraInput = cameraManager.createCameraInput(camera);
@@ -38,11 +54,11 @@ class cameraClass {
}
async addOutput1(cameraManager: camera.CameraManager, camera: camera.CameraDevice, session: camera.Session,
- cameraOutputCapability: camera.CameraOutputCapability) {
+ cameraOutputCapability: camera.CameraOutputCapability): Promise {
let previewOutput: camera.CameraOutput | undefined = undefined;
let cameraInput: camera.CameraInput | undefined = undefined;
let profile: camera.Profile = cameraOutputCapability.previewProfiles[0];
- let surfaceId = 'xxx';
+ let surfaceId: string = 'xxx';
// [Start add_output1]
previewOutput = cameraManager.createPreviewOutput(profile, surfaceId);
cameraInput = cameraManager.createCameraInput(camera);
@@ -53,14 +69,15 @@ class cameraClass {
session.commitConfig();
// [End add_output1]
}
-
}
-let cameraInput:camera.CameraInput;
-let cameraSession:camera.Session;
+let cameraInput: camera.CameraInput;
+let cameraSession: camera.Session;
+
// [Start close_release]
-async function onBackground() {
+async function onBackground(): Promise {
await cameraInput.close();
await cameraSession.release();
}
+
// [End close_release]
\ No newline at end of file
diff --git a/ApiUsingStandards/entry/src/main/ets/pages/playStateCallback.ets b/ApiUsingStandards/entry/src/main/ets/pages/playStateCallback.ets
index 7876e2a1ee16e2516f9019f465fa4964aae6510c..d9621a1659c6227cb8621016b74da65ca02fd1a3 100644
--- a/ApiUsingStandards/entry/src/main/ets/pages/playStateCallback.ets
+++ b/ApiUsingStandards/entry/src/main/ets/pages/playStateCallback.ets
@@ -1,10 +1,24 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 易错API的使用规范
*/
import { BusinessError } from '@kit.BasicServicesKit';
import { avSession } from '@kit.AVSessionKit';
-
-const TAG = 'TEST';
+import { hilog } from '@kit.PerformanceAnalysisKit';
class avSessionClass {
castController!: avSession.AVCastController;
@@ -14,24 +28,23 @@ class avSessionClass {
playStateCallback: (state: avSession.AVPlaybackState) => void = () => {
}
- create(context: Context, tag: string) {
+ create(context: Context, tag: string): void {
avSession.createAVSession(context, tag, "audio").then(async (currentAVSession: avSession.AVSession) => {
this.session = currentAVSession;
- let sessionController = await currentAVSession.getAVCastController();
+ let sessionController: avSession.AVCastController = await currentAVSession.getAVCastController();
this.castController = sessionController;
// [Start play_state_callback]
- let playStateCallback = (state: avSession.AVPlaybackState) => {
-
+ let playStateCallback: (state: avSession.AVPlaybackState) => void = (state: avSession.AVPlaybackState) => {
}
sessionController.on('playbackStateChange', 'all', this.playStateCallback);
sessionController.off('playbackStateChange', this.playStateCallback);
// [End play_state_callback]
}).catch((err: BusinessError) => {
- console.info(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
+ hilog.error(0x0000, 'testTag', `CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
});
}
- prepare() {
+ prepare(): void {
let playItem: avSession.AVQueueItem = {
itemId: 0,
description: {
@@ -51,19 +64,17 @@ class avSessionClass {
// [Start prepare]
// Preparing to play, this will not trigger actual playback, it will load and buffer
this.castController?.prepare(playItem, () => {
- console.info('Preparation done');
// Start playback, truly triggering the playback on the other end. Please call start after Prepare is successful.
this.castController?.start(playItem, () => {
- console.info('Playback started');
+ hilog.info(0x0000, 'testTag', 'Playback started');
});
});
// [End prepare]
}
- onPrepare() {
+ onPrepare(): void {
// [Start on_prepare]
this.session?.on('pause', async () => {
- console.info(TAG, `on pause , do pause task`);
// Execute player pause
// Set the status and progress during pause
this.currentState = {
diff --git a/ApiUsingStandards/entry/src/main/module.json5 b/ApiUsingStandards/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..ad219d733f6afa5ea07f85f580208b08cc3b9041 100644
--- a/ApiUsingStandards/entry/src/main/module.json5
+++ b/ApiUsingStandards/entry/src/main/module.json5
@@ -5,9 +5,7 @@
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
- "phone",
- "tablet",
- "2in1"
+ "phone"
],
"deliveryWithInstall": true,
"installationFree": false,
diff --git a/ApiUsingStandards/entry/src/main/resources/base/element/string.json b/ApiUsingStandards/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..9ce98bfb9ff4c08bd128cf4ca71326277260f640 100644
--- a/ApiUsingStandards/entry/src/main/resources/base/element/string.json
+++ b/ApiUsingStandards/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "ApiUsingStandards"
}
]
}
\ No newline at end of file
diff --git a/ApiUsingStandards/oh-package.json5 b/ApiUsingStandards/oh-package.json5
index 75e4e229db0f608fc3d9471c8819d0e52fb403c5..60ef03cdf1b3f06de3df44880fb15d89e87bc1f5 100644
--- a/ApiUsingStandards/oh-package.json5
+++ b/ApiUsingStandards/oh-package.json5
@@ -4,7 +4,5 @@
"dependencies": {
},
"devDependencies": {
- "@ohos/hypium": "1.0.21",
- "@ohos/hamock": "1.0.0"
}
}
diff --git a/AppAspectProgrammingDesign/README.md b/AppAspectProgrammingDesign/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9e5f3f2614a76367a5c468ee58d0777ecffb6e51
--- /dev/null
+++ b/AppAspectProgrammingDesign/README.md
@@ -0,0 +1,62 @@
+# 应用切面编程设计
+
+### 介绍
+
+本示例是《应用切面编程设计》最佳实践中的代码示例片段。
+
+### 使用说明
+
+进入首面,加载示例逻辑。
+
+### 工程目录
+
+```
+├──entry/src/main/ets
+│ ├──entryability
+│ │ └──EntryAbility.ets // 入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 备份恢复类
+│ └──pages
+│ ├──Index.ets // 示例页面
+│ ├──Index1.ets // 示例页面
+│ ├──Index2.ets // 示例页面
+│ ├──Index3.ets // 示例页面
+│ ├──Index4.ets // 示例页面
+│ ├──Index5.ets // 示例页面
+│ ├──Index6.ets // 示例页面
+│ ├──Index7.ets // 示例页面
+│ ├──Index8.ets // 示例页面
+│ ├──Index9.ets // 示例页面
+│ └──Index10.ets // 示例页面
+└──entry/src/main/resources // 应用资源目录
+```
+
+
+### 具体实现
+
+1. 介绍使用util.Aspect在切面编程中的方法操作,包括使用addBefore、addAfter、replace等。
+
+### 相关权限
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppAspectProgrammingDesign
+git checkout
+```
\ No newline at end of file
diff --git a/AppAspectProgrammingDesign/build-profile.json5 b/AppAspectProgrammingDesign/build-profile.json5
index 03ac3a3ae9dd397844173066e5d5ee21b49455a1..492123c253881f5bbd9bc76553bfb74e842dfb40 100644
--- a/AppAspectProgrammingDesign/build-profile.json5
+++ b/AppAspectProgrammingDesign/build-profile.json5
@@ -5,7 +5,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.4(16)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/AppAspectProgrammingDesign/entry/src/main/module.json5 b/AppAspectProgrammingDesign/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..ad219d733f6afa5ea07f85f580208b08cc3b9041 100644
--- a/AppAspectProgrammingDesign/entry/src/main/module.json5
+++ b/AppAspectProgrammingDesign/entry/src/main/module.json5
@@ -5,9 +5,7 @@
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
- "phone",
- "tablet",
- "2in1"
+ "phone"
],
"deliveryWithInstall": true,
"installationFree": false,
diff --git a/AppAspectProgrammingDesign/entry/src/main/resources/base/element/string.json b/AppAspectProgrammingDesign/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..162ff06f3016378f5490c97cae44fff1199ea814 100644
--- a/AppAspectProgrammingDesign/entry/src/main/resources/base/element/string.json
+++ b/AppAspectProgrammingDesign/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "AppAspectProgrammingDesign"
}
]
}
\ No newline at end of file
diff --git a/AppColdStart/HapAndHarDependHar/AppScope/app.json5 b/AppColdStart/HapAndHarDependHar/AppScope/app.json5
deleted file mode 100644
index 86cc9b85e3d6376e23d256dffccbcdd1d59b4e6e..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/AppScope/app.json5
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "app": {
- "bundleName": "com.example.coldstart",
- "vendor": "example",
- "versionCode": 1000000,
- "versionName": "1.0.0",
- "icon": "$media:app_icon",
- "label": "$string:app_name"
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/AppScope/resources/base/element/string.json b/AppColdStart/HapAndHarDependHar/AppScope/resources/base/element/string.json
deleted file mode 100644
index 7b173461f58b7687bc9b8423941cb83b96c12069..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/AppScope/resources/base/element/string.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "string": [
- {
- "name": "app_name",
- "value": "ColdStart"
- }
- ]
-}
diff --git a/AppColdStart/HapAndHarDependHar/build-profile.json5 b/AppColdStart/HapAndHarDependHar/build-profile.json5
deleted file mode 100644
index 2c03ac0f094d139e2ae61c76ed8a58d81a0d8dcd..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/build-profile.json5
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "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"
- ]
- }
- ]
- },
- {
- "name": "har_library",
- "srcPath": "./library"
- },
- {
- "name": "har_common",
- "srcPath": "./har_common",
- }
- ]
-}
\ No newline at end of file
diff --git a/AppColdStart/HapAndHarDependHar/entry/oh-package.json5 b/AppColdStart/HapAndHarDependHar/entry/oh-package.json5
deleted file mode 100644
index 0fde17fdf11b4e1e509993c6079ea76c582de11a..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/entry/oh-package.json5
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "name": "entry",
- "version": "1.0.0",
- "description": "Please describe the basic information.",
- "main": "",
- "author": "",
- "license": "",
- "dependencies": {
- "har_library": "file:../library",
- "har_common": "file:../har_common"
- }
-}
-
diff --git a/AppColdStart/HapAndHarDependHar/entry/src/main/ets/entryability/EntryAbility.ets b/AppColdStart/HapAndHarDependHar/entry/src/main/ets/entryability/EntryAbility.ets
deleted file mode 100644
index aa7b8e4d139fe8671c5a382b0f8b80e5335c6c52..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/entry/src/main/ets/entryability/EntryAbility.ets
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
-* 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/AppColdStart/HapAndHarDependHar/entry/src/main/ets/pages/Index.ets b/AppColdStart/HapAndHarDependHar/entry/src/main/ets/pages/Index.ets
deleted file mode 100644
index 6413cae7d4867bc242c0a89f91d560ffd08780a2..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/entry/src/main/ets/pages/Index.ets
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
-* 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.
-*/
-
-// DocsCode 1
-// entry/src/main/ets/pages/Index.ets
-import { MainPage } from 'har_library';
-import { funcResult } from 'har_common';
-// DocsCode 1
-
-@Entry
-@Component
-struct Index {
- @State message: string = 'Hello World' + funcResult;
-
- build() {
- Row() {
- // 引用HAR的ArkUI组件
- MainPage()
- }
- .height('100%')
- .width('100%')
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/entry/src/main/module.json5 b/AppColdStart/HapAndHarDependHar/entry/src/main/module.json5
deleted file mode 100644
index 3b355d125c7bb7b28090d101652243c5facbd9ba..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/entry/src/main/module.json5
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "module": {
- "name": "entry",
- "type": "entry",
- "description": "$string:module_desc",
- "mainElement": "EntryAbility",
- "deviceTypes": [
- "phone"
- ],
- "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"
- ]
- }
- ]
- }
- ]
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/har_common/Index.ets b/AppColdStart/HapAndHarDependHar/har_common/Index.ets
deleted file mode 100644
index 557674ecc19a7d3bf7692082e2713e2e6883fcf0..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/har_common/Index.ets
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
-* 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 { funcResult } from './src/main/ets/utils/Utils';
\ No newline at end of file
diff --git a/AppColdStart/HapAndHarDependHar/har_common/obfuscation-rules.txt b/AppColdStart/HapAndHarDependHar/har_common/obfuscation-rules.txt
deleted file mode 100644
index 985b2aeb7658286b17bd26eab8f217c3fe75ea8b..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/har_common/obfuscation-rules.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-# 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/AppColdStart/HapAndHarDependHar/har_common/oh-package.json5 b/AppColdStart/HapAndHarDependHar/har_common/oh-package.json5
deleted file mode 100644
index c9288aefd5fa8348c6967366470b24384f1b52a0..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/har_common/oh-package.json5
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "name": "har_common",
- "version": "1.0.0",
- "description": "Please describe the basic information.",
- "main": "Index.ets",
- "author": "",
- "license": "Apache-2.0",
- "dependencies": {
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/har_common/src/main/ets/components/mainpage/MainPage.ets b/AppColdStart/HapAndHarDependHar/har_common/src/main/ets/components/mainpage/MainPage.ets
deleted file mode 100644
index 8fe31bb9fbcd035b0eddfd578f9b01099a294585..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/har_common/src/main/ets/components/mainpage/MainPage.ets
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
-* 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 MainPage {
- @State message: string = 'Hello World';
-
- build() {
- Row() {
- Column() {
- Text(this.message)
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
- }
- .width('100%')
- }
- .height('100%')
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/har_common/src/main/ets/utils/Utils.ets b/AppColdStart/HapAndHarDependHar/har_common/src/main/ets/utils/Utils.ets
deleted file mode 100644
index e22b4f60a4e92b96f9ecc8d1bb897af3994e8e8b..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/har_common/src/main/ets/utils/Utils.ets
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-* 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.
-*/
-
-const LARGE_NUMBER = 100000000;
-
-function func(): number {
- let count = 0;
- while (count < LARGE_NUMBER) {
- count++;
- }
- return count;
-}
-
-export let funcResult = func();
\ No newline at end of file
diff --git a/AppColdStart/HapAndHarDependHar/har_common/src/main/module.json5 b/AppColdStart/HapAndHarDependHar/har_common/src/main/module.json5
deleted file mode 100644
index b26580cd6a0aa8c7df3ca1fc657f963a1b1b4ef4..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/har_common/src/main/module.json5
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "module": {
- "name": "har_common",
- "type": "har",
- "deviceTypes": [
- "default",
- "tablet",
- "2in1"
- ]
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/library/Index.ets b/AppColdStart/HapAndHarDependHar/library/Index.ets
deleted file mode 100644
index 6f8afc6e836c6ca8e21cba85918b0495bbc721bb..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/Index.ets
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
-* 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.
-*/
-
-// [Start not_recommend_demo]
-export { MainPage } from './src/main/ets/components/mainpage/MainPage'; // 冷启动强相关文件
-export { SubPage } from './src/main/ets/components/mainpage/SubPage'; // 非冷启动强相关文件
-// [End not_recommend_demo]
diff --git a/AppColdStart/HapAndHarDependHar/library/build-profile.json5 b/AppColdStart/HapAndHarDependHar/library/build-profile.json5
deleted file mode 100644
index 697dff23e224373edb713dc2b8a08ed7341d5b4c..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/build-profile.json5
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "apiType": "stageMode",
- "buildOption": {
- },
- "buildOptionSet": [
- {
- "name": "release",
- "arkOptions": {
- "obfuscation": {
- "ruleOptions": {
- "enable": true,
- "files": [
- "./obfuscation-rules.txt"
- ]
- },
- "consumerFiles": [
- "./consumer-rules.txt"
- ]
- }
- },
- },
- ],
- "targets": [
- {
- "name": "default"
- },
- {
- "name": "ohosTest"
- }
- ]
-}
diff --git a/AppColdStart/HapAndHarDependHar/library/consumer-rules.txt b/AppColdStart/HapAndHarDependHar/library/consumer-rules.txt
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/AppColdStart/HapAndHarDependHar/library/hvigorfile.ts b/AppColdStart/HapAndHarDependHar/library/hvigorfile.ts
deleted file mode 100644
index 42187071482d292588ad40babeda74f7b8d97a23..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/hvigorfile.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { harTasks } from '@ohos/hvigor-ohos-plugin';
-
-export default {
- system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
- plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
-}
diff --git a/AppColdStart/HapAndHarDependHar/library/obfuscation-rules.txt b/AppColdStart/HapAndHarDependHar/library/obfuscation-rules.txt
deleted file mode 100644
index 985b2aeb7658286b17bd26eab8f217c3fe75ea8b..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/obfuscation-rules.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-# 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/AppColdStart/HapAndHarDependHar/library/oh-package.json5 b/AppColdStart/HapAndHarDependHar/library/oh-package.json5
deleted file mode 100644
index 3824a8247b7ff16278737ec539e98f7b88a8de55..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/oh-package.json5
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "name": "har_library",
- "version": "1.0.0",
- "description": "Please describe the basic information.",
- "main": "Index.ets",
- "author": "",
- "license": "Apache-2.0",
- "dependencies": {
- "har_common": "file:../har_common"
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/library/src/main/ets/components/mainpage/SubPage.ets b/AppColdStart/HapAndHarDependHar/library/src/main/ets/components/mainpage/SubPage.ets
deleted file mode 100644
index 5d9893548432c492579940234cc5ab33ad7b0a64..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/src/main/ets/components/mainpage/SubPage.ets
+++ /dev/null
@@ -1,14 +0,0 @@
-// [Start not_recommend_demo]
-// library/src/main/ets/components/mainpage/SubPage.ets
-// SubPage中的全局耗时函数
-const LARGE_NUMBER = 10000000;
-function computeTask(): number {
- let count = 0;
- while (count < LARGE_NUMBER) {
- count++;
- }
- return count;
-}
-let count = computeTask();
-// ...
-// [End not_recommend_demo]
\ No newline at end of file
diff --git a/AppColdStart/HapAndHarDependHar/library/src/main/module.json5 b/AppColdStart/HapAndHarDependHar/library/src/main/module.json5
deleted file mode 100644
index 2892dab4fe007cb1eda74bd7189f3a55159038ff..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/src/main/module.json5
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "module": {
- "name": "har_library",
- "type": "har",
- "deviceTypes": [
- "default",
- "tablet",
- "2in1"
- ]
- }
-}
diff --git a/AppColdStart/HapAndHarDependHar/library/src/main/resources/zh_CN/element/string.json b/AppColdStart/HapAndHarDependHar/library/src/main/resources/zh_CN/element/string.json
deleted file mode 100644
index f51a9c8461a55f6312ef950344e3145b7f82d607..0000000000000000000000000000000000000000
--- a/AppColdStart/HapAndHarDependHar/library/src/main/resources/zh_CN/element/string.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "string": [
- {
- "name": "page_show",
- "value": "page from package"
- }
- ]
-}
diff --git a/AppColdStart/README.md b/AppColdStart/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9ccce59eb7f80cd7e52e69c60f5c8721cf3de0b6
--- /dev/null
+++ b/AppColdStart/README.md
@@ -0,0 +1,66 @@
+# 应用冷启动时延优化同源示例代码
+
+### 介绍
+
+本示例代码为最佳实践《应用冷启动时延优化》配套示例代码。
+
+### 使用说明
+
+不涉及
+
+### 工程目录
+
+```
+├──entry/src/main/ets
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 数据备份恢复类
+│ ├──pages
+│ │ ├──ColdStartSlow.ets // 冷启动缓慢示例
+│ │ ├──ColdStartSpeedOptimization.ets // 冷启快速示例
+│ │ ├──ComputeTaskAsync.ets // 异步任务示例
+│ │ ├──ImportMainPage.ets // 页面导入示例
+│ │ ├──ImportMainPageDemo.ets // 减少导入文件示例
+│ │ ├──ImportSubPage.ets // 导入次级页面
+│ │ ├──Index.ets // 应用首页
+│ │ ├──NewIndex.ets // 展示网路图片首页
+│ │ ├──NotRecommendDemo.ets // 不推荐iport示例
+│ │ ├──ReduceImport.ets // 减少import导入示例
+│ │ ├──ScenariosExample.ets // 网络二次刷新示例
+│ │ └──SecondPage.ets // 跳转页面
+│ └──utils
+│ ├──Calculator.ets // 耗时运算函数封装
+│ └──NetRequest.ets // 网络请求工具类
+├──entry/src/main/resources // 应用资源目录
+└──library // 静态资源共享包
+ ├──src/main/ets/components/mainpage
+ │ ├──MainPgge.ets // 静态资源包首页
+ │ └──SubPage.ets // 静态资源包次级页面
+ ├──Index.ets // 入口文件,对外暴露模块方法
+ ├──IndexAppStart.ets // 拆分导出文件MainPage
+ ├──IndexOthers.ets // 拆分导出文件SubPage
+ └──src/main/resources // 应用静态资源目录
+```
+
+### 相关权限
+
+不涉及
+
+### 约束与限制
+
+* 本示例仅支持标准系统上运行,支持设备:华为手机。
+* HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+* DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+* HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppColdStart
+git checkout
+```
\ No newline at end of file
diff --git a/AppColdStart/build-profile.json5 b/AppColdStart/build-profile.json5
index 9e87e7e6f19020fe21192844709f192cec80fd44..ae19bf006133749717f7eb1fc8ae716bca4dbd74 100644
--- a/AppColdStart/build-profile.json5
+++ b/AppColdStart/build-profile.json5
@@ -37,6 +37,10 @@
]
}
]
+ },
+ {
+ "name": "library",
+ "srcPath": "./library",
}
]
}
\ No newline at end of file
diff --git a/AppColdStart/entry/oh-package.json5 b/AppColdStart/entry/oh-package.json5
index 248c3b7541a589682a250f86a6d3ecf7414d2d6a..caa370f06bd44102373d4d518a2c11a0a1f9d8ee 100644
--- a/AppColdStart/entry/oh-package.json5
+++ b/AppColdStart/entry/oh-package.json5
@@ -5,6 +5,8 @@
"main": "",
"author": "",
"license": "",
- "dependencies": {}
+ "dependencies": {
+ "library": "file:../library"
+ }
}
diff --git a/AppColdStart/entry/src/main/ets/entryability/EntryAbility.ets b/AppColdStart/entry/src/main/ets/entryability/EntryAbility.ets
index 90267ef7fae8fb46b5d1a0dd1c7a5a742d083909..78fd17bfd32dfbbed632567bc53a000ef3d7e686 100644
--- a/AppColdStart/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/AppColdStart/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,16 +1,64 @@
-// [Start my_ability_stage]
-// MyAbilityStage.ets
-import { AbilityStage, Want } from '@kit.AbilityKit';
-import { httpRequest } from '../utils/NetRequest';
-export default class MyAbilityStage extends AbilityStage {
- onCreate(): void {
- // Send a network request
- httpRequest();
+/*
+* Copyright (C) 2025 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.
+*/
+
+// [Start entry_ability_demo]
+import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { window } from '@kit.ArkUI'
+
+const LARGE_NUMBER: number = 100000000;
+const DELAYED_TIME: number = 1000;
+
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
+ // Time-consuming operation
+ // this.computeTask();
+ this.computeTaskAsync(); // Asynchronous tasks
+ }
+
+ onWindowStageCreate(windowStage: window.WindowStage): void {
+ windowStage.loadContent('pages/Index', (err, data) => {
+ if (err.code) {
+ console.error('Failed to load the content. Cause: ' + JSON.stringify(err) ?? '');
+ return;
+ }
+ console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data) ?? '');
+ });
+
+ // Time-consuming operation
+ // this.computeTask();
+ // this.computeTaskAsync(); // Asynchronous mission
+ }
+
+ onForeground(): void {
+ // Time-consuming operation
+ // this.computeTask();
+ // this.computeTaskAsync(); // Asynchronous mission
+ }
+
+ private computeTask(): void {
+ let count: number = 0;
+ while (count < LARGE_NUMBER) {
+ count++;
+ }
}
- onAcceptWant(want: Want): string {
- // Triggered in specified mode only.
- return 'MyAbilityStage';
+ private computeTaskAsync(): void {
+ setTimeout(() => { // SetTimeout is used here to achieve asynchronous delayed operation.
+ this.computeTask();
+ }, DELAYED_TIME);
}
}
-// [End my_ability_stage]
\ No newline at end of file
+// [End entry_ability_demo]
\ No newline at end of file
diff --git a/AppColdStart/entry/src/main/ets/entryability/EntryAbilityDemo.ets b/AppColdStart/entry/src/main/ets/entryability/EntryAbilityDemo.ets
deleted file mode 100644
index f0dc3f343819e7ed2e9784f219f2c2f397ee7c4f..0000000000000000000000000000000000000000
--- a/AppColdStart/entry/src/main/ets/entryability/EntryAbilityDemo.ets
+++ /dev/null
@@ -1,49 +0,0 @@
-// [Start entry_ability_demo]
-import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
-import { window } from '@kit.ArkUI'
-
-const LARGE_NUMBER = 100000000;
-const DELAYED_TIME = 1000;
-
-
-export default class EntryAbility extends UIAbility {
- onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- // Time-consuming operation
- // this.computeTask();
- this.computeTaskAsync(); // Asynchronous tasks
- }
-
- onWindowStageCreate(windowStage: window.WindowStage): void {
- windowStage.loadContent('pages/Index', (err, data) => {
- if (err.code) {
- console.error('Failed to load the content. Cause: ' + JSON.stringify(err) ?? '');
- return;
- }
- console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data) ?? '');
- });
-
- // Time-consuming operation
- // this.computeTask();
- // this.computeTaskAsync(); // Asynchronous mission
- }
-
- onForeground(): void {
- // Time-consuming operation
- // this.computeTask();
- // this.computeTaskAsync(); // Asynchronous mission
- }
-
- private computeTask(): void {
- let count = 0;
- while (count < LARGE_NUMBER) {
- count++;
- }
- }
-
- private computeTaskAsync(): void {
- setTimeout(() => { // SetTimeout is used here to achieve asynchronous delayed operation.
- this.computeTask();
- }, DELAYED_TIME);
- }
-}
-// [End entry_ability_demo]
\ No newline at end of file
diff --git a/AppColdStart/entry/src/main/ets/entryability/MyAbilityStage.ets b/AppColdStart/entry/src/main/ets/entryability/MyAbilityStage.ets
index da3225812a26ffd802864288847604a10355df15..49c5e9274c0c4cbf8c74d83b289fdf85fad6270e 100644
--- a/AppColdStart/entry/src/main/ets/entryability/MyAbilityStage.ets
+++ b/AppColdStart/entry/src/main/ets/entryability/MyAbilityStage.ets
@@ -1,32 +1,31 @@
-// [Start reduce_ability_stage_time]
-import { AbilityStage, Want } from '@kit.AbilityKit';
-
-const LARGE_NUMBER = 100000000;
-const DELAYED_TIME = 1000;
+/*
+* Copyright (C) 2025 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.
+*/
+// [Start my_ability_stage]
+// MyAbilityStage.ets
+import { AbilityStage, Want } from '@kit.AbilityKit';
+import { httpRequest } from '../utils/NetRequest';
export default class MyAbilityStage extends AbilityStage {
onCreate(): void {
- // Time-consuming operation
- // this.computeTask();
- this.computeTaskAsync(); // Asynchronous mission
+ // Send a network request
+ httpRequest();
}
onAcceptWant(want: Want): string {
- // Trigger in specified mode only
+ // Triggered in specified mode only.
return 'MyAbilityStage';
}
-
- private computeTask(): void {
- let count = 0;
- while (count < LARGE_NUMBER) {
- count++;
- }
- }
-
- private computeTaskAsync(): void {
- setTimeout(() => { // SetTimeout is used here to achieve asynchronous delayed operation.
- this.computeTask();
- }, DELAYED_TIME);
- }
}
-// [End reduce_ability_stage_time]
\ No newline at end of file
+// [End my_ability_stage]
\ No newline at end of file
diff --git a/AppColdStart/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/AppColdStart/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
index 8e4de99282050bad799ac892eb85ac5449364a51..7eb1afb81759bc5d59117077cb08b938ea66d402 100644
--- a/AppColdStart/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
+++ b/AppColdStart/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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';
diff --git a/AppColdStart/entry/src/main/ets/pages/ColdStartSlow.ets b/AppColdStart/entry/src/main/ets/pages/ColdStartSlow.ets
index fd03ac97033a5cce90ea14d9c6daf2532259a6be..4c4bfbff3a4671e7c2e5a6cb6e91b5227f67bf54 100644
--- a/AppColdStart/entry/src/main/ets/pages/ColdStartSlow.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ColdStartSlow.ets
@@ -1,6 +1,20 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start cold_start_slow]
-const LARGE_NUMBER = 200000000;
-const DELAYED_TIME = 1000;
+const LARGE_NUMBER: number = 200000000;
@Entry
@Component
@@ -13,7 +27,7 @@ struct Index {
}
computeTask(): void {
- let count = 0;
+ let count: number = 0;
while (count < LARGE_NUMBER) {
count++;
}
diff --git a/AppColdStart/entry/src/main/ets/pages/ColdStartSpeedOptimization.ets b/AppColdStart/entry/src/main/ets/pages/ColdStartSpeedOptimization.ets
index 6efdcf6dd4233513daed9a13bf4abf53e90fe842..31fa4fefa9abb679057c8f5bb2e42464a1baf8f0 100644
--- a/AppColdStart/entry/src/main/ets/pages/ColdStartSpeedOptimization.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ColdStartSpeedOptimization.ets
@@ -1,6 +1,21 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start cold_start_speed_optimization]
-const LARGE_NUMBER = 100000000;
-const DELAYED_TIME = 1000;
+const LARGE_NUMBER: number = 100000000;
+const DELAYED_TIME: number = 1000;
@Entry
@Component
@@ -27,7 +42,7 @@ struct Index {
// [EndExclude cold_start_speed_optimization]
computeTask(): void {
- let count = 0;
+ let count: number = 0;
while (count < LARGE_NUMBER) {
count++;
}
diff --git a/AppColdStart/entry/src/main/ets/pages/ComputeTaskAsync.ets b/AppColdStart/entry/src/main/ets/pages/ComputeTaskAsync.ets
index 53d1a1a4f24078e2406316888d23104d0edaaafe..e8e5d6ff44973b249a2cc9f64e1dc408165d4c6d 100644
--- a/AppColdStart/entry/src/main/ets/pages/ComputeTaskAsync.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ComputeTaskAsync.ets
@@ -1,6 +1,21 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start compute_task_async]
-const LARGE_NUMBER = 100000000;
-const DELAYED_TIME = 1000;
+const LARGE_NUMBER: number = 100000000;
+const DELAYED_TIME: number = 1000;
@Entry
@Component
@@ -26,7 +41,7 @@ struct Index {
}
private computeTask(): void {
- let count = 0;
+ let count: number = 0;
while (count < LARGE_NUMBER) {
count++;
}
diff --git a/AppColdStart/entry/src/main/ets/pages/ImportMainPage.ets b/AppColdStart/entry/src/main/ets/pages/ImportMainPage.ets
index 581fc19ec1e16d748f5a674c9164b669664856f2..07ce5a68692bd50ef90f1e4aa1c8a8b11740f38e 100644
--- a/AppColdStart/entry/src/main/ets/pages/ImportMainPage.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ImportMainPage.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start import_main_page]
// Index.ets
import { MainPage } from 'library/IndexAppStart';
diff --git a/AppColdStart/entry/src/main/ets/pages/ImportMainPageDemo.ets b/AppColdStart/entry/src/main/ets/pages/ImportMainPageDemo.ets
index b348b090bde12e91d74342d1f8430bcff0465ebf..eb5f107823f86cf37f176f626346b4069c9c26c9 100644
--- a/AppColdStart/entry/src/main/ets/pages/ImportMainPageDemo.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ImportMainPageDemo.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start import_main_page_demo]
// Index.ets
import { MainPage } from 'library/src/main/ets/components/mainpage/MainPage';
diff --git a/AppColdStart/entry/src/main/ets/pages/ImportOthers.ets b/AppColdStart/entry/src/main/ets/pages/ImportOthers.ets
deleted file mode 100644
index c867ddd5d95672a010cbb35a16080c761cb13457..0000000000000000000000000000000000000000
--- a/AppColdStart/entry/src/main/ets/pages/ImportOthers.ets
+++ /dev/null
@@ -1,22 +0,0 @@
-// [Start import_others]
-import { add } from 'hsp1';
-import { add2 } from 'hsp2';
-import { add3 } from 'hsp3';
-import { add4 } from 'hsp4';
-import { add5 } from 'hsp5';
-import { add6 } from 'hsp6';
-import { add7 } from 'hsp7';
-import { add8 } from 'hsp8';
-import { add9 } from 'hsp9';
-import { add10 } from 'hsp10';
-import { add11 } from 'hsp11';
-import { add12 } from 'hsp12';
-import { add13 } from 'hsp13';
-import { add14 } from 'hsp14';
-import { add15 } from 'hsp15';
-import { add16 } from 'hsp16';
-import { add17 } from 'hsp17';
-import { add18 } from 'hsp18';
-import { add19 } from 'hsp19';
-import { add20 } from 'hsp20'
-// [End import_others]
\ No newline at end of file
diff --git a/AppColdStart/entry/src/main/ets/pages/ImportSubPage.ets b/AppColdStart/entry/src/main/ets/pages/ImportSubPage.ets
index 61c1be1d1ecb55d7dc957d1bc6254cbbd4ae3996..13806a93588479c80de14babfd365df82bac6dcf 100644
--- a/AppColdStart/entry/src/main/ets/pages/ImportSubPage.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ImportSubPage.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start import_sub_page]
// SecondPage.ets
import { SubPage } from 'library/IndexOthers';
diff --git a/AppColdStart/entry/src/main/ets/pages/Index.ets b/AppColdStart/entry/src/main/ets/pages/Index.ets
index 13b64258e8c48209fdb0ced0bc1f6bf10f9acf7d..aea2e929eba5f67b343912779488de16f3607896 100644
--- a/AppColdStart/entry/src/main/ets/pages/Index.ets
+++ b/AppColdStart/entry/src/main/ets/pages/Index.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start request_in_home]
// entry/src/main/ets/pages/Index.ets
import { httpRequest } from '../utils/NetRequest';
@@ -10,15 +25,22 @@ PersistentStorage.persistProp('netData', undefined);
@Entry
@Component
struct Index {
- @State message: string = 'Hello World' + number; // In order to reflect the performance benefits, refer to the execution result number of the time-consuming function.
+ // In order to reflect the performance benefits, refer to the execution result number of the time-consuming function.
+ @State message: string = 'Hello World' + number;
@StorageLink('netData') netData: PixelMap | undefined = undefined;
- build(){
- Row(){
+
+ build() {
+ Column() {
+ Text(this.message)
+ .fontSize(32)
Image(this.netData)
.objectFit(ImageFit.Contain)
.width('50%')
.height('50%')
}
+ .width('100%')
+ .height('100%')
+ .justifyContent(FlexAlign.Center)
.onAppear(() => {
// Send a network request
httpRequest();
diff --git a/AppColdStart/entry/src/main/ets/pages/NewIndex.ets b/AppColdStart/entry/src/main/ets/pages/NewIndex.ets
index cd0605ce633c12bf9e38c17ac51ab5f146c7adb6..dc90821aa2a48f02ad8bc30cb82eb4a7a00c021c 100644
--- a/AppColdStart/entry/src/main/ets/pages/NewIndex.ets
+++ b/AppColdStart/entry/src/main/ets/pages/NewIndex.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start new_index]
// Index.ets
import { number } from '../utils/Calculator';
diff --git a/AppColdStart/entry/src/main/ets/pages/NotRecommendDemo.ets b/AppColdStart/entry/src/main/ets/pages/NotRecommendDemo.ets
index 87ea199a85fc04ffa253b8543e63c0dad76dbdf2..c1ad2bab5315bfa4236e97a0957a65de5909ca49 100644
--- a/AppColdStart/entry/src/main/ets/pages/NotRecommendDemo.ets
+++ b/AppColdStart/entry/src/main/ets/pages/NotRecommendDemo.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start not_recommend_demo]
// entry/src/main/ets/pages/Index.ets
import { MainPage } from 'library/Index'; // Unrecommended usage: Direct import of subPage.ets files related to cold start non-strong
diff --git a/AppColdStart/entry/src/main/ets/pages/ReduceImport.ets b/AppColdStart/entry/src/main/ets/pages/ReduceImport.ets
index 3bad56357edfdd48692665631668cba2c91942cd..b241a34b36b59977bd76b9d7ad2ac0174ef06973 100644
--- a/AppColdStart/entry/src/main/ets/pages/ReduceImport.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ReduceImport.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start reduce_import]
// Optimize modules that reduce import
/*import { ConfigurationConstant, contextConstant, wantConstant } from '@kit.AbilityKit';
@@ -8,9 +23,7 @@ import { atomicService } from '@kit.ScenarioFusionKit';
import { sim } from '@kit.TelephonyKit';*/
-import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
-import { hilog } from '@kit.PerformanceAnalysisKit';
-import { window } from '@kit.ArkUI';
+import { UIAbility } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
diff --git a/AppColdStart/entry/src/main/ets/pages/ScenariosExample.ets b/AppColdStart/entry/src/main/ets/pages/ScenariosExample.ets
index 7eb5bc424885de0edb7d8e3010e55f306ca2acb6..b086f51ab5353a9d49ddf31400f637b0aa284afc 100644
--- a/AppColdStart/entry/src/main/ets/pages/ScenariosExample.ets
+++ b/AppColdStart/entry/src/main/ets/pages/ScenariosExample.ets
@@ -1,10 +1,25 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start scenarios_example]
// Index.ets
import { http } from '@kit.NetworkKit';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
-import { fileIo as fs } from '@kit.CoreFileKit';
+import { fileIo, fileIo as fs } from '@kit.CoreFileKit';
const PERMISSIONS: Array = [
'ohos.permission.READ_MEDIA',
@@ -22,7 +37,7 @@ struct Index {
/**
* Download picture resources from the Internet through the http request method
*/
- async getPicture() {
+ async getPicture(): Promise {
http.createHttp()
.request('https://www.example1.com/POST?e=f&g=h',
(error: BusinessError, data: http.HttpResponse) => {
@@ -42,7 +57,7 @@ struct Index {
* Use createPixelMap to replace pictures of ArrayBuffer type with PixelMap type
* @param data:Resources obtained from the network
*/
- transcodePixelMap(data: http.HttpResponse) {
+ transcodePixelMap(data: http.HttpResponse): void {
if (http.ResponseCode.OK === data.responseCode) {
const imageData: ArrayBuffer = data.result as ArrayBuffer;
// Create a picture source instance through ArrayBuffer
@@ -67,19 +82,18 @@ struct Index {
}
}
-
- /**
- * 保存ArrayBuffer到沙箱路径
- * @param buffer:图片ArrayBuffer
- * @returns
- */
async saveImage(buffer: ArrayBuffer | string): Promise {
- const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
- const filePath: string = context.cacheDir + '/test.jpg';
- AppStorage.set('net_picture', filePath);
- const file = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
- await fs.write(file.fd, buffer);
- await fs.close(file.fd);
+ try {
+ const context:common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
+ const filePath: string = context.cacheDir + '/test.jpg';
+ AppStorage.set('net_picture', filePath);
+ const file: fileIo.File = await fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
+ await fs.write(file.fd, buffer);
+ await fs.close(file.fd);
+ } catch (err) {
+ let error = err as BusinessError;
+ console.error(`onAddForm err, code: ${error.code}, mesage: ${error.message}`);
+ }
}
@@ -100,10 +114,9 @@ struct Index {
}
}
-
async aboutToAppear(): Promise {
- const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
- const atManager = abilityAccessCtrl.createAtManager();
+ const context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
+ const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
await atManager.requestPermissionsFromUser(context, PERMISSIONS);
this.useCachePic(); // Get data from local storage
this.getPicture(); // Obtain data from the network side
diff --git a/AppColdStart/entry/src/main/ets/pages/SecondPage.ets b/AppColdStart/entry/src/main/ets/pages/SecondPage.ets
index 34891c80268b250c5cc7396ddce787b4859c427d..889d45ffec4014698ba9f6472b4bf414139350b5 100644
--- a/AppColdStart/entry/src/main/ets/pages/SecondPage.ets
+++ b/AppColdStart/entry/src/main/ets/pages/SecondPage.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start not_recommend_demo]
// entry/src/main/ets/pages/SecondPage.ets
import { SubPage } from 'library/Index';
diff --git a/AppColdStart/entry/src/main/ets/utils/Calculator.ets b/AppColdStart/entry/src/main/ets/utils/Calculator.ets
index d41b4edcf2722dbfbc5647edfbc2da8d54447c74..4a6a84ff999d2fea2450142bef336aa3790fd4c8 100644
--- a/AppColdStart/entry/src/main/ets/utils/Calculator.ets
+++ b/AppColdStart/entry/src/main/ets/utils/Calculator.ets
@@ -1,8 +1,9 @@
// [Start request_in_home]
// Calculator.ets
-const LARGE_NUMBER = 100000000;
+const LARGE_NUMBER: number = 100000000;
+
function computeTask(): number {
- let count = 0;
+ let count: number = 0;
while (count < LARGE_NUMBER) {
count++;
}
diff --git a/AppColdStart/entry/src/main/ets/utils/NetRequest.ets b/AppColdStart/entry/src/main/ets/utils/NetRequest.ets
index 75a6da13490c36bce8dda37bb2b91a1d72eaa9d1..e5cabcf5e3b3d881f1a23bc95c7a4306b7b58deb 100644
--- a/AppColdStart/entry/src/main/ets/utils/NetRequest.ets
+++ b/AppColdStart/entry/src/main/ets/utils/NetRequest.ets
@@ -6,10 +6,10 @@ import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
// Download picture resources from the Internet through the http request method
-export function httpRequest() {
+export function httpRequest(): void {
hiTraceMeter.startTrace('Http Request', 1);
http.createHttp()
- // The actual development needs to "https://www.example1.com/POST?e=f&g=h"replaced with the real website address to visit
+ // The actual development needs to "https://www.example1.com/POST?e=f&g=h"replaced with the real website address to visit
.request('https://www.example1.com/POST?e=f&g=h',
(error: BusinessError, data: http.HttpResponse) => {
if (error) {
@@ -23,7 +23,7 @@ export function httpRequest() {
}
// Use createPixelMap to replace pictures of ArrayBuffer types with PixelMap types.
-function transcodePixelMap(data: http.HttpResponse) {
+function transcodePixelMap(data: http.HttpResponse): void {
if (http.ResponseCode.OK === data.responseCode) {
const imageData: ArrayBuffer = data.result as ArrayBuffer;
// Create a picture source instance through ArrayBuffer
diff --git a/AppColdStart/entry/src/main/resources/base/element/float.json b/AppColdStart/entry/src/main/resources/base/element/float.json
index 33ea22304f9b1485b5f22d811023701b5d4e35b6..a0a93dd91fd48f08f3a9532c76e9b26e68d4c034 100644
--- a/AppColdStart/entry/src/main/resources/base/element/float.json
+++ b/AppColdStart/entry/src/main/resources/base/element/float.json
@@ -5,4 +5,4 @@
"value": "50fp"
}
]
-}
+}
\ No newline at end of file
diff --git a/AppColdStart/entry/src/main/resources/base/element/string.json b/AppColdStart/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..0549cb3e0bf016383038ffc1c975f9fcb117269b 100644
--- a/AppColdStart/entry/src/main/resources/base/element/string.json
+++ b/AppColdStart/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "AppColdStart"
}
]
}
\ No newline at end of file
diff --git a/AppColdStart/entry/src/main/resources/base/profile/main_pages.json b/AppColdStart/entry/src/main/resources/base/profile/main_pages.json
index 1898d94f58d6128ab712be2c68acc7c98e9ab9ce..55c3f007f87b7ce5206d325f968cc56f2f79441f 100644
--- a/AppColdStart/entry/src/main/resources/base/profile/main_pages.json
+++ b/AppColdStart/entry/src/main/resources/base/profile/main_pages.json
@@ -2,4 +2,4 @@
"src": [
"pages/Index"
]
-}
+}
\ No newline at end of file
diff --git a/AppColdStart/entry/src/ohosTest/module.json5 b/AppColdStart/entry/src/ohosTest/module.json5
deleted file mode 100644
index 509a3a28a3e6be8d7f98cc563fa8195657d77d1d..0000000000000000000000000000000000000000
--- a/AppColdStart/entry/src/ohosTest/module.json5
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "module": {
- "name": "entry_test",
- "type": "feature",
- "deviceTypes": [
- "phone"
- ],
- "deliveryWithInstall": true,
- "installationFree": false
- }
-}
diff --git a/AppColdStart/library/Index.ets b/AppColdStart/library/Index.ets
new file mode 100644
index 0000000000000000000000000000000000000000..b9d2467c5092233d4a4b74072162cf6169cff33a
--- /dev/null
+++ b/AppColdStart/library/Index.ets
@@ -0,0 +1,19 @@
+/*
+* 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.
+*/
+
+// [Start not_recommend_demo]
+export { MainPage } from './src/main/ets/components/mainpage/MainPage'; // Cold start strong related files
+export { SubPage } from './src/main/ets/components/mainpage/SubPage'; // Non-cold start strong related files
+// [End not_recommend_demo]
diff --git a/AppColdStart/HapAndHarDependHar/library/IndexAppStart.ets b/AppColdStart/library/IndexAppStart.ets
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/library/IndexAppStart.ets
rename to AppColdStart/library/IndexAppStart.ets
diff --git a/AppColdStart/HapAndHarDependHar/library/IndexOthers.ets b/AppColdStart/library/IndexOthers.ets
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/library/IndexOthers.ets
rename to AppColdStart/library/IndexOthers.ets
diff --git a/AppColdStart/HapAndHarDependHar/har_common/build-profile.json5 b/AppColdStart/library/build-profile.json5
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/har_common/build-profile.json5
rename to AppColdStart/library/build-profile.json5
diff --git a/AppColdStart/HapAndHarDependHar/har_common/consumer-rules.txt b/AppColdStart/library/consumer-rules.txt
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/har_common/consumer-rules.txt
rename to AppColdStart/library/consumer-rules.txt
diff --git a/AppColdStart/HapAndHarDependHar/har_common/hvigorfile.ts b/AppColdStart/library/hvigorfile.ts
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/har_common/hvigorfile.ts
rename to AppColdStart/library/hvigorfile.ts
diff --git a/AppColdStart/HapAndHarDependHar/entry/obfuscation-rules.txt b/AppColdStart/library/obfuscation-rules.txt
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/obfuscation-rules.txt
rename to AppColdStart/library/obfuscation-rules.txt
diff --git a/AppColdStart/library/oh-package.json5 b/AppColdStart/library/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..0651f82cdedfec5fbf293e03a9158fb88cfc40a6
--- /dev/null
+++ b/AppColdStart/library/oh-package.json5
@@ -0,0 +1,10 @@
+{
+ "name": "library",
+ "version": "1.0.0",
+ "description": "Please describe the basic information.",
+ "main": "Index.ets",
+ "author": "",
+ "license": "Apache-2.0",
+ "dependencies": {
+ }
+}
diff --git a/AppColdStart/HapAndHarDependHar/library/src/main/ets/components/mainpage/MainPage.ets b/AppColdStart/library/src/main/ets/components/mainpage/MainPage.ets
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/library/src/main/ets/components/mainpage/MainPage.ets
rename to AppColdStart/library/src/main/ets/components/mainpage/MainPage.ets
diff --git a/AppColdStart/library/src/main/ets/components/mainpage/SubPage.ets b/AppColdStart/library/src/main/ets/components/mainpage/SubPage.ets
new file mode 100644
index 0000000000000000000000000000000000000000..437d9c689926a8268a21907ed2284aac0d4281b7
--- /dev/null
+++ b/AppColdStart/library/src/main/ets/components/mainpage/SubPage.ets
@@ -0,0 +1,31 @@
+// [Start not_recommend_demo]
+// library/src/main/ets/components/mainpage/SubPage.ets
+// Global time-consuming functions in SubPage
+const LARGE_NUMBER: number = 10000000;
+
+function computeTask(): number {
+ let count: number = 0;
+ while (count < LARGE_NUMBER) {
+ count++;
+ }
+ return count;
+}
+
+computeTask();
+// ...
+// [End not_recommend_demo]
+@Component
+export struct SubPage {
+ @Consume pathStack: NavPathStack;
+ @State message: string = 'HAR SubPage';
+
+ build() {
+ Row() {
+ Text(this.message)
+ .fontSize(32)
+ .fontWeight(FontWeight.Bold)
+ }.onClick(() => {
+ this.pathStack.pushPath({ name: 'SecondPage' });
+ })
+ }
+}
\ No newline at end of file
diff --git a/AppColdStart/library/src/main/module.json5 b/AppColdStart/library/src/main/module.json5
new file mode 100644
index 0000000000000000000000000000000000000000..dd30f8e0de7154e00da5009b23df656940652a64
--- /dev/null
+++ b/AppColdStart/library/src/main/module.json5
@@ -0,0 +1,11 @@
+{
+ "module": {
+ "name": "library",
+ "type": "har",
+ "deviceTypes": [
+ "default",
+ "tablet",
+ "2in1"
+ ]
+ }
+}
diff --git a/AppColdStart/HapAndHarDependHar/har_common/src/main/resources/base/element/string.json b/AppColdStart/library/src/main/resources/base/element/string.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/har_common/src/main/resources/base/element/string.json
rename to AppColdStart/library/src/main/resources/base/element/string.json
diff --git a/AppColdStart/HapAndHarDependHar/library/src/main/resources/base/element/string.json b/AppColdStart/library/src/main/resources/en_US/element/string.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/library/src/main/resources/base/element/string.json
rename to AppColdStart/library/src/main/resources/en_US/element/string.json
diff --git a/AppColdStart/HapAndHarDependHar/library/src/main/resources/en_US/element/string.json b/AppColdStart/library/src/main/resources/zh_CN/element/string.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/library/src/main/resources/en_US/element/string.json
rename to AppColdStart/library/src/main/resources/zh_CN/element/string.json
diff --git a/AppColdStart/oh-package-lock.json5 b/AppColdStart/oh-package-lock.json5
deleted file mode 100644
index 7fcf818273347b97063c0c0a151bb14770ca1c79..0000000000000000000000000000000000000000
--- a/AppColdStart/oh-package-lock.json5
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "meta": {
- "stableOrder": true
- },
- "lockfileVersion": 3,
- "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
- "specifiers": {
- "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0",
- "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21"
- },
- "packages": {
- "@ohos/hamock@1.0.0": {
- "name": "@ohos/hamock",
- "version": "1.0.0",
- "integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==",
- "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hamock/-/hamock-1.0.0.har",
- "registryType": "ohpm"
- },
- "@ohos/hypium@1.0.21": {
- "name": "@ohos/hypium",
- "version": "1.0.21",
- "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==",
- "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.21.har",
- "registryType": "ohpm"
- }
- }
-}
\ No newline at end of file
diff --git a/AppColdStart/oh-package.json5 b/AppColdStart/oh-package.json5
index a8aff0c5aff22d78aa26fd19c3861f4320e951ff..2d9c74ff34f1383ec920815a40399dd0fe46a6c5 100644
--- a/AppColdStart/oh-package.json5
+++ b/AppColdStart/oh-package.json5
@@ -4,7 +4,5 @@
"dependencies": {
},
"devDependencies": {
- "@ohos/hypium": "1.0.21",
- "@ohos/hamock": "1.0.0"
}
}
diff --git a/AppDataSecurity/README.md b/AppDataSecurity/README.md
index 08b246b6a4c69cd627abdcec9ee9092e8735af2b..7cb0831413ddac5cfa4fd99b1b4e1641632fd496 100644
--- a/AppDataSecurity/README.md
+++ b/AppDataSecurity/README.md
@@ -3,6 +3,17 @@
### 简介
本示例实现了获取文件路径以及通用密钥库加解密算法。
+### 效果图
+| 首页 |
+|----------------------------------------------------|
+| |
+
+### 使用说明
+1. 点击获取通用文件路径获取el2文件路径。
+2. 点击获取EL1文件路径获取el1文件路径。
+3. 点击加密会执行加密算法,可通过日志查看加密结果。
+4. 点击解密对加密的数据进行解密,可通过日志查看解密结果。
+
### 工程目录
```
├──entry/src/main/ets/
@@ -27,8 +38,19 @@
1. 本示例仅支持标准系统上运行,支持设备:华为手机。
-2. HarmonyOS系统:HarmonyOS NEXT Release及以上。
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
-3. DevEco Studio版本:DevEco Studio NEXT Release及以上。
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
-4. HarmonyOS SDK版本:HarmonyOS NEXT Release SDK及以上。
\ No newline at end of file
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppDataSecurity
+git checkout
+```
\ No newline at end of file
diff --git a/AppDataSecurity/README_EN.md b/AppDataSecurity/README_EN.md
index 65d2d7ccdd092b4f11acbc14d12c510339068001..d4e1e5d587088ed9e2093093b9c9f5eb6553e3d6 100644
--- a/AppDataSecurity/README_EN.md
+++ b/AppDataSecurity/README_EN.md
@@ -3,6 +3,11 @@
### Overview
This sample implements file paths and HUKS encryption/decryption algorithm.
+### Effect
+| Home Page |
+|-------------------------------------------------------|
+| |
+
### Project Directory
```
├──entry/src/main/ets/
@@ -32,3 +37,14 @@ N/A
3. The DevEco Studio version must be DevEco Studio NEXT Release or later.
4. The HarmonyOS SDK version must be HarmonyOS NEXT Release SDK or later.
+
+### Download
+
+To download this project separately, execute the following command:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppDataSecurity
+git checkout
+```
diff --git a/AppDataSecurity/build-profile.json5 b/AppDataSecurity/build-profile.json5
index 1e69556b3411622cb2e87a87389653bb34f1b148..9e87e7e6f19020fe21192844709f192cec80fd44 100644
--- a/AppDataSecurity/build-profile.json5
+++ b/AppDataSecurity/build-profile.json5
@@ -5,7 +5,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "targetSdkVersion": "5.0.5(17)",
+ "compatibleSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/AppDataSecurity/entry/src/main/ets/pages/Index.ets b/AppDataSecurity/entry/src/main/ets/pages/Index.ets
index 3574ed8a8f6ac64de5ecd52c7ccca64bc73814fa..2baf55383cc4e367ea0f6de1dd430508bdbce339 100644
--- a/AppDataSecurity/entry/src/main/ets/pages/Index.ets
+++ b/AppDataSecurity/entry/src/main/ets/pages/Index.ets
@@ -65,7 +65,7 @@ struct Index {
}
// [Start get_el2_path]
- getEl2Path() {
+ getEl2Path(): void {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
context.area = contextConstant.AreaMode.EL2;
let filePath = context.filesDir + '/health_data.txt';
@@ -74,7 +74,7 @@ struct Index {
// [End get_el2_path]
// [Start get_el1_path]
- getEl1Path() {
+ getEl1Path(): void {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
context.area = contextConstant.AreaMode.EL1;
let filePath = context.filesDir + '/health_data.txt';
@@ -83,51 +83,60 @@ struct Index {
// [End get_el1_path]
}
-let aesKeyAlias = 'test_aesKeyAlias';
+let aesKeyAlias: string = 'test_aesKeyAlias';
let handle: number;
-let plainText = '123456';
-let IV = '001122334455';
+let plainText: string = '123456';
+let IV: string = '001122334455';
let cipherData: Uint8Array;
// [Start write_file]
-function writeFile(filePath: string, data: string) {
- let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
- let writeLen = fileIo.writeSync(file.fd, data);
- hilog.info(0x0000, 'AppDataSecurity', 'The length of str is: ' + writeLen);
- fileIo.closeSync(file);
+function writeFile(filePath: string, data: string): void {
+ try {
+ let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
+ let writeLen = fileIo.writeSync(file.fd, data);
+ hilog.info(0x0000, 'AppDataSecurity', 'The length of str is: ' + writeLen);
+ fileIo.closeSync(file);
+ } catch (error) {
+ hilog.error(0x0000, 'AppDataSecurity', `writeFile error ${JSON.stringify(error)}`);
+ }
}
function readFile(filePath: string): string {
- let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
- let arrayBuffer = new ArrayBuffer(1024);
+ try {
+ let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
+ let arrayBuffer = new ArrayBuffer(1024);
- class Option {
- public offset: number = 0;
- public length: number = 0;
- }
+ class Option {
+ public offset: number = 0;
+ public length: number = 0;
+ }
- let option = new Option();
- option.length = arrayBuffer.byteLength;
- let readLen = fileIo.readSync(file.fd, arrayBuffer, option);
- let buf = buffer.from(arrayBuffer, 0, readLen);
- hilog.info(0x0000, 'AppDataSecurity', `The length of of file: ${readLen}`);
- fileIo.closeSync(file);
- return buf.toString();
+ let option = new Option();
+ option.length = arrayBuffer.byteLength;
+ let readLen = fileIo.readSync(file.fd, arrayBuffer, option);
+ let buf = buffer.from(arrayBuffer, 0, readLen);
+ hilog.info(0x0000, 'AppDataSecurity', `The length of of file: ${readLen}`);
+ fileIo.closeSync(file);
+ return buf.toString();
+ } catch (error) {
+ hilog.error(0x0000, 'AppDataSecurity', `readFile error ${JSON.stringify(error)}`);
+ }
+ return '';
}
// [End write_file]
-function StringToUint8Array(str: string) {
+function StringToUint8Array(str: string): Uint8Array {
let textEncoder = util.TextEncoder.create('utf-8');
return textEncoder.encodeInto(str);
}
-function Uint8ArrayToString(fileData: Uint8Array) {
+function Uint8ArrayToString(fileData: Uint8Array): string {
let textDecoder = util.TextDecoder.create('utf-8');
return textDecoder.decodeToString(fileData);
}
// [Start get_aes_generate_properties]
-function GetAesGenerateProperties() {
+function GetAesGenerateProperties(): Array {
let properties: Array = [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
@@ -144,7 +153,7 @@ function GetAesGenerateProperties() {
// [End get_aes_generate_properties]
// [Start get_aes_encrypt_properties]
-function GetAesEncryptProperties() {
+function GetAesEncryptProperties(): Array {
let properties: Array = [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
@@ -169,7 +178,7 @@ function GetAesEncryptProperties() {
// [End get_aes_encrypt_properties]
// [Start get_aes_decrypt_properties]
-function GetAesDecryptProperties() {
+function GetAesDecryptProperties(): Array {
let properties: Array = [{
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_AES
@@ -194,7 +203,7 @@ function GetAesDecryptProperties() {
// [End get_aes_decrypt_properties]
// [Start generate_aes_key]
-async function GenerateAesKey() {
+async function GenerateAesKey(): Promise {
let genProperties = GetAesGenerateProperties();
let options: huks.HuksOptions = {
properties: genProperties
@@ -210,7 +219,7 @@ async function GenerateAesKey() {
// [End generate_aes_key]
// [Start encrypt_data]
-async function EncryptData() {
+async function EncryptData(): Promise {
let encryptProperties = GetAesEncryptProperties();
let options: huks.HuksOptions = {
properties: encryptProperties,
@@ -234,7 +243,7 @@ async function EncryptData() {
})
}
-async function DecryptData() {
+async function DecryptData(): Promise {
let decryptOptions = GetAesDecryptProperties()
let options: huks.HuksOptions = {
properties: decryptOptions,
@@ -258,7 +267,7 @@ async function DecryptData() {
}
// [End encrypt_data]
-async function DeleteKey() {
+async function DeleteKey(): Promise {
let emptyOptions: huks.HuksOptions = {
properties: []
};
diff --git a/AppDataSecurity/screenshots/device/phone.png b/AppDataSecurity/screenshots/device/phone.png
new file mode 100644
index 0000000000000000000000000000000000000000..15a61b5893983d1104c8cc40ed8ad12bf2da9d67
Binary files /dev/null and b/AppDataSecurity/screenshots/device/phone.png differ
diff --git a/AppDataSecurity/screenshots/device/phone_en.png b/AppDataSecurity/screenshots/device/phone_en.png
new file mode 100644
index 0000000000000000000000000000000000000000..c12d6edaa7358a46bbf4baca21f0cc8266dd2d8f
Binary files /dev/null and b/AppDataSecurity/screenshots/device/phone_en.png differ
diff --git a/AppFreeze/AppScope/app.json5 b/AppFreeze/AppScope/app.json5
new file mode 100644
index 0000000000000000000000000000000000000000..e2a0e082396a57f4f87681236b885cf552741164
--- /dev/null
+++ b/AppFreeze/AppScope/app.json5
@@ -0,0 +1,10 @@
+{
+ "app": {
+ "bundleName": "com.example.appfreeze",
+ "vendor": "example",
+ "versionCode": 1000000,
+ "versionName": "1.0.0",
+ "icon": "$media:layered_image",
+ "label": "$string:app_name"
+ }
+}
diff --git a/AppFreeze/AppScope/resources/base/element/string.json b/AppFreeze/AppScope/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..3bd6025d487422080411763227a3a4ae82611c4e
--- /dev/null
+++ b/AppFreeze/AppScope/resources/base/element/string.json
@@ -0,0 +1,8 @@
+{
+ "string": [
+ {
+ "name": "app_name",
+ "value": "AppFreeze"
+ }
+ ]
+}
diff --git a/MultiCommunityApplication/AppScope/resources/base/media/background.png b/AppFreeze/AppScope/resources/base/media/background.png
similarity index 100%
rename from MultiCommunityApplication/AppScope/resources/base/media/background.png
rename to AppFreeze/AppScope/resources/base/media/background.png
diff --git a/MultiCommunityApplication/products/phone/src/main/resources/base/media/foreground.png b/AppFreeze/AppScope/resources/base/media/foreground.png
similarity index 100%
rename from MultiCommunityApplication/products/phone/src/main/resources/base/media/foreground.png
rename to AppFreeze/AppScope/resources/base/media/foreground.png
diff --git a/AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/media/layered_image.json b/AppFreeze/AppScope/resources/base/media/layered_image.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/media/layered_image.json
rename to AppFreeze/AppScope/resources/base/media/layered_image.json
diff --git a/AppFreeze/README.md b/AppFreeze/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8cb68c28187503ad3e13fe6f54c32343f33c7596
--- /dev/null
+++ b/AppFreeze/README.md
@@ -0,0 +1,62 @@
+# 应用冻屏(AppFreeze)样例代码工程
+
+### 介绍
+
+本示例为应用冻屏(AppFreeze)样例代码工程,包含最佳实践文档中涉及的分析方法、优化建议、问题案例等内容的局部样例代码。工程本身不具备实际功能,开发者请直接阅读具体源码结合文档来理解应用冻屏(AppFreeze)类问题的产生原因,规避方法等。
+
+
+### 效果预览
+
+不涉及
+
+### 工程目录
+```
+├──entry/src/main
+│ ├──cpp
+│ │ └──pages
+│ │ ├──CMakeLists.txt
+│ │ ├──napi_init.txt // C++ init示例代码
+│ │ └──AppFreezeCase.cpp // C++ 样例代码
+│ └──ets
+│ ├──pages
+│ │ ├──appfreezecase.ets // ArkTS样例代码
+│ │ └──Index.ets // 首页
+│ ├──entryability
+│ │ └──EntryAbility.ets // Ability的生命周期回调内容
+│ └──entrybackupability
+│ └──EntryBackupAbility.ets // 应用数据备份恢复类
+└──entry/src/main/resources // 应用资源目录
+```
+
+### 具体实现
+
+不涉及。
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机、华为PC/2in1设备、华为平板。
+
+2. HarmonyOS系统:HarmonyOS NEXT 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio NEXT 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS NEXT 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppFreeze
+git checkout
+```
\ No newline at end of file
diff --git a/AppFreeze/build-profile.json5 b/AppFreeze/build-profile.json5
new file mode 100644
index 0000000000000000000000000000000000000000..9e87e7e6f19020fe21192844709f192cec80fd44
--- /dev/null
+++ b/AppFreeze/build-profile.json5
@@ -0,0 +1,42 @@
+{
+ "app": {
+ "signingConfigs": [],
+ "products": [
+ {
+ "name": "default",
+ "signingConfig": "default",
+ "targetSdkVersion": "5.0.5(17)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "runtimeOS": "HarmonyOS",
+ "buildOption": {
+ "strictMode": {
+ "caseSensitiveCheck": true,
+ "useNormalizedOHMUrl": true
+ }
+ }
+ }
+ ],
+ "buildModeSet": [
+ {
+ "name": "debug",
+ },
+ {
+ "name": "release"
+ }
+ ]
+ },
+ "modules": [
+ {
+ "name": "entry",
+ "srcPath": "./entry",
+ "targets": [
+ {
+ "name": "default",
+ "applyToProducts": [
+ "default"
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/code-linter.json5 b/AppFreeze/code-linter.json5
similarity index 100%
rename from ArkUI/UI_Component_Performance_Optimization/code-linter.json5
rename to AppFreeze/code-linter.json5
diff --git a/AppColdStart/entry/.gitignore b/AppFreeze/entry/.gitignore
similarity index 100%
rename from AppColdStart/entry/.gitignore
rename to AppFreeze/entry/.gitignore
diff --git a/NativeSoIntegration/Ndk/build-profile.json5 b/AppFreeze/entry/build-profile.json5
similarity index 100%
rename from NativeSoIntegration/Ndk/build-profile.json5
rename to AppFreeze/entry/build-profile.json5
diff --git a/AppColdStart/HapAndHarDependHar/entry/hvigorfile.ts b/AppFreeze/entry/hvigorfile.ts
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/hvigorfile.ts
rename to AppFreeze/entry/hvigorfile.ts
diff --git a/NativeSoIntegration/Ndk/obfuscation-rules.txt b/AppFreeze/entry/obfuscation-rules.txt
similarity index 100%
rename from NativeSoIntegration/Ndk/obfuscation-rules.txt
rename to AppFreeze/entry/obfuscation-rules.txt
diff --git a/UseSendable/entry/oh-package-lock.json5 b/AppFreeze/entry/oh-package-lock.json5
similarity index 100%
rename from UseSendable/entry/oh-package-lock.json5
rename to AppFreeze/entry/oh-package-lock.json5
diff --git a/AppFreeze/entry/oh-package.json5 b/AppFreeze/entry/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..54cb066266f9993f5a023f2ac5a8dfc5d2574643
--- /dev/null
+++ b/AppFreeze/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/AppFreeze/entry/src/main/cpp/AppFreezeCase.cpp b/AppFreeze/entry/src/main/cpp/AppFreezeCase.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..2edf7ba5785dba8d46a2c438c5dc4466daf52d15
--- /dev/null
+++ b/AppFreeze/entry/src/main/cpp/AppFreezeCase.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+/**
+ * 最佳实践:AppFreeze 类问题优化建议
+ */
+
+#include
+#include
+#include
+
+std::mutex mtx;
+std::vector sharedVec;
+
+// [Start appfreeze_advise1]
+bool ContainTarget(int target) {
+ auto ret = std::find(sharedVec.begin(), sharedVec.end(), target);
+ if (ret == sharedVec.end()) {
+ return false;
+ }
+ return true;
+}
+
+int AppFreezeAdvise1() {
+ // ...
+ mtx.lock();
+ if (ContainTarget(1)) {
+ return -1;
+ // 没有释放锁
+ }
+ // 没有释放锁
+ return 0;
+}
+// [End appfreeze_advise1]
+
+
+/**
+ * 最佳实践:AppFreeze 类问题案例
+ */
+
+// [Start appfreeze_case_1_negative]
+int AppFreezeAdviseNegative() {
+ // ...
+ mtx.lock();
+ if (ContainTarget(1)) {
+ return -1;
+ }
+ // ...
+ return 0;
+}
+// [End appfreeze_case_1_negative]
+
+// [Start appfreeze_case_1_positive]
+int AppFreezeAdvisePositive() {
+ // ...
+ mtx.lock();
+ if (ContainTarget(1)) {
+ mtx.unlock();
+ return -1;
+ }
+ mtx.unlock();
+ // ...
+ return 0;
+}
+// [End appfreeze_case_1_positive]
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/cpp/CMakeLists.txt b/AppFreeze/entry/src/main/cpp/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3f9027b26132982df2949b3071b856ace4fa75cb
--- /dev/null
+++ b/AppFreeze/entry/src/main/cpp/CMakeLists.txt
@@ -0,0 +1,15 @@
+# the minimum version of CMake.
+cmake_minimum_required(VERSION 3.5.0)
+project(CppCrash)
+
+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 napi_init.cpp AppFreezeCase.cpp)
+target_link_libraries(entry PUBLIC libace_napi.z.so)
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/cpp/napi_init.cpp b/AppFreeze/entry/src/main/cpp/napi_init.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..d0e1aafcb6b5c3252ef439d9d9d54e8c082fda1d
--- /dev/null
+++ b/AppFreeze/entry/src/main/cpp/napi_init.cpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2025 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 "napi/native_api.h"
+
+static napi_value Add(napi_env env, napi_callback_info info)
+{
+ size_t argc = 2;
+ napi_value args[2] = {nullptr};
+
+ napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
+
+ napi_valuetype valuetype0;
+ napi_typeof(env, args[0], &valuetype0);
+
+ napi_valuetype valuetype1;
+ napi_typeof(env, args[1], &valuetype1);
+
+ double value0;
+ napi_get_value_double(env, args[0], &value0);
+
+ double value1;
+ napi_get_value_double(env, args[1], &value1);
+
+ napi_value sum;
+ napi_create_double(env, value0 + value1, &sum);
+
+ return sum;
+
+}
+
+EXTERN_C_START
+static napi_value Init(napi_env env, napi_value exports)
+{
+ napi_property_descriptor desc[] = {
+ { "add", nullptr, Add, 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);
+}
diff --git a/NativeSoIntegration/Ndk/src/main/cpp/types/libentry/Index.d.ts b/AppFreeze/entry/src/main/cpp/types/libentry/index.d.ts
similarity index 100%
rename from NativeSoIntegration/Ndk/src/main/cpp/types/libentry/Index.d.ts
rename to AppFreeze/entry/src/main/cpp/types/libentry/index.d.ts
diff --git a/AppFreeze/entry/src/main/cpp/types/libentry/oh-package.json5 b/AppFreeze/entry/src/main/cpp/types/libentry/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..17f2fec28b34ad5d42507c4fa15c7e4d0d16eb70
--- /dev/null
+++ b/AppFreeze/entry/src/main/cpp/types/libentry/oh-package.json5
@@ -0,0 +1,6 @@
+{
+ "name": "libentry.so",
+ "types": "./index.d.ts",
+ "version": "1.0.0",
+ "description": "Please describe the basic information."
+}
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/ets/entryability/EntryAbility.ets b/AppFreeze/entry/src/main/ets/entryability/EntryAbility.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a7e8ad07979614ccfe122b70e0ccd7306acaef68
--- /dev/null
+++ b/AppFreeze/entry/src/main/ets/entryability/EntryAbility.ets
@@ -0,0 +1,48 @@
+import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { window } from '@kit.ArkUI';
+
+const DOMAIN = 0x0000;
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (err) {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'setColorMode fail');
+ }
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
+ }
+
+ onDestroy(): void {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
+ }
+
+ onWindowStageCreate(windowStage: window.WindowStage): void {
+ // Main window is created, set main page for this ability
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
+
+ windowStage.loadContent('pages/Index', (err) => {
+ if (err.code) {
+ hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
+ return;
+ }
+ hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
+ });
+ }
+
+ onWindowStageDestroy(): void {
+ // Main window is destroyed, release UI related resources
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
+ }
+
+ onForeground(): void {
+ // Ability has brought to foreground
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
+ }
+
+ onBackground(): void {
+ // Ability has back to background
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
+ }
+}
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/AppFreeze/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
new file mode 100644
index 0000000000000000000000000000000000000000..8e4de99282050bad799ac892eb85ac5449364a51
--- /dev/null
+++ b/AppFreeze/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
@@ -0,0 +1,16 @@
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
+
+const DOMAIN = 0x0000;
+
+export default class EntryBackupAbility extends BackupExtensionAbility {
+ async onBackup() {
+ hilog.info(DOMAIN, 'testTag', 'onBackup ok');
+ await Promise.resolve();
+ }
+
+ async onRestore(bundleVersion: BundleVersion) {
+ hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion));
+ await Promise.resolve();
+ }
+}
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/ets/pages/Index.ets b/AppFreeze/entry/src/main/ets/pages/Index.ets
new file mode 100644
index 0000000000000000000000000000000000000000..0f481f696485b8c840d49ad9e7d7dff7f6b71241
--- /dev/null
+++ b/AppFreeze/entry/src/main/ets/pages/Index.ets
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Entry
+@Component
+struct Index {
+ @State message: string = 'Hello World';
+
+ build() {
+ RelativeContainer() {
+ Text(this.message)
+ .id('HelloWorld')
+ .fontSize($r('app.float.page_text_font_size'))
+ .fontWeight(FontWeight.Bold)
+ .alignRules({
+ center: { anchor: '__container__', align: VerticalAlign.Center },
+ middle: { anchor: '__container__', align: HorizontalAlign.Center }
+ })
+ .onClick(() => {
+ this.message = 'Welcome';
+ })
+ }
+ .height('100%')
+ .width('100%')
+ }
+}
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/ets/pages/appfreezecase.ets b/AppFreeze/entry/src/main/ets/pages/appfreezecase.ets
new file mode 100644
index 0000000000000000000000000000000000000000..3dca8efbfe7ec84ca112e48cf56decc5945cc800
--- /dev/null
+++ b/AppFreeze/entry/src/main/ets/pages/appfreezecase.ets
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2025 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 fs from '@ohos.file.fs';
+
+@Component
+struct ItemType {
+ @State xxx1 : number = 1;
+ @State xxx2 : number = 2;
+ @State themeStyle : string = "xxx";
+
+ build() {}
+}
+
+// [Start appfreeze_advise2]
+function getForeachKey(item : ItemType) : string {
+ // ...
+ return `${item.xxx2}${item.xxx2}...${item.themeStyle}`;
+} // 这部分逻辑如果较为耗时,执行次数多,总时长就是发生冻屏的耗时操作
+// [End appfreeze_advise2]
+
+/**
+ * 最佳实践:应用冻屏优化建议
+ */
+
+// [Start appfreeze_advise3]
+function xxxFunction1(fileUris : string[]): void {
+ // ...
+ for (const fileuri of fileUris) {
+ let file = fs.openSync(fileuri, fs.OpenMode.READ_ONLY);
+ // ...
+ }
+ // ...
+} // 如果使用同步操作,需要考虑到容器弱网或无网等极端情况发生
+// [End appfreeze_advise3]
+
+// [Start appfreeze_case_3_positive]
+async function xxxFunction2(fileUris : string[]) : Promise {
+ // ...
+ AppStorage.setOrCreate('isLoadingPic', true); // 用于页面load效果展示
+ for (const fileuri of fileUris) {
+ let file = await fs.openSync(fileuri, fs.OpenMode.READ_ONLY); // 改为异步加载
+ // ...
+ }
+ // ...
+}
+// [End appfreeze_case_3_positive]
\ No newline at end of file
diff --git a/AppFreeze/entry/src/main/module.json5 b/AppFreeze/entry/src/main/module.json5
new file mode 100644
index 0000000000000000000000000000000000000000..a1cea8b6a4560cee7bda7a2db52f310c035ab6c8
--- /dev/null
+++ b/AppFreeze/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/AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/element/color.json b/AppFreeze/entry/src/main/resources/base/element/color.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/element/color.json
rename to AppFreeze/entry/src/main/resources/base/element/color.json
diff --git a/NativeSoIntegration/Ndk/src/main/resources/base/element/float.json b/AppFreeze/entry/src/main/resources/base/element/float.json
similarity index 100%
rename from NativeSoIntegration/Ndk/src/main/resources/base/element/float.json
rename to AppFreeze/entry/src/main/resources/base/element/float.json
diff --git a/AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/element/string.json b/AppFreeze/entry/src/main/resources/base/element/string.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/element/string.json
rename to AppFreeze/entry/src/main/resources/base/element/string.json
diff --git a/MultiCommunityApplication/products/phone/src/main/resources/base/media/background.png b/AppFreeze/entry/src/main/resources/base/media/background.png
similarity index 100%
rename from MultiCommunityApplication/products/phone/src/main/resources/base/media/background.png
rename to AppFreeze/entry/src/main/resources/base/media/background.png
diff --git a/MultiVideoApplication/AppScope/resources/base/media/foreground.png b/AppFreeze/entry/src/main/resources/base/media/foreground.png
similarity index 100%
rename from MultiVideoApplication/AppScope/resources/base/media/foreground.png
rename to AppFreeze/entry/src/main/resources/base/media/foreground.png
diff --git a/CrossPlatformCompatibility/entry/src/main/resources/base/media/layered_image.json b/AppFreeze/entry/src/main/resources/base/media/layered_image.json
similarity index 100%
rename from CrossPlatformCompatibility/entry/src/main/resources/base/media/layered_image.json
rename to AppFreeze/entry/src/main/resources/base/media/layered_image.json
diff --git a/AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/media/startIcon.png b/AppFreeze/entry/src/main/resources/base/media/startIcon.png
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/media/startIcon.png
rename to AppFreeze/entry/src/main/resources/base/media/startIcon.png
diff --git a/MultMusicHome/products/phone/src/main/resources/base/profile/backup_config.json b/AppFreeze/entry/src/main/resources/base/profile/backup_config.json
similarity index 100%
rename from MultMusicHome/products/phone/src/main/resources/base/profile/backup_config.json
rename to AppFreeze/entry/src/main/resources/base/profile/backup_config.json
diff --git a/AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/profile/main_pages.json b/AppFreeze/entry/src/main/resources/base/profile/main_pages.json
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/entry/src/main/resources/base/profile/main_pages.json
rename to AppFreeze/entry/src/main/resources/base/profile/main_pages.json
diff --git a/AppFreeze/entry/src/main/resources/dark/element/color.json b/AppFreeze/entry/src/main/resources/dark/element/color.json
new file mode 100644
index 0000000000000000000000000000000000000000..79b11c2747aec33e710fd3a7b2b3c94dd9965499
--- /dev/null
+++ b/AppFreeze/entry/src/main/resources/dark/element/color.json
@@ -0,0 +1,8 @@
+{
+ "color": [
+ {
+ "name": "start_window_background",
+ "value": "#000000"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/AppColdStart/entry/src/mock/mock-config.json5 b/AppFreeze/entry/src/mock/mock-config.json5
similarity index 100%
rename from AppColdStart/entry/src/mock/mock-config.json5
rename to AppFreeze/entry/src/mock/mock-config.json5
diff --git a/ApiUsingStandards/entry/src/ohosTest/ets/test/Ability.test.ets b/AppFreeze/entry/src/ohosTest/ets/test/Ability.test.ets
similarity index 100%
rename from ApiUsingStandards/entry/src/ohosTest/ets/test/Ability.test.ets
rename to AppFreeze/entry/src/ohosTest/ets/test/Ability.test.ets
diff --git a/ApiUsingStandards/entry/src/ohosTest/ets/test/List.test.ets b/AppFreeze/entry/src/ohosTest/ets/test/List.test.ets
similarity index 100%
rename from ApiUsingStandards/entry/src/ohosTest/ets/test/List.test.ets
rename to AppFreeze/entry/src/ohosTest/ets/test/List.test.ets
diff --git a/ApiUsingStandards/entry/src/ohosTest/module.json5 b/AppFreeze/entry/src/ohosTest/module.json5
similarity index 100%
rename from ApiUsingStandards/entry/src/ohosTest/module.json5
rename to AppFreeze/entry/src/ohosTest/module.json5
diff --git a/ApiUsingStandards/entry/src/test/List.test.ets b/AppFreeze/entry/src/test/List.test.ets
similarity index 100%
rename from ApiUsingStandards/entry/src/test/List.test.ets
rename to AppFreeze/entry/src/test/List.test.ets
diff --git a/ApiUsingStandards/entry/src/test/LocalUnit.test.ets b/AppFreeze/entry/src/test/LocalUnit.test.ets
similarity index 100%
rename from ApiUsingStandards/entry/src/test/LocalUnit.test.ets
rename to AppFreeze/entry/src/test/LocalUnit.test.ets
diff --git a/AppFreeze/hvigor/hvigor-config.json5 b/AppFreeze/hvigor/hvigor-config.json5
new file mode 100644
index 0000000000000000000000000000000000000000..5bebc9755447385d82ce4138f54d991b1f85f348
--- /dev/null
+++ b/AppFreeze/hvigor/hvigor-config.json5
@@ -0,0 +1,22 @@
+{
+ "modelVersion": "5.0.5",
+ "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/AppColdStart/HapAndHarDependHar/hvigorfile.ts b/AppFreeze/hvigorfile.ts
similarity index 100%
rename from AppColdStart/HapAndHarDependHar/hvigorfile.ts
rename to AppFreeze/hvigorfile.ts
diff --git a/ArkUI/Lazy_Loading_Optimizes_Performance/oh-package-lock.json5 b/AppFreeze/oh-package-lock.json5
similarity index 100%
rename from ArkUI/Lazy_Loading_Optimizes_Performance/oh-package-lock.json5
rename to AppFreeze/oh-package-lock.json5
diff --git a/AppFreeze/oh-package.json5 b/AppFreeze/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..a8aff0c5aff22d78aa26fd19c3861f4320e951ff
--- /dev/null
+++ b/AppFreeze/oh-package.json5
@@ -0,0 +1,10 @@
+{
+ "modelVersion": "5.0.5",
+ "description": "Please describe the basic information.",
+ "dependencies": {
+ },
+ "devDependencies": {
+ "@ohos/hypium": "1.0.21",
+ "@ohos/hamock": "1.0.0"
+ }
+}
diff --git a/AppPrivacyProtection/README.en.md b/AppPrivacyProtection/README.en.md
index 3d2bb52a740a2d251f547328805999ff56d82efb..ac7ec58b9d3bfa82d49b2ebc3e657a8cf7e27a3d 100644
--- a/AppPrivacyProtection/README.en.md
+++ b/AppPrivacyProtection/README.en.md
@@ -47,8 +47,19 @@ N/A
1. This sample is supported only on Huawei phones running the standard system.
-2. The HarmonyOS version must be HarmonyOS NEXT Beta 1 or later.
+2. The HarmonyOS version must be HarmonyOS 5.0.5 Release or later.
-3. The DevEco Studio version must be DevEco Studio NEXT Beta1 or later.
+3. The DevEco Studio version must be DevEco Studio 5.0.5 Release or later.
-4. The HarmonyOS SDK version must be HarmonyOS NEXT Beta1 SDK or later.
+4. The HarmonyOS SDK version must be HarmonyOS 5.0.5 Release SDK or later.
+
+### Download
+
+To download this project separately, execute the following command:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppPrivacyProtection
+git checkout
+```
diff --git a/AppPrivacyProtection/README.md b/AppPrivacyProtection/README.md
index 4c2270dbaf26e1f41f97d3290a7079e685699f97..489516615c9f929247ed6e9f37fb17a04fd13f31 100644
--- a/AppPrivacyProtection/README.md
+++ b/AppPrivacyProtection/README.md
@@ -45,11 +45,22 @@
1. 本示例仅支持标准系统上运行,支持设备:华为手机。
-2. HarmonyOS系统:HarmonyOS 5.0.0 Release及以上。
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
-3. DevEco Studio版本:DevEco Studio 5.0.0 Release及以上。
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
-4. HarmonyOS SDK版本:HarmonyOS 5.0.0 Release SDK及以上。
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AppPrivacyProtection
+git checkout
+```
diff --git a/AppPrivacyProtection/build-profile.json5 b/AppPrivacyProtection/build-profile.json5
index 1e69556b3411622cb2e87a87389653bb34f1b148..492123c253881f5bbd9bc76553bfb74e842dfb40 100644
--- a/AppPrivacyProtection/build-profile.json5
+++ b/AppPrivacyProtection/build-profile.json5
@@ -5,7 +5,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/AppPrivacyProtection/entry/src/main/ets/pages/ApproximatelyLocationDemo.ets b/AppPrivacyProtection/entry/src/main/ets/pages/ApproximatelyLocationDemo.ets
index d24fcb14e743a9723dceb0125ca771ae600759f3..4d1d7adf2ccfdcb5957f15fd044a612494ec4fa8 100644
--- a/AppPrivacyProtection/entry/src/main/ets/pages/ApproximatelyLocationDemo.ets
+++ b/AppPrivacyProtection/entry/src/main/ets/pages/ApproximatelyLocationDemo.ets
@@ -30,12 +30,18 @@ struct ApproximatelyLocationDemo {
// [End request_permission]
const bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
- const grantStatus = accessManager.checkAccessTokenSync(bundleInfo.appInfo.accessTokenId, permissions[0]);
-
+ let grantStatus: abilityAccessCtrl.GrantStatus | null = null;
+ try {
+ grantStatus = accessManager.checkAccessTokenSync(bundleInfo.appInfo.accessTokenId, permissions[0]);
+ } catch (error) {
+ let err = error as BusinessError;
+ Logger.error(`showToast failed, code=${err.code}, message=${err.message}`);
+ }
return new Promise((resolve, reject) => {
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
// [Start request_permission]
- accessManager.requestPermissionsFromUser(this.getUIContext().getHostContext(), ['ohos.permission.APPROXIMATELY_LOCATION'])
+ accessManager.requestPermissionsFromUser(this.getUIContext().getHostContext(),
+ ['ohos.permission.APPROXIMATELY_LOCATION'])
.then((data) => {
let grantStatus: Array = data.authResults;
if (grantStatus.length > 0 && grantStatus[0] === 0) {
@@ -48,15 +54,20 @@ struct ApproximatelyLocationDemo {
// The user rejects the authorization
Logger.info('request permissions denied');
// [StartExclude request_permission]
- this.getUIContext().getPromptAction().showToast({
- message: 'This function requires the location permission. Go to the settings page to authorize the permission'
- });
+ try {
+ this.getUIContext().getPromptAction().showToast({
+ message: 'This function requires the location permission. Go to the settings page to authorize the permission'
+ });
+ } catch (error) {
+ let err = error as BusinessError;
+ Logger.error(`showToast failed, code=${err.code}, message=${err.message}`);
+ }
resolve(-1);
// [EndExclude request_permission]
}
Logger.info(`request permissions result: ${JSON.stringify(data)}`);
})
- // [End request_permission]
+ // [End request_permission]
.catch((error: BusinessError) => {
Logger.error(`request permissions exception, Catch error:${JSON.stringify(error)}`);
reject(error);
@@ -67,7 +78,6 @@ struct ApproximatelyLocationDemo {
});
}
-
getLocation() {
this.requestPermissions().then(data => {
diff --git a/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets b/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets
index f190b3ea84857682f733a7f4a3636082a07dca37..78cc67a40ac38c67f4d8fa85651be9e60ab158a3 100644
--- a/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets
+++ b/AppPrivacyProtection/entry/src/main/ets/pages/Index.ets
@@ -25,7 +25,13 @@ struct Index {
const accessManager = abilityAccessCtrl.createAtManager();
const bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
- const grantStatus = accessManager.checkAccessTokenSync(bundleInfo.appInfo.accessTokenId, permissions[0]);
+ let grantStatus: abilityAccessCtrl.GrantStatus | null = null;
+ try {
+ grantStatus = accessManager.checkAccessTokenSync(bundleInfo.appInfo.accessTokenId, permissions[0]);
+ } catch (error) {
+ let err = error as BusinessError;
+ Logger.error(`checkAccessTokenSync failed, code=${err.code}, message=${err.message}`);
+ }
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
// [Start permission_camera]
accessManager.requestPermissionsFromUser(this.getUIContext().getHostContext(), ['ohos.permission.CAMERA'])
@@ -36,18 +42,31 @@ struct Index {
} else {
Logger.info('request permissions denied');
// [StartExclude permission_camera]
- this.getUIContext().getPromptAction().showToast({
- message: 'This function requires the camera permission. Go to the settings page to authorize the permission'
- });
+ try {
+ this.getUIContext().getPromptAction().showToast({
+ message: 'This function requires the camera permission. Go to the settings page to authorize the permission'
+ });
+ } catch (error) {
+ let err = error as BusinessError;
+ Logger.error(`showToast failed, code=${err.code}, message=${err.message}`);
+ }
// [EndExclude permission_camera]
}
})
- // [End permission_camera]
+ // [End permission_camera]
.catch((error: BusinessError) => {
Logger.error(`request permissions exception, Catch error:${JSON.stringify(error)}`);
})
} else {
Logger.info('request permissions granted');
+ try {
+ this.getUIContext().getPromptAction().showToast({
+ message: 'request permissions has granted'
+ });
+ } catch (error) {
+ let err = error as BusinessError;
+ Logger.error(`showToast failed, code=${err.code}, message=${err.message}`);
+ }
}
}
@@ -57,13 +76,29 @@ struct Index {
.height(40)
.width('100%')
.onClick(() => {
- this.getUIContext().getRouter().pushUrl({ url: 'pages/ApproximatelyLocationDemo' });
+ this.getUIContext()
+ .getRouter()
+ .pushUrl({ url: 'pages/ApproximatelyLocationDemo' })
+ .then(() => {
+ Logger.info(`showToast success`);
+ })
+ .catch((err: BusinessError) => {
+ Logger.error(`showToast failed, code=${err.code}, message=${err.message}`);
+ })
})
Button($r('app.string.use_picker'))
.height(40)
.width('100%')
.onClick(() => {
- this.getUIContext().getRouter().pushUrl({ url: 'pages/PickerDemo' });
+ this.getUIContext()
+ .getRouter()
+ .pushUrl({ url: 'pages/PickerDemo' })
+ .then(() => {
+ Logger.info(`showToast success`);
+ })
+ .catch((err: BusinessError) => {
+ Logger.error(`showToast failed, code=${err.code}, message=${err.message}`);
+ })
})
Button($r('app.string.apply_camera_permissions'))
.height(40)
diff --git a/AppPrivacyProtection/entry/src/main/ets/pages/PickerDemo.ets b/AppPrivacyProtection/entry/src/main/ets/pages/PickerDemo.ets
index 672e4fc2f9175a07f8fc33b914beefc5e3fb0383..2af5826d33d175f2c72ecdcde7ca86498e8adff1 100644
--- a/AppPrivacyProtection/entry/src/main/ets/pages/PickerDemo.ets
+++ b/AppPrivacyProtection/entry/src/main/ets/pages/PickerDemo.ets
@@ -16,7 +16,6 @@
// [Start picker_demo]
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
-// [End picker_demo]
import Logger from '../utils/Logger';
@Entry
@@ -27,23 +26,25 @@ struct PickerDemo {
build() {
RelativeContainer() {
Image(this.imageUri)
- .width('100%')
+ // [StartExclude picker_demo]
+ .width('60%')
.margin({ bottom: 12 })
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
-
+ // [EndExclude picker_demo]
Button($r('app.string.select_picture'))
+ // [StartExclude picker_demo]
.height(40)
.width('100%')
.margin({ bottom: 44 })
.alignRules({
- center: { anchor: '__container__', align: VerticalAlign.Center },
+ center: { anchor: '__container__', align: VerticalAlign.Bottom },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
+ // [EndExclude picker_demo]
.onClick(() => {
- // [Start picker_demo]
const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 5;
@@ -54,11 +55,13 @@ struct PickerDemo {
}).catch((err: BusinessError) => {
Logger.error(`PhotoViewPicker.select failed with err: ${JSON.stringify(err)}`)
})
- // [End picker_demo]
})
}
+ // [StartExclude picker_demo]
.height('100%')
.width('100%')
.padding(16)
+ // [EndExclude picker_demo]
}
-}
\ No newline at end of file
+}
+// [End picker_demo]
\ No newline at end of file
diff --git a/ArkTS_high_performance_segment/README.md b/ArkTS_high_performance_segment/README.md
index e112b3470786aac68ca9c192131ef9edf90ccbba..7bffe6a58bf8030b50237d6d9ede610f7ae875a4 100644
--- a/ArkTS_high_performance_segment/README.md
+++ b/ArkTS_high_performance_segment/README.md
@@ -1,3 +1,26 @@
# ArkTS高性能编程代码片段
+## 介绍
+最佳实践->应用框架->ArkTS语言->ArkTS高性能编程。
-最佳实践->应用框架->ArkTS语言->ArkTS高性能编程
\ No newline at end of file
+## 相关权限
+无
+
+## 约束与限制
+* 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+* HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+* DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+* HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+## 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkTS_high_performance_segment
+git checkout
+```
\ No newline at end of file
diff --git a/ArkTS_high_performance_segment/entry/src/main/ets/segment/segment6.ets b/ArkTS_high_performance_segment/entry/src/main/ets/segment/segment6.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a04b9687cc09be36c347177fccbcd1bb1bfbf253
--- /dev/null
+++ b/ArkTS_high_performance_segment/entry/src/main/ets/segment/segment6.ets
@@ -0,0 +1,74 @@
+// Attention: This is the counterexample file
+
+// [Start export_multi_levels]
+// main: Hap import har file
+import { one } from '@har/Index'
+
+// har/Index.ets (one level)
+export * from './InnerIndex'
+export * from './Utils'
+export * from './Logs'
+export * from './Service'
+export * from './Common'
+export * from './Feature'
+
+// InnerIndex.ets (two level)
+export * from './ThirdIndex'
+export { two } from 'Temp'
+export * from './Utils'
+export * from './Logs'
+export * from './Service'
+
+// ...more level
+
+// LastIndex.ets (N level)
+export * from './Utils';
+export { three } from 'Temp'
+export * from './Numbers'
+
+// Numbers.ets
+export const One: number = 1;
+// [End export_multi_levels]
+
+// [Start export_one_level]
+// main: Hap import har file
+import { one } from '@har/Index'
+
+// har/Index.ets
+export * from './Numbers' // only one level
+
+// Numbers.ets
+export const one: number = 1;
+// [End export_one_level]
+
+// [Start multi_star_export]
+// main.ets
+import { one } from '@har/Index';
+
+// @har/Index.ets
+export * from './Numbers'
+export * from './Utils'
+export * from './Logs'
+export * from './Service'
+export * from './Common'
+export * from './Feature'
+
+// Numbers.ets
+export const one : number = 1;
+// [End multi_star_export]
+
+// [Start name_export]
+// main.ets
+import { one } from '@har/Index';
+
+// @har/Index.ets
+export { one } from '../Numbers' // use named export
+export * from './Utils'
+export * from './Logs'
+export * from './Service'
+export * from './Common'
+export * from './Feature'
+
+// Numbers.ets
+export const one: number = 1;
+// [End name_export]
\ No newline at end of file
diff --git a/ArkUI/Component_Nesting_Optimization/README_zh.md b/ArkUI/Component_Nesting_Optimization/README_zh.md
new file mode 100644
index 0000000000000000000000000000000000000000..ae48f3220d53b9cf54d92065afdc0f0092045269
--- /dev/null
+++ b/ArkUI/Component_Nesting_Optimization/README_zh.md
@@ -0,0 +1,51 @@
+# 不同场景下组件嵌套的性能优化策略
+
+### 介绍
+
+本示例是[《组件嵌套优化》](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-component-nesting-optimization)的配套示例代码,通过正反例代码展示页面布局时,如何减少性能开销。
+
+
+### 工程目录
+```
+├──entry/src/main/ets // 代码区
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets
+│ ├──pages
+│ │ └──Index.ets
+│ └──segment
+│ ├──segment1.ets // 场景1
+│ ├──segment2.ets // 场景2
+│ ├──segment3.ets // 场景3
+│ ├──segment4.ets // 场景4
+│ ├──segment5.ets // 场景5
+│ └──segment6.ets // 场景6
+└──entry/src/main/resources // 应用资源目录
+```
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/Component_Nesting_Optimization
+git checkout
+```
\ No newline at end of file
diff --git a/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..faef53f986d5fbedc6ba520c813ee0d0dbd18f9a 100644
--- a/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,4 +1,5 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit'
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -6,7 +7,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment2.ets b/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment2.ets
index c606b3482bd58e8a18b45ec9a4180705322798db..e4e30ddff6e535cc6207e10e50791ed8823d4ade 100644
--- a/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment2.ets
+++ b/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment2.ets
@@ -61,7 +61,7 @@ struct ModifierCustom {
build() {
Column() {
- Text('Hello Word')
+ Text('Hello World')
}.attributeModifier(this.modifier)
}
}
diff --git a/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment6.ets b/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment6.ets
index 6f51145bc8bf0138c343b01b0bb7be7e2dc64a7b..86f22e9f56dd9dea8c110e05825e856a4c6ff5fc 100644
--- a/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment6.ets
+++ b/ArkUI/Component_Nesting_Optimization/entry/src/main/ets/segment/segment6.ets
@@ -1,6 +1,7 @@
// [Start Case5]
import { ColorMetrics } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
@Component
struct ColorMeasure {
@@ -18,7 +19,12 @@ struct ColorMeasure {
getBlendColor(baseColor: ResourceColor, addColor: ResourceColor): ColorMetrics {
if (!baseColor || !addColor) {
- return ColorMetrics.resourceColor(Color.Black);
+ try {
+ return ColorMetrics.resourceColor(Color.Black);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `showToast failed, code=${err.code}, message=${err.message}`);
+ }
}
let sourceColor: ColorMetrics;
try {
@@ -48,4 +54,5 @@ struct ColorMetricsExample {
}
}
}
+
// [End Case5]
\ No newline at end of file
diff --git a/ArkUI/Component_Nesting_Optimization/entry/src/main/module.json5 b/ArkUI/Component_Nesting_Optimization/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..ad219d733f6afa5ea07f85f580208b08cc3b9041 100644
--- a/ArkUI/Component_Nesting_Optimization/entry/src/main/module.json5
+++ b/ArkUI/Component_Nesting_Optimization/entry/src/main/module.json5
@@ -5,9 +5,7 @@
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
- "phone",
- "tablet",
- "2in1"
+ "phone"
],
"deliveryWithInstall": true,
"installationFree": false,
diff --git a/ArkUI/Component_Nesting_Optimization/entry/src/main/resources/base/element/string.json b/ArkUI/Component_Nesting_Optimization/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..ac8f28701c8c94819a1b34d5c402c751cdfa61d3 100644
--- a/ArkUI/Component_Nesting_Optimization/entry/src/main/resources/base/element/string.json
+++ b/ArkUI/Component_Nesting_Optimization/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "component-nesting-optimization"
}
]
}
\ No newline at end of file
diff --git a/ArkUI/Component_Redundancy_Refresh_Optimization/README.md b/ArkUI/Component_Redundancy_Refresh_Optimization/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..594a40f5c0a8c7c5adc3da40351e996df77543d7
--- /dev/null
+++ b/ArkUI/Component_Redundancy_Refresh_Optimization/README.md
@@ -0,0 +1,58 @@
+# 组件冗余刷新解决方案样例代码工程
+
+### 介绍
+
+本示例为组件冗余刷新解决方案样例代码工程,包含组件冗余刷新解决方案正例和反例内容的局部样例代码。工程本身不具备实际功能,开发者请直接阅读具体源码结合文档来理解。
+
+
+### 效果预览
+
+不涉及
+
+### 工程目录
+```
+├──entry/src/main/ets
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 应用数据备份恢复类
+│ ├──pages
+│ │ └──Index.ets // 首页
+│ └──segment
+│ ├──segment1 // 反例
+│ └──segment2 // 正例
+└──entry/src/main/resources // 应用静态资源目录
+```
+
+### 具体实现
+
+不涉及。
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机、华为PC/2in1设备、华为平板。
+
+2. HarmonyOS系统:HarmonyOS NEXT 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio NEXT 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS NEXT 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/Component_Redundancy_Refresh_Optimization
+git checkout
+```
\ No newline at end of file
diff --git a/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..2880ca09588393e53ffafcdb1a11f66cdde90b4f 100644
--- a/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,4 +1,5 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -6,7 +7,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment1.ets b/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment1.ets
index 9b3c26bca072a24651ba4dea953e552d6e67360c..386160749164fc280e3d43499b18082b0d1cd426 100644
--- a/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment1.ets
+++ b/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment1.ets
@@ -24,39 +24,54 @@ struct ComponentA {
Column() {
// Components that use state variables
SpecialImage({ specialImageUiStyle: this.uiStyle })
- Stack() {
- Column() {
- Image($r('app.media.startIcon'))
- .height(78)
- .width(78)
- .scale({
- x: this.uiStyle.scaleX,
- y: this.uiStyle.scaleY
- })
- }
-
- Stack() {
- Text('Hello World')
- }
+ Column() {
+ // 需要替换为开发者所需的图像资源文件
+ Image($r('app.media.startIcon'))
+ .height('150vp')
+ .width('150vp')
+ .scale({
+ x: this.uiStyle.scaleX,
+ y: this.uiStyle.scaleY
+ })
+ Text('Hello World')
+ .fontWeight(FontWeight.Bold)
}
.translate({
x: this.uiStyle.translateX,
y: this.uiStyle.translateY
})
-
+ .width('95%')
+ .height('200vp')
+ .margin({
+ top: '10vp',
+ left: '15vp',
+ right: '15vp'
+ })
+ .borderRadius('16vp')
+ .backgroundColor(Color.White)
// Modify the value of a state variable via a button click callback, causing the corresponding component to refresh.
Column() {
Button('Move')
+ .width('80%')
.onClick(() => {
this.getUIContext().animateTo({ duration: animationDuration }, () => {
this.uiStyle.translateY = (this.uiStyle.translateY + translateYChangeValue) % translateYChangeRange;
})
})
Button('Scale')
+ .width('80%')
.onClick(() => {
this.uiStyle.scaleX = (this.uiStyle.scaleX + scaleXChangeValue) % scaleXChangeRange;
})
+ .margin({
+ top: '10vp',
+ left: '15vp',
+ right: '15vp'
+ })
}
+ .height('35%')
+ .justifyContent(FlexAlign.End)
+ .width('100%')
}
}
}
@@ -74,15 +89,26 @@ struct SpecialImage {
build() {
Column() {
+ // 需要替换为开发者所需的图像资源文件
Image($r('app.media.startIcon'))
- .size({ width: 200, height: 200 })
+ .size({ width: 78, height: 78 })
.scale({
x: this.specialImageUiStyle.scaleX,
y: this.specialImageUiStyle.scaleY
})
.opacity(this.isRenderSpecialImage())
Text("SpecialImage")
+ .fontWeight(FontWeight.Bold)
}
+ .width('95%')
+ .margin({
+ top: '10vp',
+ left: '15vp',
+ right: '15vp'
+ })
+ .borderRadius('16vp')
+ .height('200vp')
+ .backgroundColor(Color.White)
}
}
@@ -100,6 +126,7 @@ struct DFXStateBeforeOptimization {
}
.width('100%')
.height('100%')
+ .backgroundColor(0xDCDCDC)
}
}
diff --git a/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment2.ets b/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment2.ets
index c44e19606b9c18e7d6026f8a0f61d97a77e52290..1583092b1b7b8809a68ce07f5f4823c1ff29e04a 100644
--- a/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment2.ets
+++ b/ArkUI/Component_Redundancy_Refresh_Optimization/entry/src/main/ets/segment/segment2.ets
@@ -40,27 +40,36 @@ struct ComponentA {
specialImageScaleStyle: this.scaleStyle
})
// Other UI components
- Stack() {
Column() {
+ // 需要替换为开发者所需的图像资源文件
Image($r('app.media.startIcon'))
+ .height('150vp')
+ .width('150vp')
.scale({
x: this.scaleStyle.scaleX,
y: this.scaleStyle.scaleY
})
- }
-
- Stack() {
Text('Hello World')
+ .fontWeight(FontWeight.Bold)
}
- }
+
.translate({
x: this.translateStyle.translateX,
y: this.translateStyle.translateY
})
-
+ .width('95%')
+ .height('200vp')
+ .margin({
+ top: '10vp',
+ left: '15vp',
+ right: '15vp'
+ })
+ .borderRadius('16vp')
+ .backgroundColor(Color.White)
// Modify the value of a state variable via a button click callback, causing the corresponding component to refresh.
Column() {
Button('Move')
+ .width('80%')
.onClick(() => {
this.getUIContext().animateTo({ duration: animationDuration }, () => {
this.translateStyle.translateY =
@@ -68,10 +77,19 @@ struct ComponentA {
})
})
Button('Scale')
+ .width('80%')
.onClick(() => {
this.scaleStyle.scaleX = (this.scaleStyle.scaleX + scaleXChangeValue) % scaleXChangeRange;
})
+ .margin({
+ top: '10vp',
+ left: '15vp',
+ right: '15vp'
+ })
}
+ .height('35%')
+ .justifyContent(FlexAlign.End)
+ .width('100%')
}
}
}
@@ -90,14 +108,26 @@ struct SpecialImage {
build() {
Column() {
+ // 需要替换为开发者所需的图像资源文件
Image($r('app.media.startIcon'))
+ .size({ width: 78, height: 78 })
.scale({
x: this.specialImageScaleStyle.scaleX,
y: this.specialImageScaleStyle.scaleY
})
.opacity(this.isRenderSpecialImage())
Text("SpecialImage")
+ .fontWeight(FontWeight.Bold)
}
+ .width('95%')
+ .margin({
+ top: '10vp',
+ left: '15vp',
+ right: '15vp'
+ })
+ .borderRadius('16vp')
+ .height('200vp')
+ .backgroundColor(Color.White)
}
}
@@ -113,6 +143,9 @@ struct DFXStateAfterOptimization {
translateStyle: this.uiStyle.translateStyle,
})
}
+ .width('100%')
+ .height('100%')
+ .backgroundColor(0xDCDCDC)
}
}
diff --git a/ArkUI/Lazy_Loading_Optimizes_Performance/README.md b/ArkUI/Lazy_Loading_Optimizes_Performance/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..819198a50f3463d6d2c9cfd46b5cd7722bc0ceb4
--- /dev/null
+++ b/ArkUI/Lazy_Loading_Optimizes_Performance/README.md
@@ -0,0 +1,53 @@
+# 布局优化指导
+## 介绍
+本例介绍了5种优化手段,分别为使用系统提供的动画接口、使用图形变换属性变化组件布局、参数相同时使用同一个animateTo、多次animateTo时统一更新状态变量、使用renderGroup。通过这些优化手段的单个使用或组合使用,可以对动画帧率、应用卡顿等方面带来优化,提升性能和用户体验。
+
+## 效果预览
+不涉及
+
+## 使用说明
+不涉及
+
+## 工程目录
+```
+├──entry/src/main/ets // 代码区
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 应用数据备份和恢复
+│ ├──pages
+│ │ └──Index.ets // 首页
+│ └──segment
+│ ├──segment1.ets // ForEach页面
+│ └──segment2.ets // LazyForEach页面
+└──entry/src/main/resources // 应用资源目录
+```
+
+## 具体实现
+
+不涉及。
+
+## 相关权限
+
+不涉及。
+
+## 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+## 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/Lazy_Loading_Optimizes_Performance
+git checkout
+```
\ No newline at end of file
diff --git a/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..a7e8ad07979614ccfe122b70e0ccd7306acaef68 100644
--- a/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/entryability/EntryAbility.ets
@@ -6,7 +6,11 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (err) {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'setColorMode fail');
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/pages/Index.ets b/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/pages/Index.ets
index bfb9190d4b26c6248dea78b6da3eddc37dde5389..2da5d3f7349279647d7511efed13f8c75b176e2d 100644
--- a/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/pages/Index.ets
+++ b/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/ets/pages/Index.ets
@@ -22,11 +22,11 @@ struct Index {
}.margin({ left: 10, right: 10 })
}.onAppear(() => {
// Record the number of times the component is created through onAppear
- console.info("appear:" + lazyForEachItem)
+ console.info('appear:' + lazyForEachItem);
})
}, (item: string) => {
// Print the key value in the keyGenerator function
- console.info("key:" + item)
+ console.info('key:' + item);
return item;
})
// [End Lazy_for_each]
diff --git a/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/resources/base/element/string.json b/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..79995ff14b6a7263a947a5f63ff4cd1820a7a436 100644
--- a/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/resources/base/element/string.json
+++ b/ArkUI/Lazy_Loading_Optimizes_Performance/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "LazyLoad"
}
]
}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/README.md b/ArkUI/Proper_Use_Layout/README.md
index f51b77558444e5ba33447d1070bc788576c83f46..061425f4779180d24cfb6a2b3d9d11453a6bfd82 100644
--- a/ArkUI/Proper_Use_Layout/README.md
+++ b/ArkUI/Proper_Use_Layout/README.md
@@ -2,10 +2,6 @@
## 介绍
本例通过Scroll嵌套List,对比List设置宽度和不设置的情况。
-## 预览效果
-
-
-
## 工程目录
```
├──entry/src/main/ets // 代码区
@@ -16,20 +12,35 @@
│ ├──pages
│ │ └──Index.ets // 首页
│ └──segment
-│ ├──segment1.ets
-│ ├──segment2.ets
-│ └──segment3.ets
+│ ├──segment1.ets // List列表数据
+│ ├──segment2.ets // List不设置宽高
+│ └──segment3.ets // List设置固定高度
└──entry/src/main/resources // 应用资源目录
```
+## 使用说明
+示例代码包含两个场景:
+* Scroll嵌套List,List不设置宽高。
+* Scroll嵌套List,List设置固定宽高。
## 相关权限
无
## 约束与限制
-* 本示例仅支持标准系统上运行,支持设备:华为手机。
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
-* HarmonyOS系统:HarmonyOS NEXT Release及以上。
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
-* DevEco Studio版本:DevEco Studio NEXT Release及以上。
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
-* HarmonyOS SDK版本:HarmonyOS NEXT Release SDK及以上。
\ No newline at end of file
+## 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/Proper_Use_Layout
+git checkout
+```
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/README_EN.md b/ArkUI/Proper_Use_Layout/README_EN.md
index 58b21c1bb15c9b10e45c2555e9c5fb0b30ecd026..99f230393d37c542f62bdee2f9a5924b5284b3c3 100644
--- a/ArkUI/Proper_Use_Layout/README_EN.md
+++ b/ArkUI/Proper_Use_Layout/README_EN.md
@@ -25,10 +25,21 @@ This example uses Scroll to nest a List and compares the situations where the Li
N/A
## Constraints
-* This sample is supported only on Huawei phones running the standard system.
+1. This sample is supported only on Huawei phones running the standard system.
-* The HarmonyOS version must be HarmonyOS NEXT Release or later.
+2. The HarmonyOS version must be HarmonyOS 5.0.5 Release or later.
-* The DevEco Studio version must be DevEco Studio NEXT Release or later.
+3. The DevEco Studio version must be DevEco Studio 5.0.5 Release or later.
-* The HarmonyOS SDK version must be HarmonyOS NEXT Release SDK or later.
+4. The HarmonyOS SDK version must be HarmonyOS 5.0.5 Release SDK or later.
+
+## Download
+
+To download this project separately, execute the following command:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/Proper_Use_Layout
+git checkout
+```
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/Proper_Use_Layout/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..5282cb6dd13ef29510ba872b3e237c9fab7732fb 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,4 +1,20 @@
+/*
+* Copyright (C) 2025 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, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -6,7 +22,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/ArkUI/Proper_Use_Layout/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
index 8e4de99282050bad799ac892eb85ac5449364a51..7eb1afb81759bc5d59117077cb08b938ea66d402 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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';
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/ets/pages/Index.ets b/ArkUI/Proper_Use_Layout/entry/src/main/ets/pages/Index.ets
index 8e2d24ad42693fc877d51bb7820f0a9da68fa135..c149968e780eb9bac1ecb78fb539dff080631356 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/ets/pages/Index.ets
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/ets/pages/Index.ets
@@ -1,23 +1,59 @@
+/*
+* Copyright (C) 2025 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 { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+
@Entry
@Component
struct Index {
- @State message: string = 'Hello World';
-
build() {
- RelativeContainer() {
- Text(this.message)
- .id('HelloWorld')
- .fontSize($r('app.float.page_text_font_size'))
- .fontWeight(FontWeight.Bold)
- .alignRules({
- center: { anchor: '__container__', align: VerticalAlign.Center },
- middle: { anchor: '__container__', align: HorizontalAlign.Center }
+ Column({ space: 15 }) {
+ Button('to segment2')
+ .width('100%')
+ .onClick(() => {
+ this.getUIContext()
+ .getRouter()
+ .pushUrl({
+ url: 'segment/segment2'
+ })
+ .then(() => {
+ hilog.info(0x000, 'testTag', `pushUrl succeed.`);
+ })
+ .catch((err: BusinessError) => {
+ hilog.warn(0x000, 'testTag', `pushUrl failed. code=${err.code}, message=${err.message}`);
+ })
})
+ Button('to segment3')
+ .width('100%')
.onClick(() => {
- this.message = 'Welcome';
+ this.getUIContext()
+ .getRouter()
+ .pushUrl({
+ url: 'segment/segment3'
+ })
+ .then(() => {
+ hilog.info(0x000, 'testTag', `pushUrl succeed.`);
+ })
+ .catch((err: BusinessError) => {
+ hilog.warn(0x000, 'testTag', `pushUrl failed. code=${err.code}, message=${err.message}`);
+ })
})
}
.height('100%')
.width('100%')
+ .justifyContent(FlexAlign.End)
+ .padding({ left: 12, right: 12, bottom: 15 })
}
}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment1.ets b/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment1.ets
index e638042083e9b1c6fd0590e406ea45cb80740030..78e7470d1cd9603a56bae794a705f9aaf2b0da8e 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment1.ets
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment1.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Case1]
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = [];
@@ -29,31 +44,31 @@ class BasicDataSource implements IDataSource {
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded();
- })
+ });
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index);
- })
+ });
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index);
- })
+ });
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index);
- })
+ });
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to);
- })
+ });
}
}
@@ -65,22 +80,18 @@ export class MyDataSource extends BasicDataSource {
return this.dataArray.length;
}
-
public getData(index: number): string {
return this.dataArray[index];
}
-
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data);
this.notifyDataAdd(index);
}
-
public pushData(data: string): void {
this.dataArray.push(data);
this.notifyDataAdd(this.dataArray.length - 1);
}
}
-
// [End Case1]
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment2.ets b/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment2.ets
index 8a35f830bdb7994fb799fa75247bd13ecac808da..ceba20c641185308c1a3da842bbf0dbfcb72936e 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment2.ets
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment2.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Case2]
import { MyDataSource } from './segment1';
@@ -12,7 +27,9 @@ struct NotSetHeightTestPage {
LazyForEach(this.data, (item: string, index: number) => {
ListItem() {
Row() {
- Text('item value: ' + item + (index + 1)).fontSize(20).margin(10)
+ Text('item value: ' + item + (index + 1))
+ .fontSize(20)
+ .margin(10)
}
}
})
@@ -20,5 +37,4 @@ struct NotSetHeightTestPage {
}
}
}
-
// [End Case2]
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment3.ets b/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment3.ets
index 8e402c582648152c4fbc2ee9ba9fd998df0e788d..d6af7e0482e95f6af54386d19e9e2c4596b0bbed 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment3.ets
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/ets/segment/segment3.ets
@@ -1,7 +1,21 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Case3]
import { MyDataSource } from './segment1';
-
@Entry
@Component
struct SetHeightTestPage {
@@ -13,13 +27,16 @@ struct SetHeightTestPage {
LazyForEach(this.data, (item: string, index: number) => {
ListItem() {
Row() {
- Text('item value: ' + item + (index + 1)).fontSize(20).margin(10)
+ Text('item value: ' + item + (index + 1))
+ .fontSize(20)
+ .margin(10)
}
}
})
- }.width('100%').height(500)
+ }
+ .width('100%')
+ .height(500)
}
}
}
-
// [End Case3]
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/module.json5 b/ArkUI/Proper_Use_Layout/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..44c5e49d8129f5d5bcc87ee6768d4a007d4877ca 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/module.json5
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/module.json5
@@ -6,8 +6,6 @@
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
- "tablet",
- "2in1"
],
"deliveryWithInstall": true,
"installationFree": false,
diff --git a/ArkUI/Proper_Use_Layout/entry/src/main/resources/base/profile/main_pages.json b/ArkUI/Proper_Use_Layout/entry/src/main/resources/base/profile/main_pages.json
index 1898d94f58d6128ab712be2c68acc7c98e9ab9ce..7230a3f2b31a1de8b2b3a36a3e4448bb571b3434 100644
--- a/ArkUI/Proper_Use_Layout/entry/src/main/resources/base/profile/main_pages.json
+++ b/ArkUI/Proper_Use_Layout/entry/src/main/resources/base/profile/main_pages.json
@@ -1,5 +1,7 @@
{
"src": [
- "pages/Index"
+ "pages/Index",
+ "segment/segment2",
+ "segment/segment3"
]
}
diff --git a/ArkUI/Proper_Use_Layout/entry/src/mock/mock-config.json5 b/ArkUI/Proper_Use_Layout/entry/src/mock/mock-config.json5
deleted file mode 100644
index 7a73a41bfdf76d6f793007240d80983a52f15f97..0000000000000000000000000000000000000000
--- a/ArkUI/Proper_Use_Layout/entry/src/mock/mock-config.json5
+++ /dev/null
@@ -1,2 +0,0 @@
-{
-}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/ohosTest/ets/test/Ability.test.ets b/ArkUI/Proper_Use_Layout/entry/src/ohosTest/ets/test/Ability.test.ets
deleted file mode 100644
index 85c78f67579d6e31b5f5aeea463e216b9b141048..0000000000000000000000000000000000000000
--- a/ArkUI/Proper_Use_Layout/entry/src/ohosTest/ets/test/Ability.test.ets
+++ /dev/null
@@ -1,35 +0,0 @@
-import { hilog } from '@kit.PerformanceAnalysisKit';
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function abilityTest() {
- describe('ActsAbilityTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- })
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- })
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- })
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- })
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- })
- })
-}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/ohosTest/ets/test/List.test.ets b/ArkUI/Proper_Use_Layout/entry/src/ohosTest/ets/test/List.test.ets
deleted file mode 100644
index 794c7dc4ed66bd98fa3865e07922906e2fcef545..0000000000000000000000000000000000000000
--- a/ArkUI/Proper_Use_Layout/entry/src/ohosTest/ets/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import abilityTest from './Ability.test';
-
-export default function testsuite() {
- abilityTest();
-}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/test/List.test.ets b/ArkUI/Proper_Use_Layout/entry/src/test/List.test.ets
deleted file mode 100644
index bb5b5c3731e283dd507c847560ee59bde477bbc7..0000000000000000000000000000000000000000
--- a/ArkUI/Proper_Use_Layout/entry/src/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import localUnitTest from './LocalUnit.test';
-
-export default function testsuite() {
- localUnitTest();
-}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/entry/src/test/LocalUnit.test.ets b/ArkUI/Proper_Use_Layout/entry/src/test/LocalUnit.test.ets
deleted file mode 100644
index 165fc1615ee8618b4cb6a622f144a9a707eee99f..0000000000000000000000000000000000000000
--- a/ArkUI/Proper_Use_Layout/entry/src/test/LocalUnit.test.ets
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function localUnitTest() {
- describe('localUnitTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- });
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- });
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- });
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- });
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- });
- });
-}
\ No newline at end of file
diff --git a/ArkUI/Proper_Use_Layout/oh-package.json5 b/ArkUI/Proper_Use_Layout/oh-package.json5
index a8aff0c5aff22d78aa26fd19c3861f4320e951ff..f440d114b8a9d9aeadd0e891bba0d0d076e70936 100644
--- a/ArkUI/Proper_Use_Layout/oh-package.json5
+++ b/ArkUI/Proper_Use_Layout/oh-package.json5
@@ -3,8 +3,5 @@
"description": "Please describe the basic information.",
"dependencies": {
},
- "devDependencies": {
- "@ohos/hypium": "1.0.21",
- "@ohos/hamock": "1.0.0"
- }
+ "devDependencies": {}
}
diff --git a/ArkUI/Proper_Use_Layout/screenshots/Screenshot.jpeg b/ArkUI/Proper_Use_Layout/screenshots/Screenshot.jpeg
deleted file mode 100644
index 5c4d3548c337cfa452db36ff85aa23a952e0afd7..0000000000000000000000000000000000000000
Binary files a/ArkUI/Proper_Use_Layout/screenshots/Screenshot.jpeg and /dev/null differ
diff --git a/ArkUI/PureTabsExt/README.md b/ArkUI/PureTabsExt/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..fdd98fc080aae135424c3b0faef31e68194d3c2a
--- /dev/null
+++ b/ArkUI/PureTabsExt/README.md
@@ -0,0 +1,61 @@
+# Tabs开发实践案例-补充案例
+### 简介
+ 本示例主要Tabs组件常用的场景实践示例的补充内容,补充了TabsBar显示效果相关的子场景,包含TabBar背景模糊效果、页签超出TabBar区域显示、TabBar边缘渐隐、TabBar偏移、切换指定页签等场景。
+
+### 效果预览
+| TabBar背景模糊效果 | 页签超出TabBar区域显示,TabBar边缘渐隐 | TabBar偏移 | 切换指定页签 |
+|--------------------------------------------|--------------------------------------------|--------------------------------------|-------------------------------------|
+|  |  |  |  |
+### 工程目录
+```
+├──entry/src/main/ets // 代码区
+│ ├──common
+│ │ └──constant
+│ │ └──Constants.ets // 常量类
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets
+│ ├──pages
+│ │ └──Index.ets // 入口页
+│ └──view
+│ ├──InTabComponent.ets // 设置TabBar偏移量及透明度
+│ ├──OutTabComponent.ets // 页签超出TabBar区域显示
+│ ├──SearchBarComponent.ets // 搜索框
+│ └──SwitchTabComponent.ets // 切换至指定页签
+└──entry/src/main/resources // 应用资源目录
+```
+### 具体实现
+- TabBar背景模糊效果
+ 通过设置Tabs组件的barOverlap属性,可以实现TabBar变模糊并叠加在TabContent之上,并且配合barBackgroundBlurStyle属性实现毛玻璃效果。
+- 页签超出TabBar区域显示
+ 通过barModifier设置tabBar的clip属性,实现页签超出tabBar区域显示效果。
+- TabBar边缘渐隐
+ 通过配置fadingEdge(true)实现TabBar边缘渐隐。
+- TabBar偏移
+ 通过TabsController的setTabBarTranslate()、setTabBarOpacity()方法可以设置TabBar偏移量及透明度。
+- 切换指定页签
+ Tabs组件除了自带的滑动切换和点击切换功能外,还提供了两种可编程方式来切换页签。第一种是通过调用TabsController的changeIndex()方法,切换到指定的index;第二种是定义一个由@State修饰的变量currentIndex,并将其绑定到Tabs,通过修改currentIndex的值来触发页签切换。
+
+### 相关权限
+无
+
+### 约束与限制
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/PureTabsExt
+git checkout
+```
diff --git a/ArkUI/PureTabsExt/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/PureTabsExt/entry/src/main/ets/entryability/EntryAbility.ets
index d3ee54d2beea61d38866762868bd056d3e39e3c9..6e8ddad71a3f9ef705cc39a675342118ec298ffd 100644
--- a/ArkUI/PureTabsExt/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/PureTabsExt/entry/src/main/ets/entryability/EntryAbility.ets
@@ -14,6 +14,7 @@
*/
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -21,7 +22,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ArkUI/PureTabsExt/entry/src/main/ets/view/InTabComponent.ets b/ArkUI/PureTabsExt/entry/src/main/ets/view/InTabComponent.ets
index 95476169b1cf53aa29d639b0bb914a0e9189d0f4..81999269719c8423601719861109f4c5a6cc2673 100644
--- a/ArkUI/PureTabsExt/entry/src/main/ets/view/InTabComponent.ets
+++ b/ArkUI/PureTabsExt/entry/src/main/ets/view/InTabComponent.ets
@@ -12,7 +12,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-import { AbilityConstant,Configuration } from "@kit.AbilityKit";
+import { AbilityConstant, common,Configuration } from "@kit.AbilityKit";
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from "@kit.PerformanceAnalysisKit";
// [Start tabs_bar_translate]
@Component
@@ -38,10 +40,13 @@ export default struct InTabComponent {
}
private async updateTabItems(){
- await this.getUIContext().getHostContext()?.resourceManager.getStringArrayValue($r('app.strarray.in_tabs_items'))
+ await this.getUIContext().getHostContext()?.resourceManager.getStringArrayValue($r('app.strarray.in_tabs_items').id)
.then((strarray: string[]) => {
this.tabItems = strarray;
- });
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `getStringArrayValue failed, code=${err.code}, message=${err.message}`)
+ })
}
subscribeSystemLanguageUpdate() {
diff --git a/ArkUI/PureTabsExt/entry/src/main/ets/view/SwitchTabComponent.ets b/ArkUI/PureTabsExt/entry/src/main/ets/view/SwitchTabComponent.ets
index 03adf3c67f746e3df24c07e84a6b43595957b9f3..e2528a293becb424feb6926c7ecbd0dfba35af70 100644
--- a/ArkUI/PureTabsExt/entry/src/main/ets/view/SwitchTabComponent.ets
+++ b/ArkUI/PureTabsExt/entry/src/main/ets/view/SwitchTabComponent.ets
@@ -13,7 +13,8 @@
* limitations under the License.
*/
import { AbilityConstant, Configuration } from "@kit.AbilityKit";
-import { Constants } from "../common/constant/Constants";
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from "@kit.PerformanceAnalysisKit";
// [Start custom_switch_tab]
@Component
@@ -32,10 +33,13 @@ export default struct SwitchTabComponent {
private async updateTabItems() {
await this.getUIContext()
- .getHostContext()?.resourceManager.getStringArrayValue($r('app.strarray.switch_tabs_items'))
+ .getHostContext()?.resourceManager.getStringArrayValue($r('app.strarray.switch_tabs_items').id)
.then((strarray: string[]) => {
this.tabItems = strarray;
- });
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `getStringArrayValue failed, code=${err.code}, message=${err.message}`)
+ })
}
subscribeSystemLanguageUpdate() {
diff --git a/ArkUI/PureTabsExt/entry/src/main/module.json5 b/ArkUI/PureTabsExt/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..44c5e49d8129f5d5bcc87ee6768d4a007d4877ca 100644
--- a/ArkUI/PureTabsExt/entry/src/main/module.json5
+++ b/ArkUI/PureTabsExt/entry/src/main/module.json5
@@ -6,8 +6,6 @@
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
- "tablet",
- "2in1"
],
"deliveryWithInstall": true,
"installationFree": false,
diff --git a/ArkTS_high_performance_segment/.gitignore b/ArkUI/StateManagement/.gitignore
similarity index 100%
rename from ArkTS_high_performance_segment/.gitignore
rename to ArkUI/StateManagement/.gitignore
diff --git a/ArkUI/StateManagement/AppScope/app.json5 b/ArkUI/StateManagement/AppScope/app.json5
new file mode 100644
index 0000000000000000000000000000000000000000..555e16abacdd36eb1771ceff940174bfe7e8faf2
--- /dev/null
+++ b/ArkUI/StateManagement/AppScope/app.json5
@@ -0,0 +1,10 @@
+{
+ "app": {
+ "bundleName": "com.example.statemanagement",
+ "vendor": "example",
+ "versionCode": 1000000,
+ "versionName": "1.0.0",
+ "icon": "$media:layered_image",
+ "label": "$string:app_name"
+ }
+}
diff --git a/ArkUI/StateManagement/AppScope/resources/base/element/string.json b/ArkUI/StateManagement/AppScope/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..f2aaa15ddeb29f99e8453bc919d10efcf44d0361
--- /dev/null
+++ b/ArkUI/StateManagement/AppScope/resources/base/element/string.json
@@ -0,0 +1,8 @@
+{
+ "string": [
+ {
+ "name": "app_name",
+ "value": "StateManagement"
+ }
+ ]
+}
diff --git a/MultiVideoApplication/AppScope/resources/base/media/background.png b/ArkUI/StateManagement/AppScope/resources/base/media/background.png
similarity index 100%
rename from MultiVideoApplication/AppScope/resources/base/media/background.png
rename to ArkUI/StateManagement/AppScope/resources/base/media/background.png
diff --git a/MultiVideoApplication/products/phone/src/main/resources/base/media/foreground.png b/ArkUI/StateManagement/AppScope/resources/base/media/foreground.png
similarity index 100%
rename from MultiVideoApplication/products/phone/src/main/resources/base/media/foreground.png
rename to ArkUI/StateManagement/AppScope/resources/base/media/foreground.png
diff --git a/MultiCommunityApplication/AppScope/resources/base/media/layered_image.json b/ArkUI/StateManagement/AppScope/resources/base/media/layered_image.json
similarity index 100%
rename from MultiCommunityApplication/AppScope/resources/base/media/layered_image.json
rename to ArkUI/StateManagement/AppScope/resources/base/media/layered_image.json
diff --git a/ArkUI/StateManagement/LICENSE b/ArkUI/StateManagement/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..18795a48d6b12fcdc1aa7bac9a9cb99f83815267
--- /dev/null
+++ b/ArkUI/StateManagement/LICENSE
@@ -0,0 +1,78 @@
+ Copyright (c) 2025 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/ArkUI/StateManagement/README.md b/ArkUI/StateManagement/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..58903262d186e9383751d7479108a5a2a42c258f
--- /dev/null
+++ b/ArkUI/StateManagement/README.md
@@ -0,0 +1,34 @@
+# 状态管理最佳实践
+
+### 介绍
+
+本示例通过ArkUI状态管理@State、@Prop、@Link、@Observed等装饰器,实现不同页面之间状态同步情景和应用的数据状态管理情景。帮助开发者掌握应用的数据状态同步处理。
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1.本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2.HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3.DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4.HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/StateManagement
+git checkout
+```
diff --git a/ArkUI/StateManagement/build-profile.json5 b/ArkUI/StateManagement/build-profile.json5
new file mode 100644
index 0000000000000000000000000000000000000000..9e87e7e6f19020fe21192844709f192cec80fd44
--- /dev/null
+++ b/ArkUI/StateManagement/build-profile.json5
@@ -0,0 +1,42 @@
+{
+ "app": {
+ "signingConfigs": [],
+ "products": [
+ {
+ "name": "default",
+ "signingConfig": "default",
+ "targetSdkVersion": "5.0.5(17)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "runtimeOS": "HarmonyOS",
+ "buildOption": {
+ "strictMode": {
+ "caseSensitiveCheck": true,
+ "useNormalizedOHMUrl": true
+ }
+ }
+ }
+ ],
+ "buildModeSet": [
+ {
+ "name": "debug",
+ },
+ {
+ "name": "release"
+ }
+ ]
+ },
+ "modules": [
+ {
+ "name": "entry",
+ "srcPath": "./entry",
+ "targets": [
+ {
+ "name": "default",
+ "applyToProducts": [
+ "default"
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/code-linter.json5 b/ArkUI/StateManagement/code-linter.json5
similarity index 100%
rename from ArkUI/orientationDevelopment/code-linter.json5
rename to ArkUI/StateManagement/code-linter.json5
diff --git a/ArkUI/Component_Nesting_Optimization/entry/.gitignore b/ArkUI/StateManagement/entry/.gitignore
similarity index 100%
rename from ArkUI/Component_Nesting_Optimization/entry/.gitignore
rename to ArkUI/StateManagement/entry/.gitignore
diff --git a/Privacy/ContactData/build-profile.json5 b/ArkUI/StateManagement/entry/build-profile.json5
similarity index 100%
rename from Privacy/ContactData/build-profile.json5
rename to ArkUI/StateManagement/entry/build-profile.json5
diff --git a/ArkUI/StateManagement/entry/hvigorfile.ts b/ArkUI/StateManagement/entry/hvigorfile.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b0e3a1ab98a91bc918d6404b2413111a5011f14a
--- /dev/null
+++ b/ArkUI/StateManagement/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. */
+}
\ No newline at end of file
diff --git a/Privacy/ContactData/obfuscation-rules.txt b/ArkUI/StateManagement/entry/obfuscation-rules.txt
similarity index 100%
rename from Privacy/ContactData/obfuscation-rules.txt
rename to ArkUI/StateManagement/entry/obfuscation-rules.txt
diff --git a/CrossPlatformCompatibility/entry/oh-package.json5 b/ArkUI/StateManagement/entry/oh-package.json5
similarity index 100%
rename from CrossPlatformCompatibility/entry/oh-package.json5
rename to ArkUI/StateManagement/entry/oh-package.json5
diff --git a/ArkUI/StateManagement/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/StateManagement/entry/src/main/ets/entryability/EntryAbility.ets
new file mode 100644
index 0000000000000000000000000000000000000000..508880af8c33aa838016d1cd4b2c68be2f447540
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/entryability/EntryAbility.ets
@@ -0,0 +1,44 @@
+import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { window } from '@kit.ArkUI';
+
+const DOMAIN = 0x0000;
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
+ }
+
+ onDestroy(): void {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
+ }
+
+ onWindowStageCreate(windowStage: window.WindowStage): void {
+ // Main window is created, set main page for this ability
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
+
+ windowStage.loadContent('pages/Index', (err) => {
+ if (err.code) {
+ hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
+ return;
+ }
+ hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
+ });
+ }
+
+ onWindowStageDestroy(): void {
+ // Main window is destroyed, release UI related resources
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
+ }
+
+ onForeground(): void {
+ // Ability has brought to foreground
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
+ }
+
+ onBackground(): void {
+ // Ability has back to background
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
+ }
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/ArkUI/StateManagement/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
new file mode 100644
index 0000000000000000000000000000000000000000..8e4de99282050bad799ac892eb85ac5449364a51
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
@@ -0,0 +1,16 @@
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
+
+const DOMAIN = 0x0000;
+
+export default class EntryBackupAbility extends BackupExtensionAbility {
+ async onBackup() {
+ hilog.info(DOMAIN, 'testTag', 'onBackup ok');
+ await Promise.resolve();
+ }
+
+ async onRestore(bundleVersion: BundleVersion) {
+ hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion));
+ await Promise.resolve();
+ }
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/pages/Index.ets b/ArkUI/StateManagement/entry/src/main/ets/pages/Index.ets
new file mode 100644
index 0000000000000000000000000000000000000000..633adadd00282a226ff7901c1d9e32a19e85d144
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/pages/Index.ets
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Entry
+@Component
+struct Index {
+ private buttonList: string[] =
+ Array.from({ length: 12 }, (_: number, i: number) => `Segment${i + 1}`);
+ @Provide("appPathStack") appPathStack: NavPathStack = new NavPathStack();
+ @Provide("discoverPathStack") discoverPathStack: NavPathStack = new NavPathStack();
+
+ build() {
+ Navigation(this.appPathStack) {
+ List({ space: 12 }) {
+ ForEach(this.buttonList, (item: string) => {
+ ListItem() {
+ Button(item).onClick(() => this.appPathStack.pushPathByName(item, null));
+ }
+ }, (item: string) => item)
+ }
+ .width('100%')
+ .height('100%')
+ .alignListItem(ListItemAlign.Center)
+ }
+ .mode(NavigationMode.Stack)
+ .height('100%')
+ .width('100%')
+ }
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment.ets
new file mode 100644
index 0000000000000000000000000000000000000000..90d01106be3521aba361fb5f63de6decafa920f4
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment.ets
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment01Builder() {
+ NavDestination(){
+ MyComponent()
+ }
+}
+
+// [Start Counter_example1_start]
+@Observed
+class Translate {
+ translateX: number = 20;
+}
+
+@Component
+struct MyComponent {
+ @State translateObj: Translate = new Translate(); // The variable translateObj is not associated with any UI component and should not be defined as a state variable
+ @State buttonMsg: string = 'I am button'; // The variable buttonMsg is not associated with any UI component and should not be defined as a state variable
+ build() {
+ }
+}
+// [End Counter_example1_start]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment10.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment10.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a0763e90c13a47f0817efe4ec9d4934eef9ccf9e
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment10.ets
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Builder
+export function Segment10Builder() {
+ NavDestination(){
+ Index()
+ }
+}
+// [Start Counter_example5]
+@Component
+struct Index {
+ @State currentIndex: number = 0; // The subscript of the currently selected list item
+ private listData: string[] = [];
+
+
+ aboutToAppear(): void {
+ for (let i = 0; i < 10; i++) {
+ this.listData.push(`${i}`);
+ }
+ }
+
+
+ build() {
+ Row() {
+ Column() {
+ List() {
+ ForEach(this.listData, (item: string, index: number) => {
+ ListItem() {
+ ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
+ }
+ })
+ }
+ .alignListItem(ListItemAlign.Center)
+ }
+ .width('100%')
+ }
+ .height('100%')
+ }
+}
+
+
+@Component
+struct ListItemComponent {
+ @Prop item: string;
+ @Prop index: number; // The subscript of the list item
+ @Link currentIndex: number;
+ private sizeFont: number = 50;
+
+
+ isRender(): number {
+ console.info(`ListItemComponent ${this.index} Text is rendered`);
+ return this.sizeFont;
+ }
+
+
+ build() {
+ Column() {
+ Text(this.item)
+ .fontSize(this.isRender())// Dynamically set the color of the text according to the difference between the index and currentIndex of the current list item.
+ .fontColor(Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue)
+ .onClick(() => {
+ this.currentIndex = this.index;
+ })
+ }
+ }
+}
+// [End Counter_example5]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment11.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment11.ets
new file mode 100644
index 0000000000000000000000000000000000000000..e611c0d9f6abcb1b87b978219a50cdd98e9935b5
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment11.ets
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Builder
+export function Segment11Builder() {
+ NavDestination(){
+ UseWatchListener()
+ }
+}
+// [Start Case7]
+@Entry
+@Component
+struct UseWatchListener {
+ @State currentIndex: number = 0; // The subscript of the currently selected list item
+ private listData: string[] = [];
+ aboutToAppear(): void {
+ for (let i = 0; i < 10; i++) {
+ this.listData.push(`${i}`);
+ }
+ }
+ build() {
+ Row() {
+ Column() {
+ List() {
+ ForEach(this.listData, (item: string, index: number) => {
+ ListItem() {
+ ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
+ }
+ })
+ }
+ .height('100%')
+ .width('100%')
+ .alignListItem(ListItemAlign.Center)
+ }
+ .width('100%')
+ }
+ .height('100%')
+ }
+}
+@Component
+struct ListItemComponent {
+ @Prop item: string;
+ @Prop index: number; // The subscript of the list item
+ @Link @Watch('onCurrentIndexUpdate') currentIndex: number;
+ @State color: Color = Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue;
+ isRender(): number {
+ console.info(`ListItemComponent ${this.index} Text is rendered`);
+ return 50;
+ }
+ onCurrentIndexUpdate() {
+ // Dynamically modifies the value of color based on the difference between the index and currentIndex of the current list item.
+ this.color = Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue;
+ }
+ build() {
+ Column() {
+ Text(this.item)
+ .fontSize(this.isRender())
+ .fontColor(this.color)
+ .onClick(() => {
+ this.currentIndex = this.index;
+ })
+ }
+ }
+}
+// [End Case7]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment12.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment12.ets
new file mode 100644
index 0000000000000000000000000000000000000000..07d106c3f27da228fb75c780475ba5e06e78a4ac
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment12.ets
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+// [Start Case8]
+import { ButtonComponent } from '../segment/segment13';
+import { ListItemComponent } from '../segment/segment14';
+@Entry
+@Component
+struct UseEmitterPublish {
+ listData: string[] = ['A', 'B', 'C', 'D', 'E', 'F'];
+ build() {
+ Column() {
+ Row() {
+ Column() {
+ ButtonComponent()
+ }
+ }
+ Column() {
+ Column() {
+ List() {
+ ForEach(this.listData, (item: string, index: number) => {
+ ListItemComponent({ myItem: item, index: index })
+ })
+ }
+ .height('100%')
+ .width('100%')
+ .alignListItem(ListItemAlign.Center)
+ }
+ }
+ }
+ }
+}
+// [End Case8]
+@Builder
+export function Segment12Builder() {
+ NavDestination(){
+ UseEmitterPublish()
+ }
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment13.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment13.ets
new file mode 100644
index 0000000000000000000000000000000000000000..5acd363a25e1fbe438dd152b11d2d3d55bb78434
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment13.ets
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+// [Start Case9]
+import { emitter } from '@kit.BasicServicesKit';
+const CHANGE_COLOR_EVENT_ID = 1;
+@Component
+export struct ButtonComponent {
+ value: number = 2;
+ build() {
+ Button(`下标是${this.value}的倍数的组件文字变为红色`)
+ .onClick(() => {
+ let event: emitter.InnerEvent = {
+ eventId: CHANGE_COLOR_EVENT_ID,
+ priority: emitter.EventPriority.LOW
+ };
+ let eventData: emitter.EventData = {
+ data: {
+ value: this.value
+ }
+ };
+ // Sends an event with eventId of CHANGE_COLOR_EVENT_ID and event content of eventData
+ emitter.emit(event, eventData);
+ this.value++;
+ })
+ }
+}
+// [End Case9]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment14.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment14.ets
new file mode 100644
index 0000000000000000000000000000000000000000..f82a457d79d29d2665e9baac6473a0d6de45371d
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment14.ets
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+// [Start Case10]
+import { emitter } from '@kit.BasicServicesKit';
+const CHANGE_COLOR_EVENT_ID = 1;
+@Component
+export struct ListItemComponent {
+ @State color: Color = Color.Black;
+ @Prop index: number;
+ @Prop myItem: string;
+ aboutToAppear(): void {
+ let event: emitter.InnerEvent = {
+ eventId: CHANGE_COLOR_EVENT_ID
+ };
+ // Execute this callback after receiving an event with eventId of CHANGE_COLOR_EVENT_ID
+ let callback = (eventData: emitter.EventData): void => {
+ if (eventData.data?.value !== 0 && this.index % eventData.data?.value === 0) {
+ this.color = Color.Red;
+ }
+ };
+ // Subscribe to events with eventId of CHANGE_COLOR_EVENT_ID
+ emitter.on(event, callback);
+ }
+ build() {
+ Column() {
+ Text(this.myItem)
+ .fontSize(50)
+ .fontColor(this.color)
+ }
+ }
+}
+// [End Case10]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment2.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment2.ets
new file mode 100644
index 0000000000000000000000000000000000000000..d7d88d7929bb146ed9d5bde52fa93a6d7a800992
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment2.ets
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment02Builder() {
+ NavDestination(){
+ MyComponent()
+ }
+}
+// [Start Counter_example2_start]
+@Observed
+class Translate {
+ translateX: number = 20;
+}
+
+@Component
+struct MyComponent {
+ @State translateObj: Translate = new Translate();
+ @State buttonMsg: string = 'I am button';
+ build() {
+ Column() {
+ Button(this.buttonMsg) // Here we just read the value of the variable buttonMsg, without any write operation.
+ }
+ }
+}
+// [End Counter_example2_start]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment3.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment3.ets
new file mode 100644
index 0000000000000000000000000000000000000000..833ab40910d6fb4154911c9c20c40591c9b9b503
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment3.ets
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Builder
+export function Segment03Builder() {
+ NavDestination(){
+ UnnecessaryState1()
+ }
+}
+// [Start Case1_start]
+@Observed
+class Translate {
+ translateX: number = 20;
+}
+
+@Component
+struct UnnecessaryState1 {
+ @State translateObj: Translate = new Translate(); // If there are both read and write operations and a Button component is associated with it, it is recommended to use state variables.
+ buttonMsg = 'I am button'; // Only read the value of the variable buttonMsg, without any write operations, just use the general variables directly
+ build() {
+ Column() {
+ Button(this.buttonMsg)
+ .onClick(() => {
+ this.getUIContext().animateTo({
+ duration: 50
+ }, () => {
+ this.translateObj.translateX = (this.translateObj.translateX + 50) % 150; // Reassign value to variable translateObj when clicked.
+ })
+ })
+ }
+ .translate({
+ x: this.translateObj.translateX // Retrieve the value in translateObj.
+ })
+ }
+}
+// [End Case1_start]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment4.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment4.ets
new file mode 100644
index 0000000000000000000000000000000000000000..21f5a4df2ffd5e877f367455afc9c85307a896f9
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment4.ets
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment04Builder() {
+ NavDestination(){
+ Index()
+ }
+}
+// [Start counter_example]
+
+@Component
+struct Index {
+ @State message: string = '';
+ // Define methods for changing state variables (multiple modifications of state variables)
+ appendMsg(newMsg: string) {
+ this.message += newMsg;
+ this.message += ';';
+ this.message += ' ';
+ }
+ build() {
+ Column() {
+ Button('Click Print Log')
+ .onClick(() => {
+ this.appendMsg('Operational state variables'); // Calling encapsulated methods for changing state variables
+ })
+ .width('90%')
+ .backgroundColor(Color.Blue)
+ .fontColor(Color.White)
+ .margin({ top: 10})
+ }
+ .justifyContent(FlexAlign.Start)
+ .alignItems(HorizontalAlign.Center)
+ .margin({ top: 15 })
+ }
+}
+// [End counter_example]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment5.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment5.ets
new file mode 100644
index 0000000000000000000000000000000000000000..c05f303c48e006387e25e7fd6ec90aa48174cfc2
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment5.ets
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment05Builder() {
+ NavDestination(){
+ UnnecessaryState2()
+ }
+}
+// [Start Case2_start]
+@Entry
+@Component
+struct UnnecessaryState2 {
+ @State message: string = '';
+ // Define methods for changing state variables (intermediate variables are manipulated during method execution, state variables are modified only once)
+ appendMsg(newMsg: string) {
+ let message = this.message;
+ message += newMsg;
+ message += ';';
+ message += ' ';
+ this.message = message;
+ }
+ build() {
+ Column() {
+ Button('Click Print Log')
+ .onClick(() => {
+ this.appendMsg('Manipulating Temporary Variables'); // Calling encapsulated methods for changing state variables
+ })
+ .width('90%')
+ .backgroundColor(Color.Blue)
+ .fontColor(Color.White)
+ .margin({ top: 10 })
+ }
+ .justifyContent(FlexAlign.Start)
+ .alignItems(HorizontalAlign.Center)
+ .margin({ top: 15 })
+ }
+}
+// [End Case2_start]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment6.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment6.ets
new file mode 100644
index 0000000000000000000000000000000000000000..42beb0647c32f1c87f156443ab02d8c01cb687d7
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment6.ets
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment06Builder() {
+ NavDestination(){
+ UserInfoView()
+ }
+}
+
+interface IUserAccountRepository {
+ getUserData(): Promise;
+}
+// [Start Case3_start]
+// Data structure of user information UserData
+export interface UserData {
+ id: string;
+ username: string;
+ description: string;
+ // ...
+}
+// [StartExclude Case3_start]
+class bb {
+ private userAccountRepository: IUserAccountRepository;
+
+ constructor(repository: IUserAccountRepository) {
+ this.userAccountRepository = repository;
+ }
+ // [EndExclude Case3_start]
+ // Getting server-side user information in a business class
+ getUserData(): void {
+ this.userAccountRepository.getUserData().then((data: UserData) => {
+ // 1.Storing user information data into AppStorage
+ AppStorage.setOrCreate('userData', data);
+ });
+ }
+ // [StartExclude Case3_start]
+}
+// [EndExclude Case3_start]
+// View component for displaying user information at the top of the “My” module
+@Component
+struct UserInfoView {
+ // 2.Receive user information stored in AppStorage using @StorageLink decorator in UI
+ @StorageLink('userData') userData: UserData | null = null;
+ build() {
+ Column() {
+ Row() {
+ // ...
+ Column() {
+ // 3.Display the user name in the userData.
+ Text(this.userData ? this.userData.username : 'default_login')
+ // ...
+ }
+ }
+ // ...
+ }
+ // ...
+ }
+}
+// [End Case3_start]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment7.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment7.ets
new file mode 100644
index 0000000000000000000000000000000000000000..4e6961c9a3ec328f373b0c61f1913aae8a27340c
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment7.ets
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment07Builder() {
+ NavDestination(){
+ ArticleCardView()
+ }
+}
+interface IUserAccountRepository {
+ getUserData(): Promise;
+}
+
+export class LearningResource {
+ id: string = "";
+ collectionCount: number = 0;
+}
+
+@Component
+struct ActionButtonView {
+ imgResource: Resource = $r("app.media.icon");
+ count: number = 0;
+ textWidth: number = 0;
+
+ build() {
+ Column() {
+ Image(this.imgResource)
+ .width(this.textWidth)
+ Text(this.count.toString())
+ }
+ .alignItems(HorizontalAlign.Center)
+ }
+}
+
+// [Start Case4]
+export interface UserData {
+ id: string;
+ username: string;
+ description: string;
+
+ // 1. Add a list of resources in the user's collection on the user information UserData id Information Type Definition
+ collectedIds: string[];
+ // ...
+}
+// [StartExclude Case4]
+class cc {
+ private userAccountRepository: IUserAccountRepository;
+
+ constructor(repository: IUserAccountRepository) {
+ this.userAccountRepository = repository;
+ }
+ // [EndExclude Case4]
+ // Getting server-side user information in a business class
+ getUserData(): void {
+ this.userAccountRepository.getUserData().then((data: UserData) => {
+ // 2.Storing user information data into AppStorage
+ AppStorage.setOrCreate('userData', data);
+ })
+ }
+ // [StartExclude Case4]
+}
+// [EndExclude Case4]
+
+// Article card component of the Explore module
+@Component
+export struct ArticleCardView {
+ // 3.Get the user information object userData on the ExploreArticleList card with the @StorageLink decorator
+ @StorageLink('userData') userData: UserData | null = null;
+ @Prop articleItem: LearningResource = new LearningResource();
+
+ // 4.Calculate whether the current article is favorite or not according to the favorite information array
+ isCollected(): boolean {
+ return !!this.userData && this.userData.collectedIds.some((id: string) => id === this.articleItem.id);
+ }
+
+ // 7.Handling interface like interaction logic: when the userData state sub-property collectedIds received using the @StorageLink decorator is modified, the new value is synchronized to AppStorage
+ handleCollected(): void {
+ // [StartExclude Case4]
+ const resourceId = this.articleItem.id;
+ // [EndExclude Case4]
+ const index = this.userData?.collectedIds.findIndex((id: string) => id === this.articleItem.id) as number;
+ if (index === -1) {
+ this.userData?.collectedIds.push(resourceId);
+ } else {
+ this.userData?.collectedIds.splice(index, 1);
+ }
+ // ...
+ }
+
+ build() {
+ ActionButtonView({
+ // 5.Determine whether the favorite icon is highlighted according to whether the current article has been favorited by the user or not
+ imgResource: this.isCollected() ? $r('app.media.icon') : $r('app.media.icon'),
+ count: this.articleItem.collectionCount,
+ textWidth: 77
+ })
+ .onClick(() => {
+ // 6.When the user clicks on the favorites icon, the function that handles changes to the status of the favorites is called
+ this.handleCollected();
+ })
+ }
+}
+// [End Case4]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment8.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment8.ets
new file mode 100644
index 0000000000000000000000000000000000000000..f00b3af02224556ee3cf6123002aecb91fe3f5ee
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment8.ets
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment08Builder() {
+ NavDestination(){
+ ArticleCardView()
+ }
+}
+@Component
+struct ActionButtonView {
+ imgResource: Resource = $r("app.media.icon");
+ count: number = 0;
+ textWidth: number = 0;
+
+ build() {
+ Column() {
+ Image(this.imgResource)
+ .width(this.textWidth)
+ Text(this.count.toString())
+ }
+ .alignItems(HorizontalAlign.Center)
+ }
+}
+
+export class LearningResource {
+ id: string = "";
+ collectionCount: number = 0;
+}
+
+interface IUserAccountRepository {
+ getUserData(): Promise;
+}
+
+export interface UserData {
+ id: string;
+ username: string;
+ description: string;
+ collectedIds: string[];
+}
+
+class dd {
+ private userAccountRepository: IUserAccountRepository;
+
+ constructor(repository: IUserAccountRepository) {
+ this.userAccountRepository = repository;
+ }
+ // [Start Case5]
+ // Getting user information in a business class
+ getUserData(): void {
+ this.userAccountRepository.getUserData().then((data: UserData) => {
+ //1.Separate storage of user collection information data in AppStorage
+ AppStorage.setOrCreate('collectedIds', data.collectedIds);
+ AppStorage.setOrCreate('userData', data);
+ })
+ }
+ // [End Case5]
+}
+
+// [Start Case5]
+// Article card component of the Explore module
+@Component
+export struct ArticleCardView {
+ // 2.Getting collection information stored in AppStorage via @StorageLink decorator
+ @StorageLink('collectedIds') collectedIds: string[] = [];
+ @Prop articleItem: LearningResource = new LearningResource();
+ // 3.Calculate whether the current article is favorite or not according to the favorite information array
+ isCollected(): boolean {
+ return this.collectedIds.some((id: string) => id === this.articleItem.id);
+ }
+ // 6.Handling interface like interaction logic: when the state collectedIds received using the @StorageLink decorator are modified, the new values are synchronized to AppStorage
+ handleCollected(): void {
+ // [StartExclude Case5]
+ const resourceId = this.articleItem.id;
+ // [EndExclude Case5]
+ const index = this.collectedIds.findIndex((id: string) => id === this.articleItem.id);
+ if (index === -1) {
+ this.collectedIds.push(resourceId);
+ } else {
+ this.collectedIds.splice(index, 1);
+ }
+ // ...
+ }
+ build(){
+ ActionButtonView({
+ // 4.Determine whether the favorite icon is highlighted according to whether the current article has been favorited by the user or not
+ imgResource: this.isCollected() ? $r('app.media.icon') : $r('app.media.icon'),
+ count: this.articleItem.collectionCount,
+ textWidth: 77
+ })
+ .onClick(() => {
+ // 5.When the user clicks on the favorites icon, the function that handles changes to the status of the favorites is called
+ this.handleCollected();
+ })
+ }
+}
+// [End Case5]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/ets/segment/segment9.ets b/ArkUI/StateManagement/entry/src/main/ets/segment/segment9.ets
new file mode 100644
index 0000000000000000000000000000000000000000..f436e5dcbb18765cb254671541778d2463123fa5
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/ets/segment/segment9.ets
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+@Builder
+export function Segment09Builder() {
+ NavDestination() {
+ DiscoverView()
+ }
+}
+
+export class LearningResource {
+ id: string = "";
+ collectionCount: number = 0;
+}
+
+export class CommonConstants {
+ static readonly SPACE_12: number = 12;
+}
+
+interface GeneratedTypeLiteralInterface_1 {
+ swiperData: LearningResource[];
+}
+
+@Component
+struct HotFeedsView {
+ @Prop hotFeedList: never[] = [];
+ showMore: () => void = () => {
+ };
+ handleClick: (item: LearningResource) => void = () => {
+ };
+
+ build() {
+ Column()
+ }
+}
+
+@Component
+struct TechArticlesView {
+ @Prop articlesDataSource: never[] = [];
+ handleClick: (item: LearningResource) => void = () => {
+ };
+
+ build() {
+ Column()
+ }
+}
+
+// [Start discover_view]
+@Component
+export struct DiscoverView {
+ // [StartExclude Case6]
+ private jumpList = () => {
+ }
+ @State hotFeedList: never[] = [];
+ @State articlesDataSource: never[] = [];
+ @State discoverModel: GeneratedTypeLiteralInterface_1 = { swiperData: [] };
+ // [EndExclude Case6]
+ // 1.Getting shared state related to jump logic
+ @Consume('appPathStack') appPathStack: NavPathStack;
+ @Consume('discoverPathStack') discoverPathStack: NavPathStack;
+ @StorageProp('currentBreakpoint') currentBreakpoint: string = 'BreakpointTypeEnum.MD';
+
+ // 5.Centralize the jump processing logic of the 3 components in the parent component
+ jumpDetail(item: LearningResource): void {
+ if (this.currentBreakpoint === 'BreakpointTypeEnum.LG') {
+ this.discoverPathStack.pushPathByName('articleDetail', item);
+ } else {
+ this.appPathStack.pushPathByName('articleDetail', item);
+ }
+ }
+
+ build() {
+ // [StartExclude Case6]
+ Column() {
+ List() {
+ ListItem() {
+ BannerView({
+ swiperData: this.discoverModel.swiperData,
+ // 2.The top rotator component passes in the parent component's logic handler function
+ handleClick: (item: LearningResource) => this.jumpDetail(item)
+ })
+ }
+ // [EndExclude Case6]
+ ListItem() {
+ Column({ space: CommonConstants.SPACE_12 }) {
+ HotFeedsView({
+ hotFeedList: this.hotFeedList,
+ showMore: this.jumpList,
+ // 3.Information list component passes in the logic handler function of the parent component
+ handleClick: (item: LearningResource) => this.jumpDetail(item)
+ })
+ TechArticlesView({
+ articlesDataSource: this.articlesDataSource,
+ // 4.Logic handler function passed to parent component by technical article component
+ handleClick: (item: LearningResource) => this.jumpDetail(item)
+ })
+ }
+ }
+ }
+ }
+ // [End Case6]
+ }
+}
+
+// [Start Case6]
+@Component
+struct BannerView {
+ @Prop swiperData: LearningResource[] = [];
+ private swiperController: SwiperController = new SwiperController();
+ // 6.The rotatoire component receives the logic handler passed to it by the parent component.
+ handleClick: (item: LearningResource) => void = () => {
+ };
+
+ build() {
+ Swiper(this.swiperController) {
+ ForEach(this.swiperData, (item: LearningResource) => {
+ Row() {
+ // $r('app.media.icon') needs to be replaced with the resource file required by the developer
+ Image($r('app.media.icon'))
+ .width(55)
+ .height(55)
+ // Set the border radius to 5vp
+ .borderRadius($r('app.float.component_radius'))
+ // 7.When clicking on an image, call the received function to process the logic
+ .onClick(() => this.handleClick(item))
+ }
+ // ...
+ }, (item: LearningResource) => item.id)
+ }
+ // ...
+ }
+}
+// [End discover_view]
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/module.json5 b/ArkUI/StateManagement/entry/src/main/module.json5
new file mode 100644
index 0000000000000000000000000000000000000000..e3043e123012d257b0cbe3486df843e11a205aa9
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/module.json5
@@ -0,0 +1,51 @@
+{
+ "module": {
+ "name": "entry",
+ "type": "entry",
+ "description": "$string:module_desc",
+ "mainElement": "EntryAbility",
+ "deviceTypes": [
+ "phone"
+ ],
+ "deliveryWithInstall": true,
+ "installationFree": false,
+ "pages": "$profile:main_pages",
+ "routerMap": "$profile:route_map",
+ "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/MultiDeviceCommunication/products/phone/src/main/resources/base/element/color.json b/ArkUI/StateManagement/entry/src/main/resources/base/element/color.json
similarity index 100%
rename from MultiDeviceCommunication/products/phone/src/main/resources/base/element/color.json
rename to ArkUI/StateManagement/entry/src/main/resources/base/element/color.json
diff --git a/ArkUI/StateManagement/entry/src/main/resources/base/element/float.json b/ArkUI/StateManagement/entry/src/main/resources/base/element/float.json
new file mode 100644
index 0000000000000000000000000000000000000000..4597c2b7452d28dae9f7582611272807909fb97a
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/resources/base/element/float.json
@@ -0,0 +1,68 @@
+{
+ "float": [
+ {
+ "name": "tips_font_size",
+ "value": "16"
+ },
+ {
+ "name": "source_code_font_size",
+ "value": "12"
+ },
+ {
+ "name": "circle_size",
+ "value": "40"
+ },
+ {
+ "name": "component_radius",
+ "value": "5"
+ },
+ {
+ "name": "button_text_size",
+ "value": "16"
+ },
+ {
+ "name": "button_height",
+ "value": "40"
+ },
+ {
+ "name": "border_width",
+ "value": "1"
+ },
+ {
+ "name": "title_bar_height",
+ "value": "60"
+ },
+ {
+ "name": "icon_back_size",
+ "value": "20"
+ },
+ {
+ "name": "page_padding",
+ "value": "12"
+ },
+ {
+ "name": "title_font_size",
+ "value": "18"
+ },
+ {
+ "name": "title_margin",
+ "value": "16"
+ },
+ {
+ "name": "divider_height",
+ "value": "1"
+ },
+ {
+ "name": "code_view_bottom",
+ "value": "20"
+ },
+ {
+ "name": "select_font_size",
+ "value": "16"
+ },
+ {
+ "name": "margin_bottom",
+ "value": "50vp"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/resources/base/element/string.json b/ArkUI/StateManagement/entry/src/main/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..f94595515a99e0c828807e243494f57f09251930
--- /dev/null
+++ b/ArkUI/StateManagement/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/MultiVideoApplication/products/phone/src/main/resources/base/media/background.png b/ArkUI/StateManagement/entry/src/main/resources/base/media/background.png
similarity index 100%
rename from MultiVideoApplication/products/phone/src/main/resources/base/media/background.png
rename to ArkUI/StateManagement/entry/src/main/resources/base/media/background.png
diff --git a/NativeSoIntegration/Ndk/src/main/resources/base/media/foreground.png b/ArkUI/StateManagement/entry/src/main/resources/base/media/foreground.png
similarity index 100%
rename from NativeSoIntegration/Ndk/src/main/resources/base/media/foreground.png
rename to ArkUI/StateManagement/entry/src/main/resources/base/media/foreground.png
diff --git a/MultMusicHome/features/live/src/main/resources/base/media/icon.png b/ArkUI/StateManagement/entry/src/main/resources/base/media/icon.png
similarity index 100%
rename from MultMusicHome/features/live/src/main/resources/base/media/icon.png
rename to ArkUI/StateManagement/entry/src/main/resources/base/media/icon.png
diff --git a/MultiCommunityApplication/products/phone/src/main/resources/base/media/layered_image.json b/ArkUI/StateManagement/entry/src/main/resources/base/media/layered_image.json
similarity index 100%
rename from MultiCommunityApplication/products/phone/src/main/resources/base/media/layered_image.json
rename to ArkUI/StateManagement/entry/src/main/resources/base/media/layered_image.json
diff --git a/CrossPlatformCompatibility/entry/src/main/resources/base/media/startIcon.png b/ArkUI/StateManagement/entry/src/main/resources/base/media/startIcon.png
similarity index 100%
rename from CrossPlatformCompatibility/entry/src/main/resources/base/media/startIcon.png
rename to ArkUI/StateManagement/entry/src/main/resources/base/media/startIcon.png
diff --git a/NativeSoIntegration/entry/src/main/resources/base/profile/backup_config.json b/ArkUI/StateManagement/entry/src/main/resources/base/profile/backup_config.json
similarity index 100%
rename from NativeSoIntegration/entry/src/main/resources/base/profile/backup_config.json
rename to ArkUI/StateManagement/entry/src/main/resources/base/profile/backup_config.json
diff --git a/MultMusicHome/products/phone/src/main/resources/base/profile/main_pages.json b/ArkUI/StateManagement/entry/src/main/resources/base/profile/main_pages.json
similarity index 100%
rename from MultMusicHome/products/phone/src/main/resources/base/profile/main_pages.json
rename to ArkUI/StateManagement/entry/src/main/resources/base/profile/main_pages.json
diff --git a/ArkUI/StateManagement/entry/src/main/resources/base/profile/route_map.json b/ArkUI/StateManagement/entry/src/main/resources/base/profile/route_map.json
new file mode 100644
index 0000000000000000000000000000000000000000..2332bd59ec9d30a1b2273dfc85b221c0100fdd61
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/resources/base/profile/route_map.json
@@ -0,0 +1,64 @@
+{
+ "routerMap": [
+ {
+ "name": "Segment1",
+ "pageSourceFile": "src/main/ets/segment/segment.ets",
+ "buildFunction": "Segment01Builder"
+ },
+ {
+ "name": "Segment2",
+ "pageSourceFile": "src/main/ets/segment/segment2.ets",
+ "buildFunction": "Segment02Builder"
+ },
+ {
+ "name": "Segment3",
+ "pageSourceFile": "src/main/ets/segment/segment3.ets",
+ "buildFunction": "Segment03Builder"
+ },
+ {
+ "name": "Segment4",
+ "pageSourceFile": "src/main/ets/segment/segment4.ets",
+ "buildFunction": "Segment04Builder"
+ },
+ {
+ "name": "Segment5",
+ "pageSourceFile": "src/main/ets/segment/segment5.ets",
+ "buildFunction": "Segment05Builder"
+ },
+ {
+ "name": "Segment6",
+ "pageSourceFile": "src/main/ets/segment/segment6.ets",
+ "buildFunction": "Segment06Builder"
+ },
+ {
+ "name": "Segment7",
+ "pageSourceFile": "src/main/ets/segment/segment7.ets",
+ "buildFunction": "Segment07Builder"
+ },
+ {
+ "name": "Segment8",
+ "pageSourceFile": "src/main/ets/segment/segment8.ets",
+ "buildFunction": "Segment08Builder"
+ },
+ {
+ "name": "Segment9",
+ "pageSourceFile": "src/main/ets/segment/segment9.ets",
+ "buildFunction": "Segment09Builder"
+ },
+ {
+ "name": "Segment10",
+ "pageSourceFile": "src/main/ets/segment/segment10.ets",
+ "buildFunction": "Segment10Builder"
+ },
+ {
+ "name": "Segment11",
+ "pageSourceFile": "src/main/ets/segment/segment11.ets",
+ "buildFunction": "Segment11Builder"
+ },
+ {
+ "name": "Segment12",
+ "pageSourceFile": "src/main/ets/segment/segment12.ets",
+ "buildFunction": "Segment12Builder"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/entry/src/main/resources/dark/element/color.json b/ArkUI/StateManagement/entry/src/main/resources/dark/element/color.json
new file mode 100644
index 0000000000000000000000000000000000000000..79b11c2747aec33e710fd3a7b2b3c94dd9965499
--- /dev/null
+++ b/ArkUI/StateManagement/entry/src/main/resources/dark/element/color.json
@@ -0,0 +1,8 @@
+{
+ "color": [
+ {
+ "name": "start_window_background",
+ "value": "#000000"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/hvigor/hvigor-config.json5 b/ArkUI/StateManagement/hvigor/hvigor-config.json5
new file mode 100644
index 0000000000000000000000000000000000000000..5bebc9755447385d82ce4138f54d991b1f85f348
--- /dev/null
+++ b/ArkUI/StateManagement/hvigor/hvigor-config.json5
@@ -0,0 +1,22 @@
+{
+ "modelVersion": "5.0.5",
+ "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/ArkUI/StateManagement/hvigorfile.ts b/ArkUI/StateManagement/hvigorfile.ts
new file mode 100644
index 0000000000000000000000000000000000000000..47113e2e36ecefde41c136272a0bd6ff745cffe4
--- /dev/null
+++ b/ArkUI/StateManagement/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. */
+}
\ No newline at end of file
diff --git a/ArkUI/StateManagement/oh-package.json5 b/ArkUI/StateManagement/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..f440d114b8a9d9aeadd0e891bba0d0d076e70936
--- /dev/null
+++ b/ArkUI/StateManagement/oh-package.json5
@@ -0,0 +1,7 @@
+{
+ "modelVersion": "5.0.5",
+ "description": "Please describe the basic information.",
+ "dependencies": {
+ },
+ "devDependencies": {}
+}
diff --git a/ArkUI/UI_Component_Performance_Optimization/README.md b/ArkUI/UI_Component_Performance_Optimization/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..c34a00fd467753eec993d7d34f89d821f94aeca3
--- /dev/null
+++ b/ArkUI/UI_Component_Performance_Optimization/README.md
@@ -0,0 +1,54 @@
+# UI组件性能优化同源示例代码
+
+### 介绍
+
+本示例代码为最佳实践《UI组件性能优化》配套示例代码。
+
+### 使用说明
+
+不涉及
+
+### 工程目录
+
+```
+├──entry/src/main/ets
+│ ├──components
+│ │ └──DiscoverView.ets // 程序入口类
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 数据备份恢复类
+│ └──pages
+│ ├──segment.ets // 避免在自定义组件的生命周期内执行高耗时操作:反例1
+│ ├──segment2.ets // 避免在自定义组件的生命周期内执行高耗时操作:正例1
+│ ├──segment3.ets // 避免在自定义组件的生命周期内执行高耗时操作:反例2
+│ ├──segment4.ets // 避免在自定义组件的生命周期内执行高耗时操作:正例2
+│ ├──segment5.ets // 按需注册组件属性同源代码:反例
+│ ├──segment6.ets // 按需注册组件属性同源代码:正例
+│ ├──segment7.ets // 优先使用@Builder方法代替自定义组件:反例
+│ ├──segment8.ets // 优先使用@Builder方法代替自定义组件:正例
+│ └──segment9.ets // 按需注册组件属性同源代码
+└──entry/src/main/resources // 应用资源目录
+```
+
+### 相关权限
+
+不涉及
+
+### 约束与限制
+
+* 本示例仅支持标准系统上运行,支持设备:华为手机。
+* HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+* DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+* HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/UI_Component_Performance_Optimization
+git checkout
+```
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..2880ca09588393e53ffafcdb1a11f66cdde90b4f 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,4 +1,5 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -6,7 +7,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/pages/Index.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/pages/Index.ets
index 8e2d24ad42693fc877d51bb7820f0a9da68fa135..6db84a6aab5bf5551c2d3347b36e88984529a63d 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/pages/Index.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/pages/Index.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
@Entry
@Component
struct Index {
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment.ets
index 039bda5ceed91007f03d34807fecdee17c185526..4704c9fb45be172a75926e80c87d7d1e637fd81f 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
interface VideoItem {
id: string;
}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment2.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment2.ets
index 7a121f36751fee30196f6d12c7cf13716a515886..0387711e0c56d43453896d18515089d5df534da8 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment2.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment2.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
interface VideoItem {
id: string;
}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment3.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment3.ets
index bd174e171860db3886f3fe52c6f39c0887feea8d..21ead008686725b558138723d28e0ac41c5062c9 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment3.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment3.ets
@@ -1,6 +1,22 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Counter_example2]
-import { hiTraceMeter } from '@kit.PerformanceAnalysisKit';
+import { hilog, hiTraceMeter } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
@@ -11,7 +27,12 @@ struct Index {
aboutToAppear(): void {
hiTraceMeter.startTrace('getStringSync', 1);
// The input parameter of the getStringSync interface uses the resource directly, without using the resource ID.
- this.context.resourceManager.getStringSync($r('app.string.app_name'));
+ try {
+ this.context.resourceManager.getStringSync($r('app.string.app_name'));
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `getStringSync failed, code=${err.code}, message=${err.message}`);
+ }
hiTraceMeter.finishTrace('getStringSync', 1);
}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment4.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment4.ets
index 0d67985f237d6452273361a7bbc6f4f649065200..39cba0d0ec295d212836984ee20c02a00ffd4ce8 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment4.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment4.ets
@@ -1,6 +1,22 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Case2]
-import { hiTraceMeter } from '@kit.PerformanceAnalysisKit';
+import { hilog, hiTraceMeter } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
@@ -11,8 +27,12 @@ struct Index {
aboutToAppear(): void {
hiTraceMeter.startTrace('getStringSyncAfter', 2);
// The input parameter of the getStringSync interface uses the resource ID.
-
- this.context.resourceManager.getStringSync($r('app.string.app_name').id);
+ try {
+ this.context.resourceManager.getStringSync($r('app.string.app_name').id);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `getStringSync failed, code=${err.code}, message=${err.message}`);
+ }
hiTraceMeter.finishTrace('getStringSyncAfter', 2);
}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment5.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment5.ets
index 3f43982e3ca8b1d6a2e2b62b9d9539828119a720..f5ca8fdc9e23275cb89cdf188cf2bdc1fa8d21cc 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment5.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment5.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Case3]
import { util } from '@kit.ArkTS';
@@ -26,8 +41,6 @@ const getUsers = () => {
});
}
-
-@Entry
@Component
export struct AvatarGrid {
@State users: User[] = getUsers();
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment6.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment6.ets
index b29dfa1b1e6ee326c642420700a3e8aaef63edb7..1d22d89f4c8db8c6f8705a2795c8a24382c6f034 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment6.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment6.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
@Observed
class User {
avatarImage: ResourceStr;
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment7.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment7.ets
index 188c5301f45f60f4ff4ac316cc821383e3038cc1..5389a92dd5e0e00b7239f71007b2d935e6b0f070 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment7.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment7.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
// [Start Case5]
import { util } from '@kit.ArkTS';
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment8.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment8.ets
index 1cf9b3d0248a19d4e864686f2037c80c395b3654..8054117cb3db3de27b433b8ee10b4c0088b7b974 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment8.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment8.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
interface User {
id: string;
name: string;
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment9.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment9.ets
index 28a75b39e42d9b54800d3c0254433a9783c0cc93..055b3e0f8ff2999176255511323a041f469c0b04 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment9.ets
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/ets/segment/segment9.ets
@@ -1,3 +1,18 @@
+/*
+* Copyright (C) 2025 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.
+*/
+
function convertColorSegmentsToString(name:string){
return name
}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/module.json5 b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..ad219d733f6afa5ea07f85f580208b08cc3b9041 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/module.json5
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/module.json5
@@ -5,9 +5,7 @@
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
- "phone",
- "tablet",
- "2in1"
+ "phone"
],
"deliveryWithInstall": true,
"installationFree": false,
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/resources/base/element/string.json b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..aff8f905a24cc896edb83c849b54a67bf34923a1 100644
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/main/resources/base/element/string.json
+++ b/ArkUI/UI_Component_Performance_Optimization/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "UIComponentPerformance"
}
]
}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/mock/mock-config.json5 b/ArkUI/UI_Component_Performance_Optimization/entry/src/mock/mock-config.json5
deleted file mode 100644
index 7a73a41bfdf76d6f793007240d80983a52f15f97..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/mock/mock-config.json5
+++ /dev/null
@@ -1,2 +0,0 @@
-{
-}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/ets/test/Ability.test.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/ets/test/Ability.test.ets
deleted file mode 100644
index 85c78f67579d6e31b5f5aeea463e216b9b141048..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/ets/test/Ability.test.ets
+++ /dev/null
@@ -1,35 +0,0 @@
-import { hilog } from '@kit.PerformanceAnalysisKit';
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function abilityTest() {
- describe('ActsAbilityTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- })
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- })
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- })
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- })
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- })
- })
-}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/ets/test/List.test.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/ets/test/List.test.ets
deleted file mode 100644
index 794c7dc4ed66bd98fa3865e07922906e2fcef545..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/ets/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import abilityTest from './Ability.test';
-
-export default function testsuite() {
- abilityTest();
-}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/module.json5 b/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/module.json5
deleted file mode 100644
index 55725a929993a8a18b3808d41ef037759440488b..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/ohosTest/module.json5
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "module": {
- "name": "entry_test",
- "type": "feature",
- "deviceTypes": [
- "phone",
- "tablet",
- "2in1"
- ],
- "deliveryWithInstall": true,
- "installationFree": false
- }
-}
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/test/List.test.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/test/List.test.ets
deleted file mode 100644
index bb5b5c3731e283dd507c847560ee59bde477bbc7..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import localUnitTest from './LocalUnit.test';
-
-export default function testsuite() {
- localUnitTest();
-}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/entry/src/test/LocalUnit.test.ets b/ArkUI/UI_Component_Performance_Optimization/entry/src/test/LocalUnit.test.ets
deleted file mode 100644
index 165fc1615ee8618b4cb6a622f144a9a707eee99f..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/entry/src/test/LocalUnit.test.ets
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function localUnitTest() {
- describe('localUnitTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- });
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- });
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- });
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- });
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- });
- });
-}
\ No newline at end of file
diff --git a/ArkUI/UI_Component_Performance_Optimization/oh-package-lock.json5 b/ArkUI/UI_Component_Performance_Optimization/oh-package-lock.json5
deleted file mode 100644
index c6f99f5c73b06c5fdef7ec6f491b74b7befebe2e..0000000000000000000000000000000000000000
--- a/ArkUI/UI_Component_Performance_Optimization/oh-package-lock.json5
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "meta": {
- "stableOrder": true
- },
- "lockfileVersion": 3,
- "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
- "specifiers": {
- "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0",
- "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21"
- },
- "packages": {
- "@ohos/hamock@1.0.0": {
- "name": "@ohos/hamock",
- "version": "1.0.0",
- "integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==",
- "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hamock/-/hamock-1.0.0.har",
- "registryType": "ohpm"
- },
- "@ohos/hypium@1.0.21": {
- "name": "@ohos/hypium",
- "version": "1.0.21",
- "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==",
- "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hypium/-/hypium-1.0.21.har",
- "registryType": "ohpm"
- }
- }
-}
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/.gitignore b/ArkUI/orientationDevelopment/.gitignore
deleted file mode 100644
index d2ff20141ceed86d87c0ea5d99481973005bab2b..0000000000000000000000000000000000000000
--- a/ArkUI/orientationDevelopment/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-/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/ArkUI/orientationDevelopment/README.md b/ArkUI/orientationDevelopment/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..493e9a6baaed2155ab4c401db2cf7afa6a515a4d
--- /dev/null
+++ b/ArkUI/orientationDevelopment/README.md
@@ -0,0 +1,53 @@
+# 多设备同源代码工程
+
+## 介绍
+
+本示例为窗口方向与多设备功能开发同源代码工程,包含最佳实践文档中包含的推荐使用方法的样例代码。工程本身不具备实际功能,开发者请直接阅读文档结合源码来理解多设备功能开发。
+
+## 效果预览
+
+不涉及。
+
+## 工程目录
+
+```
+entry/src/main/
+├──configautorotation // 窗口自动旋转
+├──configlandscapeauto // 窗口横屏
+├──configportrait // 窗口竖屏
+├──ets // 主目录
+└──resources // 资源目录
+```
+
+## 具体实现
+
+不涉及。
+
+## 相关权限
+
+不涉及。
+
+## 依赖
+
+不涉及。
+
+## 约束与限制
+
+1.本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2.HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3.DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4.HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+## 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ArkUI/orientationDevelopment
+git checkout
+```
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/build-profile.json5 b/ArkUI/orientationDevelopment/build-profile.json5
index 30857c313183c9cea23ffc9137be34d42de2f8c2..9e87e7e6f19020fe21192844709f192cec80fd44 100644
--- a/ArkUI/orientationDevelopment/build-profile.json5
+++ b/ArkUI/orientationDevelopment/build-profile.json5
@@ -5,8 +5,8 @@
{
"name": "default",
"signingConfig": "default",
- "targetSdkVersion": "5.1.0(18)",
- "compatibleSdkVersion": "5.0.3(15)",
+ "targetSdkVersion": "5.0.5(17)",
+ "compatibleSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/ArkUI/orientationDevelopment/entry/build-profile.json5 b/ArkUI/orientationDevelopment/entry/build-profile.json5
index 4d611879c7913fb0610c686e2399258ab3a6dad1..0311b505dbf43f0d22662c8d783c5f4464d15b15 100644
--- a/ArkUI/orientationDevelopment/entry/build-profile.json5
+++ b/ArkUI/orientationDevelopment/entry/build-profile.json5
@@ -20,9 +20,6 @@
"targets": [
{
"name": "default"
- },
- {
- "name": "ohosTest",
}
]
}
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/orientationDevelopment/entry/src/main/ets/entryability/EntryAbility.ets
index e8c03cc6c6e444af4f89db8e2e19222d6c589536..a9c879303eaf4476d0d4e70d152facf8775b76a1 100644
--- a/ArkUI/orientationDevelopment/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ArkUI/orientationDevelopment/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,12 +1,33 @@
-import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+/*
+ * 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 { ConfigurationConstant, UIAbility } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
- onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ onCreate(): void {
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ hilog.error(DOMAIN, 'testTag', '%{public}s',
+ `Failed to setColorMode. Cause code: ${error.code}, message: ${error.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
@@ -17,7 +38,10 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
- AppStorage.setOrCreate('mainWindow', windowStage.getMainWindow());
+ AppStorage.setOrCreate('mainWindow', windowStage.getMainWindow().catch((error: BusinessError) => {
+ hilog.error(DOMAIN, 'testTag', '%{public}s',
+ `Failed to getMainWindow. Cause code: ${error.code}, message: ${error.message}`);
+ }));
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
diff --git a/ArkUI/orientationDevelopment/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/ArkUI/orientationDevelopment/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
index 8e4de99282050bad799ac892eb85ac5449364a51..293e76aed652b84544ff154932a0ce9b60bfe9de 100644
--- a/ArkUI/orientationDevelopment/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
+++ b/ArkUI/orientationDevelopment/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets
@@ -1,5 +1,20 @@
-import { hilog } from '@kit.PerformanceAnalysisKit';
+/*
+ * 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 { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
const DOMAIN = 0x0000;
diff --git a/ArkUI/orientationDevelopment/entry/src/main/ets/pages/Index.ets b/ArkUI/orientationDevelopment/entry/src/main/ets/pages/Index.ets
index 1c7a6e8aafb095c7e79d163cd5bf9ff1af6efdde..148c0a8e2bfdce69389db03a76be4aaec59137ab 100644
--- a/ArkUI/orientationDevelopment/entry/src/main/ets/pages/Index.ets
+++ b/ArkUI/orientationDevelopment/entry/src/main/ets/pages/Index.ets
@@ -1,11 +1,31 @@
+/*
+ * 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.
+ */
+
// [Start enable_nfc]
import { nfcController } from '@kit.ConnectivityKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct Index {
// [StartExclude enable_nfc]
@State message: string = 'Hello World';
+
+ aboutToAppear(): void {
+ this.canIUseNfc();
+ }
// [EndExclude enable_nfc]
canIUseNfc(): void {
@@ -17,11 +37,14 @@ struct Index {
}
// [End caniuse_nfc_core]
// [EndExclude enable_nfc]
+ if (canIUse('SystemCapability.Communication.NFC.Core')){
try {
nfcController.enableNfc();
hilog.info(0x0000, 'Index', `nfcController enableNfc success`);
} catch (businessError) {
hilog.error(0x0000, 'Index', `nfcController enableNfc businessError: ${businessError}`);
+ }}else {
+ hilog.info(0x0000, 'Index', 'NFC not by this device.');
}
// [StartExclude enable_nfc]
}
diff --git a/ArkUI/orientationDevelopment/entry/src/main/ets/pages/OrientationPage.ets b/ArkUI/orientationDevelopment/entry/src/main/ets/pages/OrientationPage.ets
index 8b4022b387159e2ed1b76ecbe552cc9988db34bc..72e0ed10f9749da076c654256e9fcd7aa442986e 100644
--- a/ArkUI/orientationDevelopment/entry/src/main/ets/pages/OrientationPage.ets
+++ b/ArkUI/orientationDevelopment/entry/src/main/ets/pages/OrientationPage.ets
@@ -14,7 +14,7 @@ struct OrientationPage {
aboutToAppear() {
this.setOrientation(1);
let callback = async () => {
- let getDefaultDisplay = await display.getDefaultDisplaySync();
+ let getDefaultDisplay = display.getDefaultDisplaySync();
this.rotation = getDefaultDisplay.rotation;
this.message = ORIENTATION[this.rotation];
};
diff --git a/ArkUI/orientationDevelopment/entry/src/main/module.json5 b/ArkUI/orientationDevelopment/entry/src/main/module.json5
index f3a040d043f1fa5927db2c414ca731b7428f6231..1b7aac5b37b3cc701b01c64c5b44ae542c653811 100644
--- a/ArkUI/orientationDevelopment/entry/src/main/module.json5
+++ b/ArkUI/orientationDevelopment/entry/src/main/module.json5
@@ -60,6 +60,18 @@
}
]
}
+ ],
+ "requestPermissions": [
+ {
+ "name": "ohos.permission.MANAGE_SECURE_SETTINGS",
+ "reason": "$string:manage_secure_settings_reason",
+ "usedScene": {
+ "abilities": [
+ "FormAbility"
+ ],
+ "when": "inuse"
+ }
+ }
]
// [EndExclude module]
}
diff --git a/ArkUI/orientationDevelopment/entry/src/main/resources/base/element/string.json b/ArkUI/orientationDevelopment/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..9075650e024664fe588c4b836609f4d048de9d54 100644
--- a/ArkUI/orientationDevelopment/entry/src/main/resources/base/element/string.json
+++ b/ArkUI/orientationDevelopment/entry/src/main/resources/base/element/string.json
@@ -11,6 +11,10 @@
{
"name": "EntryAbility_label",
"value": "label"
+ },
+ {
+ "name": "manage_secure_settings_reason",
+ "value": "To enable NFC, you need to apply for this permission."
}
]
}
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/entry/src/ohosTest/ets/test/Ability.test.ets b/ArkUI/orientationDevelopment/entry/src/ohosTest/ets/test/Ability.test.ets
deleted file mode 100644
index 85c78f67579d6e31b5f5aeea463e216b9b141048..0000000000000000000000000000000000000000
--- a/ArkUI/orientationDevelopment/entry/src/ohosTest/ets/test/Ability.test.ets
+++ /dev/null
@@ -1,35 +0,0 @@
-import { hilog } from '@kit.PerformanceAnalysisKit';
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function abilityTest() {
- describe('ActsAbilityTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- })
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- })
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- })
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- })
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- })
- })
-}
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/entry/src/ohosTest/ets/test/List.test.ets b/ArkUI/orientationDevelopment/entry/src/ohosTest/ets/test/List.test.ets
deleted file mode 100644
index 794c7dc4ed66bd98fa3865e07922906e2fcef545..0000000000000000000000000000000000000000
--- a/ArkUI/orientationDevelopment/entry/src/ohosTest/ets/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import abilityTest from './Ability.test';
-
-export default function testsuite() {
- abilityTest();
-}
\ No newline at end of file
diff --git a/ArkUI/orientationDevelopment/entry/src/ohosTest/module.json5 b/ArkUI/orientationDevelopment/entry/src/ohosTest/module.json5
deleted file mode 100644
index cae0a4a066790141a32a4546bdc6976fa0a4225c..0000000000000000000000000000000000000000
--- a/ArkUI/orientationDevelopment/entry/src/ohosTest/module.json5
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "module": {
- "name": "entry_test",
- "type": "feature",
- "deviceTypes": [
- "phone",
- "tablet",
- "2in1",
- "wearable"
- ],
- "deliveryWithInstall": true,
- "installationFree": false
- }
-}
diff --git a/AvoidTimeComsume/README.md b/AvoidTimeComsume/README.md
index 454a1672429571f10324a4df9a851b7ee1a8f5de..4805fe672f81dc8efe1aa8ff0a47080ad8f288dc 100644
--- a/AvoidTimeComsume/README.md
+++ b/AvoidTimeComsume/README.md
@@ -1,10 +1,11 @@
# **主线程耗时操作优化指导**
## 介绍
在应用开发实践中,有效避免主线程执行冗余与易耗时操作是至关重要的策略。此举能有效降低主线程负载,提升UI的响应速度。面对高频回调接口在短时间内密集触发的场景,需要避免接口内的耗时操作,尽量保证主线程不被长时间占用,从而防止阻塞UI渲染,引发界面卡顿或掉帧现象。
-本实例结束开发过程中常见的冗余操作,常见的高频回调场景以及其他主线程优化思路。
+本实例介绍开发过程中常见的冗余操作,常见的高频回调场景以及其他主线程优化思路。
## 预览效果
-
+
+
## 工程目录
```
├──entry/src/main/ets // 代码区
@@ -16,7 +17,7 @@
│ │ └──EntryBackupAbility.ets
│ ├──pages
│ │ └──Index.ets // 首页
-│ └──views.ets
+│ └──views
│ ├──ConditionalRendering.ets // 条件渲染页
│ ├──GetStrOfId.ets // ID资源获取页
│ ├──GetStrOfResource.ets // 资源获取页
@@ -36,28 +37,40 @@
└──entry/src/main/resources // 应用资源目录
```
## 使用说明
-“避免冗余操作”的正例和反例,反例中包含release版本中冗余日志打印、Trace打点以及无业务代码的空回调,降低了性能。
-
-“高频回调场景中避免执行耗时操作”的正例和反例,以下常见高频回调场景中需要避免执行耗时操作:
-* 高频事件回调
-* 组件复用回调
-* 组件生命周期回调
-* 循环渲染
-* 组件属性
-
-反例中在高频事件中执行了上述耗时操作,降低了性能。
-
-“避免使用耗时接口”的正例和反例,反例中使用了没有指定资源id的接口,导致耗时增加,从而影响了性能。
-
-“使用多线程”是正例,开启多线程后,渲染页面速度加快,提升了性能。
+* 点击含有冗余操作按钮,进入二级页面。
+* 点击不含有冗余操作按钮,进入二级页面。
+* 点击组件复用反例按钮,进入二级页面,上下滑动,观察页面存在掉帧的现象。
+* 点击组件复用正例按钮,进入二级页面,上下滑动,页面滑动流畅。
+* 点击循环渲染反例按钮,进入二级页面,上下滑动,观察页面存在掉帧的现象。
+* 点击循环渲染正例按钮,进入二级页面,上下滑动,页面滑动流畅。
+* 点击组件属性反例按钮,进入二级页面,点击按钮,观察页面变化。
+* 点击组件属性正例按钮,进入二级页面,点击按钮,观察页面变化。
+* 点击通过资源对象按钮,进入二级页面。
+* 点击通过资源ID按钮,进入二级页面。
+* 点击使用异步按钮,进入二级页面,上下滑动,页面滑动流畅。
+* 点击使用多线程按钮,进入二级页面,上下滑动,页面滑动流畅。
+* 点击高频事件回调执行耗时操作按钮,进入二级页面。
+* 点击高频事件回调不执行耗时操作按钮,进入二级页面。
+* 点击条件渲染按钮,进入二级页面,点击按钮,观察页面变化。
## 相关权限
-无
+不涉及
## 约束与限制
* 本示例仅支持标准系统上运行,支持设备:华为手机。
-* HarmonyOS系统:HarmonyOS NEXT Release及以上。
+* HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+* DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+* HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
-* DevEco Studio版本:DevEco Studio NEXT Release及以上。
+## 下载
-* HarmonyOS SDK版本:HarmonyOS NEXT Release SDK及以上。
\ No newline at end of file
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AvoidTimeComsume
+git checkout
+```
\ No newline at end of file
diff --git a/AvoidTimeComsume/README_EN.md b/AvoidTimeComsume/README_EN.md
index 3042a16cb75fb18ec1817feec95e570aac3784fa..bae0f4ece15dbce9cc3897993711b794967341a0 100644
--- a/AvoidTimeComsume/README_EN.md
+++ b/AvoidTimeComsume/README_EN.md
@@ -3,8 +3,6 @@
In application development practices, it is important to effectively prevent the main thread from performing redundant and time-consuming operations. This can effectively reduce the load of the main thread and speed up the UI response. In scenarios where high-frequency callbacks are frequently triggered in a short period of time, time-consuming operations in the APIs need to be avoided to ensure that the main thread is not occupied for a long time. This prevents UI rendering from being blocked to avoid frame freezing or frame loss.
This sample describes common redundant operations, common high-frequency callback scenarios, and other main thread optimization methods during development.
-## Preview
-
## Project Directory
```
├──entry/src/main/ets // Code
@@ -56,8 +54,19 @@ N/A
## Constraints
* This sample is supported only on Huawei phones running the standard system.
-* The HarmonyOS version must be HarmonyOS NEXT Release or later.
+* The HarmonyOS version must be HarmonyOS 5.0.5 Release or later.
-* The DevEco Studio version must be DevEco Studio NEXT Release or later.
+* The DevEco Studio version must be DevEco Studio 5.0.5 Release or later.
-* The HarmonyOS SDK version must be HarmonyOS NEXT Release SDK or later.
+* The HarmonyOS SDK version must be HarmonyOS 5.0.5 Release SDK or later.
+
+## Download
+
+To download this project separately, execute the following command:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set AvoidTimeComsume
+git checkout
+```
diff --git a/AvoidTimeComsume/build-profile.json5 b/AvoidTimeComsume/build-profile.json5
index b2cc02977d74631a63703f33a1ae6c1f94d81219..6addf0233cf8ed875ba6574c0c91538334c17921 100644
--- a/AvoidTimeComsume/build-profile.json5
+++ b/AvoidTimeComsume/build-profile.json5
@@ -6,7 +6,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
}
],
diff --git a/AvoidTimeComsume/entry/src/main/ets/entryability/EntryAbility.ets b/AvoidTimeComsume/entry/src/main/ets/entryability/EntryAbility.ets
index 80c495ede2460b86c56489c6c654126b77f31de6..471cad2a7dac7c186ecf07b2b15d41c2274b5370 100644
--- a/AvoidTimeComsume/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/entryability/EntryAbility.ets
@@ -39,7 +39,11 @@ export default class EntryAbility extends UIAbility {
return;
}
hilog.info(0x0000, 'Sample', 'Succeeded in loading the content.');
- AppStorage.setOrCreate('uiContext', windowStage.getMainWindowSync().getUIContext());
+ try {
+ AppStorage.setOrCreate('uiContext', windowStage.getMainWindowSync().getUIContext());
+ } catch (error) {
+ hilog.error(0x0000, 'Sample', 'Failed to getMainWindowSync. Cause: %{public}s', JSON.stringify(error) ?? '');
+ }
});
windowStage.getMainWindow().then((windowObj) => {
diff --git a/AvoidTimeComsume/entry/src/main/ets/pages/Index.ets b/AvoidTimeComsume/entry/src/main/ets/pages/Index.ets
index e0258427c40dc9eb4b6459254820f2d07353f24e..8e2e7bf6cccd25a580d581b77918e6e3db87eb83 100644
--- a/AvoidTimeComsume/entry/src/main/ets/pages/Index.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/pages/Index.ets
@@ -12,6 +12,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
class DirectoryItem {
title: ResourceStr = '';
@@ -107,6 +109,8 @@ struct Index {
.onClick(() => {
this.getUIContext().getRouter().pushUrl({
url: item.uri
+ }).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`pushUrl failed. code=${error.code}, message=${error.message}`);
});
})
}
@@ -128,6 +132,8 @@ struct Index {
.onClick(() => {
this.getUIContext().getRouter().pushUrl({
url: 'views/NegativeOfOnScroll'
+ }).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`pushUrl failed. code=${error.code}, message=${error.message}`);
});
})
Button($r('app.string.positive_of_onScroll'))
@@ -139,6 +145,8 @@ struct Index {
.onClick(() => {
this.getUIContext().getRouter().pushUrl({
url: 'views/PositiveOfOnScroll'
+ }).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`pushUrl failed. code=${error.code}, message=${error.message}`);
});
})
Button($r('app.string.conditional_rendering'))
@@ -150,7 +158,9 @@ struct Index {
.onClick(() => {
this.getUIContext().getRouter().pushUrl({
url: 'views/ConditionalRendering'
- });
+ }).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`pushUrl failed. code=${error.code}, message=${error.message}`);
+ });;
})
}
.padding({ left: 16, right: 16, bottom: 44 })
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/ConditionalRendering.ets b/AvoidTimeComsume/entry/src/main/ets/views/ConditionalRendering.ets
index 382f6fa052d3e715ce5b0df966e644ac85809278..ca0d90579746c63a4079ed6b7cc7d7d6d5e2d7a5 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/ConditionalRendering.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/ConditionalRendering.ets
@@ -13,9 +13,9 @@
* limitations under the License.
*/
+// [Start conditional_rendering]
import { hilog } from '@kit.PerformanceAnalysisKit';
-// [Start conditional_rendering]
@Entry
@Component
struct MyComponent {
@@ -26,6 +26,7 @@ struct MyComponent {
Column({ space: 10 }) {
Row({ space: 5 }) {
Column() {
+ // $r('app.media.chevron_left') It needs to be replaced with the resources required by the developers
Image($r('app.media.chevron_left'))
.width(16)
.height(16)
@@ -77,7 +78,7 @@ struct MyComponent {
@Component
struct CustomComponentA {
aboutToAppear(): void {
- let temp = 0;
+ let temp: number = 0;
for (let i = 0; i < 1000000; i++) {
temp += 1;
}
@@ -85,7 +86,7 @@ struct CustomComponentA {
}
aboutToDisappear(): void {
- let temp = 0;
+ let temp: number = 0;
for (let i = 0; i < 1000000; i++) {
temp += 1;
}
@@ -103,7 +104,7 @@ struct CustomComponentA {
@Component
struct CustomComponentB {
aboutToAppear(): void {
- let temp = 0;
+ let temp: number = 0;
for (let i = 0; i < 1000000; i++) {
temp += 1;
}
@@ -111,7 +112,7 @@ struct CustomComponentB {
}
aboutToDisappear(): void {
- let temp = 0;
+ let temp: number = 0;
for (let i = 0; i < 1000000; i++) {
temp += 1;
}
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfId.ets b/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfId.ets
index c0c91c35cc43a9500b38113de23643617d0db950..2dad628dc99368e72d05e8d046541d504c924ef8 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfId.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfId.ets
@@ -14,7 +14,7 @@
*/
// [Start get_str_of_id]
-import { hiTraceMeter } from '@kit.PerformanceAnalysisKit';
+import { hilog, hiTraceMeter } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
@@ -23,8 +23,12 @@ struct GetStrOfId {
aboutToAppear(): void {
hiTraceMeter.startTrace('getStringSyncAfter', 1);
- // The input parameter of the getStringSync operation directly uses the resource and does use the resource ID
- this.getUIContext().getHostContext()!.resourceManager.getStringSync($r('app.string.test').id)
+ // The input parameter of the getStringSync operation directly uses the resource and resource ID
+ try {
+ this.getUIContext().getHostContext()!.resourceManager.getStringSync($r('app.string.test').id)
+ } catch (error) {
+ hilog.error(0x0000,'',`getStringSync failed. code=${error.code}, message=${error.message}`);
+ }
hiTraceMeter.finishTrace('getStringSyncAfter', 1)
}
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfResource.ets b/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfResource.ets
index db9f6697178b564713a2cf8db7b2fb03660e2099..edf6f5ec9cbc18b62ec02a500a368cc1c71bb75a 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfResource.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/GetStrOfResource.ets
@@ -14,7 +14,7 @@
*/
// [Start get_str_of_resource]
-import { hiTraceMeter } from '@kit.PerformanceAnalysisKit';
+import { hilog, hiTraceMeter } from '@kit.PerformanceAnalysisKit';
@Entry
@@ -25,7 +25,11 @@ struct GetStrOfResource {
aboutToAppear(): void {
hiTraceMeter.startTrace('getStringSync', 1);
// The input parameter of the getStringSync operation directly uses the resource and does not use the resource ID
- this.getUIContext().getHostContext()!.resourceManager.getStringSync($r('app.string.test'))
+ try {
+ this.getUIContext().getHostContext()!.resourceManager.getStringSync($r('app.string.test').id)
+ } catch (error) {
+ hilog.error(0x0000,'',`getStringSync failed. code=${error.code}, message=${error.message}`);
+ }
hiTraceMeter.finishTrace('getStringSync', 1)
}
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/NegativeOfGrid.ets b/AvoidTimeComsume/entry/src/main/ets/views/NegativeOfGrid.ets
index 10dc77d32809a74dfe91536457bde5cdad3ce7a0..0390ed3f5e24336b6c158b06dbf25a10d747db25 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/NegativeOfGrid.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/NegativeOfGrid.ets
@@ -14,7 +14,6 @@
*/
import { hiTraceMeter } from '@kit.PerformanceAnalysisKit';
-import { router } from '@kit.ArkUI';
class MyDataSource implements IDataSource {
private dataArray: number[] = [];
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/NoRedundantOperation.ets b/AvoidTimeComsume/entry/src/main/ets/views/NoRedundantOperation.ets
index 383ec3876813141be4d827ffa6ed4c47875e511e..c50fc4448d6899d581b16f746bd1ffa679a48923 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/NoRedundantOperation.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/NoRedundantOperation.ets
@@ -14,7 +14,6 @@
*/
import { hilog } from '@kit.PerformanceAnalysisKit';
-import { router } from '@kit.ArkUI';
// [Start no_redundant_operation]
// Redundancy operation example
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/PositiveOfProperty.ets b/AvoidTimeComsume/entry/src/main/ets/views/PositiveOfProperty.ets
index 1ce7eab8ea5024ae3037b809b959c54cda4b7fb3..431f46ecfb11ee22975ae5b7ae825d5155d0f1ce 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/PositiveOfProperty.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/PositiveOfProperty.ets
@@ -16,6 +16,7 @@
// [Start positive_of_property]
import { taskpool } from '@kit.ArkTS'; // Task pools
import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
function getHeight(): number {
@@ -31,7 +32,9 @@ function getHeight(): number {
// Execute getHeight
taskpool.execute(getHeight).then((value: Object) => {
AppStorage.setOrCreate('height', value);
-})
+}).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`execute failed. code=${error.code}, message=${error.message}`);
+});
@Entry
@Component
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/UseAsync.ets b/AvoidTimeComsume/entry/src/main/ets/views/UseAsync.ets
index cb40596a524299b49ecba14efab78bc5b5b5cbe6..76f17e27f2d49f16cc4685704ae015a49f0d7cf8 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/UseAsync.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/UseAsync.ets
@@ -16,7 +16,8 @@
import { Item, ResponseData, dataToItem } from '../common/Item';
import { WaterFlowDataSource } from './WaterFlowDataSource';
import { buffer } from '@kit.ArkTS';
-
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
@@ -122,9 +123,15 @@ struct WaterFlowExample2 {
// data.json is the local json data, which is about 20 MB in size, and simulates getting data from the network
await this.getUIContext().getHostContext()!.resourceManager.getRawFileContent('data.json').then((data: Uint8Array) => {
// parse json
- let str = buffer.from(data).toString();
- res = JSON.parse(str);
- })
+ try {
+ let str: string = buffer.from(data).toString();
+ res = JSON.parse(str);
+ } catch (error) {
+ hilog.error(0x0000,'',`buffer.from failed. code=${error.code}, message=${error.message}`);
+ }
+ }).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`getRawFileContent failed. code=${error.code}, message=${error.message}`);
+ });
return dataToItem(res.data)
}
diff --git a/AvoidTimeComsume/entry/src/main/ets/views/UseTaskPool.ets b/AvoidTimeComsume/entry/src/main/ets/views/UseTaskPool.ets
index cd2ecf9fa7bb45f021a9c2d7816070b1b016dd13..650c4ddec72f633a818605da180ea106ef13ef78 100644
--- a/AvoidTimeComsume/entry/src/main/ets/views/UseTaskPool.ets
+++ b/AvoidTimeComsume/entry/src/main/ets/views/UseTaskPool.ets
@@ -16,6 +16,8 @@
import { buffer, taskpool } from '@kit.ArkTS';
import { Item, ResponseData, dataToItem } from '../common/Item';
import { WaterFlowDataSource } from './WaterFlowDataSource';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
@@ -23,7 +25,7 @@ struct WaterFlowExample {
@State fontSize: number = 24;
scroller: Scroller = new Scroller();
dataSource: WaterFlowDataSource = new WaterFlowDataSource();
- UIContext = this.getUIContext()
+ UIContext: UIContext = this.getUIContext()
@Builder
itemFoot() {
@@ -123,18 +125,31 @@ struct WaterFlowExample {
// The following methods are defined outside of the component
async function taskPoolExecute(UIContext: UIContext): Promise {
let task: taskpool.Task = new taskpool.Task(mockRequestData, UIContext);
- return await taskpool.execute(task) as Item[];
+ let result: Item[] = [];
+ try {
+ result = await taskpool.execute(task) as Item[]
+ } catch (error) {
+ hilog.error(0x0000,'',`execute failed. code=${error.code}, message=${error.message}`);
+ }
+ return result;
}
+@Concurrent
async function mockRequestData(context: Context): Promise {
let res: ResponseData = new ResponseData();
// data.json is the local json data, which is about 20 MB in size, and simulates getting data from the network
await context.resourceManager.getRawFileContent('data.json').then((data: Uint8Array) => {
// parse json
- let str = buffer.from(data).toString();
- res = JSON.parse(str);
- })
- let arr = dataToItem(res.data);
+ try {
+ let str: string = buffer.from(data).toString();
+ res = JSON.parse(str);
+ } catch (error) {
+ hilog.error(0x0000,'',`buffer.from failed. code=${error.code}, message=${error.message}`);
+ }
+ }).catch((error: BusinessError)=>{
+ hilog.error(0x0000,'',`getRawFileContent failed. code=${error.code}, message=${error.message}`);
+ });
+ let arr: Item[] = dataToItem(res.data);
return arr;
}
diff --git a/AvoidTimeComsume/screenshots/homePage.png b/AvoidTimeComsume/screenshots/homePage.png
new file mode 100644
index 0000000000000000000000000000000000000000..c1f73094e0cc410ab9742b6a9d7849a4c87a40a0
Binary files /dev/null and b/AvoidTimeComsume/screenshots/homePage.png differ
diff --git a/AvoidTimeComsume/screenshots/output-15_16_3.gif b/AvoidTimeComsume/screenshots/output-15_16_3.gif
deleted file mode 100644
index 8edf68e5b8a0b97a89b25f71dd0a5d641399d7b4..0000000000000000000000000000000000000000
Binary files a/AvoidTimeComsume/screenshots/output-15_16_3.gif and /dev/null differ
diff --git a/AvoidTimeComsume/screenshots/output-15_53_54.gif b/AvoidTimeComsume/screenshots/output-15_53_54.gif
deleted file mode 100644
index 42fc9bd5c53efbab0f801c76f336e4b440e5ecdb..0000000000000000000000000000000000000000
Binary files a/AvoidTimeComsume/screenshots/output-15_53_54.gif and /dev/null differ
diff --git a/BackgroundBlur/README.en.md b/BackgroundBlur/README.en.md
index 92581dcc4462cec3b1b9e066bbe7b6fbfa75d32f..49126a76823303502b64ed2d7fda2c8455bafc21 100644
--- a/BackgroundBlur/README.en.md
+++ b/BackgroundBlur/README.en.md
@@ -69,8 +69,19 @@ N/A
1. This sample is supported only on Huawei phones running the standard system.
-2. The HarmonyOS version must be HarmonyOS NEXT Release or later.
+2. The HarmonyOS version must be HarmonyOS 5.0.5 Release or later.
-3. The DevEco Studio version must be DevEco Studio NEXT Release or later.
+3. The DevEco Studio version must be DevEco Studio 5.0.5 Release or later.
-4. The HarmonyOS SDK version must be HarmonyOS NEXT Release SDK or later.
+4. The HarmonyOS SDK version must be HarmonyOS5.0.5 Release SDK or later.
+
+### Download
+
+To download this project separately, execute the following command:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set BackgroundBlur
+git checkout
+```
\ No newline at end of file
diff --git a/BackgroundBlur/README.md b/BackgroundBlur/README.md
index 63ce6893af1f7cebc46281cc14bd6821d09766b2..c51ddcdc97119d50ce83f58ef11e4e856121b931 100644
--- a/BackgroundBlur/README.md
+++ b/BackgroundBlur/README.md
@@ -30,7 +30,7 @@
│ ├──entryability
│ │ └──EntryAbility.ets // Ability的生命周期回调内容
│ ├──entrybackupability
-│ │ └──EntryBackupAbility.ets
+│ │ └──EntryBackupAbility.ets // 应用数据备份和恢复
│ └──pages
│ ├──AdaptiveColorMode.ets // 视图层-使用AdaptiveColor取色效果页面
│ ├──ColorPickerMode.ets // 视图层-使用ColorPicker取色效果页面
@@ -59,8 +59,19 @@
1.本示例仅支持标准系统上运行,支持设备:华为手机。
-2.HarmonyOS系统:HarmonyOS NEXT Release及以上。
+2.HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
-3.DevEco Studio版本:DevEco Studio NEXT Release及以上。
+3.DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
-4.HarmonyOS SDK版本:HarmonyOS NEXT Release SDK及以上。
+4.HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set BackgroundBlur
+git checkout
+```
diff --git a/BackgroundBlur/build-profile.json5 b/BackgroundBlur/build-profile.json5
index adce96361e2c935e9a1f0c303bea4da26485e58b..79d90a8b6d11889d5f388820c296223aaa8e51b5 100644
--- a/BackgroundBlur/build-profile.json5
+++ b/BackgroundBlur/build-profile.json5
@@ -4,7 +4,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS"
}
],
diff --git a/BackgroundBlur/entry/src/main/ets/pages/ColorPickerMode.ets b/BackgroundBlur/entry/src/main/ets/pages/ColorPickerMode.ets
index 5109b43bce5c0e8d291013250cf1e15305a271fe..fc6cdbbb49858ca29281bc3dbd96a0eeb00fb203 100644
--- a/BackgroundBlur/entry/src/main/ets/pages/ColorPickerMode.ets
+++ b/BackgroundBlur/entry/src/main/ets/pages/ColorPickerMode.ets
@@ -30,16 +30,18 @@ export struct ColorPickerMode {
@State blurColor: string = 'rgba(255,255,255,255)';
async blurPix(resource: Resource) {
- const context = this.getUIContext().getHostContext()!;
- const resourceMgr = context.resourceManager
- const fileData = await resourceMgr.getMediaContent(resource)
- const buffer = fileData.buffer
- let imageSource = image.createImageSource(buffer as ArrayBuffer)
- this.pixMap = await imageSource.createPixelMap();
- // create a color picker for color extraction
- this.kitColor = (await effectKit.createColorPicker(this.pixMap, [0, 0, 1, 1])).getAverageColor();
- // convert to the format of the blur interface color parameter
- this.blurColor = 'rgba(' + this.kitColor.red + ',' + this.kitColor.green + ',' + this.kitColor.blue + ',0)';
+ try {
+ const context: Context = this.getUIContext().getHostContext()!;
+ const fileData: Uint8Array = await context.resourceManager.getMediaContent(resource.id);
+ const buffer: ArrayBufferLike = fileData.buffer
+ let imageSource: image.ImageSource = image.createImageSource(buffer as ArrayBuffer)
+ this.pixMap = await imageSource.createPixelMap();
+ // create a color picker for color extraction
+ this.kitColor = (await effectKit.createColorPicker(this.pixMap, [0, 0, 1, 1])).getAverageColor();
+ // convert to the format of the blur interface color parameter
+ this.blurColor = 'rgba(' + this.kitColor.red + ',' + this.kitColor.green + ',' + this.kitColor.blue + ',0)';
+ } catch (err) {
+ }
}
build() {
@@ -72,4 +74,5 @@ export struct ColorPickerMode {
.hideTitleBar(true)
}
}
+
// [End color_picker]
diff --git a/BackgroundBlur/hvigor/hvigor-config.json5 b/BackgroundBlur/hvigor/hvigor-config.json5
index 06b2783670a348f95533b352c1ceda909a842bbc..5bebc9755447385d82ce4138f54d991b1f85f348 100644
--- a/BackgroundBlur/hvigor/hvigor-config.json5
+++ b/BackgroundBlur/hvigor/hvigor-config.json5
@@ -1,5 +1,5 @@
{
- "modelVersion": "5.0.0",
+ "modelVersion": "5.0.5",
"dependencies": {
},
"execution": {
diff --git a/BackgroundBlur/oh-package.json5 b/BackgroundBlur/oh-package.json5
index 0cec98259052cc175d04dbcf61780de4bc9785f4..f440d114b8a9d9aeadd0e891bba0d0d076e70936 100644
--- a/BackgroundBlur/oh-package.json5
+++ b/BackgroundBlur/oh-package.json5
@@ -1,5 +1,5 @@
{
- "modelVersion": "5.0.0",
+ "modelVersion": "5.0.5",
"description": "Please describe the basic information.",
"dependencies": {
},
diff --git a/BptaUseResources/.gitignore b/BptaUseResources/.gitignore
deleted file mode 100644
index d2ff20141ceed86d87c0ea5d99481973005bab2b..0000000000000000000000000000000000000000
--- a/BptaUseResources/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-/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/BptaUseResources/README.md b/BptaUseResources/README.md
index d71e93dee2e251b09a1a8168e45491cfaab59d5c..475e9c17d4a36d2a7d48850042883cb3eb31623d 100644
--- a/BptaUseResources/README.md
+++ b/BptaUseResources/README.md
@@ -4,17 +4,33 @@
无长时任务的应用退到后台时,不允许进行蓝牙扫描。
+### 使用说明
+不涉及
+
### 工程结构&模块类型
```
-├──entry/src/main/ets/
-│ ├──entryability
-│ │ └──EntryAbility.ets // 配置类
-│ └──pages
-│ └──Index.ets // 程序入口
-│ └──Https.ets // HTTP数据请求
-│ └──Bluetooth.ets // 合理使用蓝牙资源
-└──entry/src/main/resource // 应用静态资源目录
+├──entry/src/main
+│ ├──ets
+│ │ ├──entryability
+│ │ │ └──EntryAbility.ets // 配置类
+│ │ ├──entrybackupability
+│ │ │ └──EntryBackupAbility.ets // 应用数据备份恢复类
+│ │ └──pages
+│ │ ├──Index.ets // 程序入口
+│ │ ├──Gps.ets // gps示例
+│ │ ├──Sensor.ets // 传感器示例
+│ │ ├──Socket.ets // socket示例
+│ │ ├──WebSocket.ets // WebSocket示例
+│ │ ├──Https.ets // HTTP数据请求
+│ │ └──Bluetooth.ets // 合理使用蓝牙资源
+│ └──cpp
+│ ├──types
+│ │ └──index.d.ts // c++导出方法
+│ ├──CMakeLists.txt
+│ ├──napi_init.cpp // 合理使用蓝牙资源
+│ └──OpenSL.cpp // 初始化代码
+└──entry/src/main/resource // 应用静态资源目录
```
@@ -26,8 +42,19 @@
1. 本示例仅支持标准系统上运行,支持设备:华为手机。
-2. HarmonyOS 系统:HarmonyOS NEXT Developer Beta1 及以上。
+2. HarmonyOS 系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio 版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK 版本:HarmonyOS 5.0.5 Release SDK及以上。
-3. DevEco Studio 版本:DevEco Studio NEXT Developer Beta1 及以上。
+### 下载
-4. HarmonyOS SDK 版本:HarmonyOS NEXT Developer Beta1 SDK 及以上。
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set BptaUseResources
+git checkout
+```
diff --git a/BptaUseResources/build-profile.json5 b/BptaUseResources/build-profile.json5
index 9e87e7e6f19020fe21192844709f192cec80fd44..f120cc13b0fec135d32bc1b97b13b9f71542a237 100644
--- a/BptaUseResources/build-profile.json5
+++ b/BptaUseResources/build-profile.json5
@@ -12,6 +12,9 @@
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
+ },
+ "packOptions": {
+ "enableSourceCodeCheck": false
}
}
}
diff --git a/BptaUseResources/entry/.gitignore b/BptaUseResources/entry/.gitignore
deleted file mode 100644
index e2713a2779c5a3e0eb879efe6115455592caeea5..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-/node_modules
-/oh_modules
-/.preview
-/build
-/.cxx
-/.test
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/cpp/CMakeLists.txt b/BptaUseResources/entry/src/main/cpp/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1acd3ec1c568e86cb70911ecc57edfbb21bcd1ea
--- /dev/null
+++ b/BptaUseResources/entry/src/main/cpp/CMakeLists.txt
@@ -0,0 +1,15 @@
+# the minimum version of CMake.
+cmake_minimum_required(VERSION 3.5.0)
+project(CppCrash)
+
+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 napi_init.cpp)
+target_link_libraries(entry PUBLIC libace_napi.z.so)
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/cpp/OpenSL.cpp b/BptaUseResources/entry/src/main/cpp/OpenSL.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..000428eb92e8303673c2eeef0bcf86ecfcb894b7
--- /dev/null
+++ b/BptaUseResources/entry/src/main/cpp/OpenSL.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+/**
+ * 最佳实践:合理使用音频资源
+ * 场景三:播音场景(OpenSL ES)
+ */
+
+// [Start open_sl_es]
+//The foreground scene starts to play
+SLPlayItfplayItf=nullptr;
+(*pcmPlayerObject)->GetInterface(pcmPlayerObject,SL_IID_PLAY,&playItf);
+(*playItf)->SetPlayState(playItf,SL_PLAYSTATE_PLAYING);
+// Stop playing the background scene
+(*playItf)->SetPlayState(playItf,SL_PLAYSTATE_STOPPED);
+(*pcmPlayerObject)->Destroy(pcmPlayerObject);
+(*engineObject)->Destroy(engineObject);
+// [End open_sl_es]
+
+/**
+ * 最佳实践:合理使用音频资源
+ * 场景四:播音场景(OHAudio)
+ */
+
+// [Start oh_audio]
+//Construct the audio stream to play
+OH_AudioRenderer*audioRenderer;
+ret=OH_AudioStreamBuilder_GenerateRenderer(builder,&audioRenderer);
+
+//The foreground scene starts to play
+ret=OH_AudioRenderer_Start(audioRenderer);
+// Stop playing the background scene
+ret=OH_AudioRenderer_Stop(audioRenderer);
+// [End oh_audio]
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/cpp/napi_init.cpp b/BptaUseResources/entry/src/main/cpp/napi_init.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..d0e1aafcb6b5c3252ef439d9d9d54e8c082fda1d
--- /dev/null
+++ b/BptaUseResources/entry/src/main/cpp/napi_init.cpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2025 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 "napi/native_api.h"
+
+static napi_value Add(napi_env env, napi_callback_info info)
+{
+ size_t argc = 2;
+ napi_value args[2] = {nullptr};
+
+ napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
+
+ napi_valuetype valuetype0;
+ napi_typeof(env, args[0], &valuetype0);
+
+ napi_valuetype valuetype1;
+ napi_typeof(env, args[1], &valuetype1);
+
+ double value0;
+ napi_get_value_double(env, args[0], &value0);
+
+ double value1;
+ napi_get_value_double(env, args[1], &value1);
+
+ napi_value sum;
+ napi_create_double(env, value0 + value1, &sum);
+
+ return sum;
+
+}
+
+EXTERN_C_START
+static napi_value Init(napi_env env, napi_value exports)
+{
+ napi_property_descriptor desc[] = {
+ { "add", nullptr, Add, 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);
+}
diff --git a/BptaUseResources/entry/src/main/cpp/types/libentry/index.d.ts b/BptaUseResources/entry/src/main/cpp/types/libentry/index.d.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e44f3615a4767c36b4fdc841b781af96bf1971a8
--- /dev/null
+++ b/BptaUseResources/entry/src/main/cpp/types/libentry/index.d.ts
@@ -0,0 +1 @@
+export const add: (a: number, b: number) => number;
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/cpp/types/libentry/oh-package.json5 b/BptaUseResources/entry/src/main/cpp/types/libentry/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..17f2fec28b34ad5d42507c4fa15c7e4d0d16eb70
--- /dev/null
+++ b/BptaUseResources/entry/src/main/cpp/types/libentry/oh-package.json5
@@ -0,0 +1,6 @@
+{
+ "name": "libentry.so",
+ "types": "./index.d.ts",
+ "version": "1.0.0",
+ "description": "Please describe the basic information."
+}
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/ets/entryability/EntryAbility.ets b/BptaUseResources/entry/src/main/ets/entryability/EntryAbility.ets
index 508880af8c33aa838016d1cd4b2c68be2f447540..69f8a2d6d7d3ebb7dbb2a410be697942b91153bd 100644
--- a/BptaUseResources/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/BptaUseResources/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,12 +1,18 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
+import { BusinessError } from '@kit.BasicServicesKit';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/BptaUseResources/entry/src/main/ets/pages/Bluetooth.ets b/BptaUseResources/entry/src/main/ets/pages/Bluetooth.ets
index 4ec6438cf8ebaf8f61d0b3276bae9f9d5d6f6223..06b4493552e0b08b7366c942c8a1589caf0c5cd3 100644
--- a/BptaUseResources/entry/src/main/ets/pages/Bluetooth.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/Bluetooth.ets
@@ -5,6 +5,8 @@
// [Start blue_tooth]
import { UIAbility } from '@kit.AbilityKit';
import { ble } from '@kit.ConnectivityKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BusinessError } from '@kit.BasicServicesKit';
// [StartExclude blue_tooth]
const scanFilter: ble.ScanFilter = {}
@@ -20,15 +22,25 @@ const advResponse = undefined
export default class EntryAbility extends UIAbility {
// ...
onForeground(): void {
- //Initiate Ble scan and broadcast as required by the service at the foreground
- ble.startBLEScan([scanFilter], scanOptions);
- ble.startAdvertising(setting, advData, advResponse);
+ try {
+ //Initiate Ble scan and broadcast as required by the service at the foreground
+ ble.startBLEScan([scanFilter], scanOptions);
+ ble.startAdvertising(setting, advData, advResponse);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `startBLEScan or startAdvertising failed, code=${err.code}, message=${err.message}`);
+ }
}
onBackground(): void {
- // Return to the background to stop the Ble scanning and broadcast, which is the same as the application
- ble.stopBLEScan();
- ble.stopAdvertising();
+ try {
+ // Return to the background to stop the Ble scanning and broadcast, which is the same as the application
+ ble.stopBLEScan();
+ ble.stopAdvertising();
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `stopBLEScan or stopAdvertising failed, code=${err.code}, message=${err.message}`);
+ }
}
}
// [End blue_tooth]
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/ets/pages/Gps.ets b/BptaUseResources/entry/src/main/ets/pages/Gps.ets
index b43d05d2255d1b3044689f33ac35ab3094565ce1..5d427bf5c5ee49c11815944ce2f48f81905d0cd9 100644
--- a/BptaUseResources/entry/src/main/ets/pages/Gps.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/Gps.ets
@@ -5,11 +5,14 @@
// [Start gps_resources]
import { UIAbility } from '@kit.AbilityKit';
import { geoLocationManager } from '@kit.LocationKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BusinessError } from '@kit.BasicServicesKit';
// [StartExclude gps_resources]
let locationChange = (location: geoLocationManager.Location): void => {
console.log('locationChanger:data:' + JSON.stringify(location));
};
+
// [EndExclude gps_resources]
export default class EntryAbility extends UIAbility {
@@ -25,13 +28,24 @@ export default class EntryAbility extends UIAbility {
let locationChange = (location: geoLocationManager.Location): void => {
console.log('locationChanger:data:' + JSON.stringify(location));
};
- //The change of the listening position
- geoLocationManager.on('locationChange', requestInfo, locationChange);
+ try {
+ //The change of the listening position
+ geoLocationManager.on('locationChange', requestInfo, locationChange);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `geoLocationManager on failed, code=${err.code}, message=${err.message}`);
+ }
}
onBackground(): void {
- //The backstage cancels the listening
- geoLocationManager.off('locationChange', locationChange);
+ try {
+ //The backstage cancels the listening
+ geoLocationManager.off('locationChange', locationChange);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `geoLocationManager off failed, code=${err.code}, message=${err.message}`);
+ }
}
}
+
// [End gps_resources]
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/ets/pages/Https.ets b/BptaUseResources/entry/src/main/ets/pages/Https.ets
index 8b62be4c91f66a1b93d085bc97d464ec57c243e5..cc982b87e49afe01ef81442ef965b1ce6c839ef3 100644
--- a/BptaUseResources/entry/src/main/ets/pages/Https.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/Https.ets
@@ -11,7 +11,7 @@ export default class EntryAbility extends UIAbility {
// ...
onForeground(): void {
// Create an HTTP request based on the service requirements at the foreground
- let httpRequest = http.createHttp();
+ let httpRequest: http.HttpRequest = http.createHttp();
// ...
}
diff --git a/BptaUseResources/entry/src/main/ets/pages/Sensor.ets b/BptaUseResources/entry/src/main/ets/pages/Sensor.ets
index 5c2a2b938ec5e38075841f923b0ba55f2be899f8..d0c2ce295fffe7f7735f4b05c65532bd734e43d4 100644
--- a/BptaUseResources/entry/src/main/ets/pages/Sensor.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/Sensor.ets
@@ -5,21 +5,34 @@
// [Start sensor_resources]
import { UIAbility } from '@kit.AbilityKit';
import { sensor } from '@kit.SensorServiceKit';
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
export default class EntryAbility extends UIAbility {
// ...
onForeground(): void {
- //In the foreground, listen to the required type of sensor based on the service requirements
- sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
- console.info("Succeededinobtainingdata.x:" + data.x + "y:" + data.y + "z:" + data.z);
- }, {
- interval: 100000000
- });
+ try {
+ //In the foreground, listen to the required type of sensor based on the service requirements
+ sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
+ console.info("Succeeded in obtaining data.x:" + data.x + "y:" + data.y + "z:" + data.z);
+ }, {
+ interval: 100000000
+ });
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `sensor on failed, code=${err.code}, message=${err.message}`);
+ }
}
onBackground(): void {
- //The backstage cancels the listening
- sensor.off(sensor.SensorId.ACCELEROMETER);
+ try {
+ //The backstage cancels the listening
+ sensor.off(sensor.SensorId.ACCELEROMETER);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `sensor off failed, code=${err.code}, message=${err.message}`);
+ }
}
}
+
// [End sensor_resources]
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/ets/pages/Socket.ets b/BptaUseResources/entry/src/main/ets/pages/Socket.ets
index 36756870d54fa3eb44a52ed222809204b1820b0f..15e743afb268fbe91724b9a7cfd235e15d0a444f 100644
--- a/BptaUseResources/entry/src/main/ets/pages/Socket.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/Socket.ets
@@ -13,10 +13,12 @@ export default class EntryAbility extends UIAbility {
tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
onForeground(): void {
- //In the foreground, create a socket connection and send service data as required
- this.tcp.bind(ipAddress, (err: BusinessError) => {})
- this.tcp.connect(tcpConnect, (err: BusinessError) => {})
- this.tcp.send(tcpSendOptions, (err: BusinessError) => {})
+ /**
+ * In the foreground, create a socket connection and send service data as required, for example:
+ * this.tcp.bind(ipAddress, (err: BusinessError) => {})
+ * this.tcp.connect(tcpConnect, (err: BusinessError) => {})
+ * this.tcp.send(tcpSendOptions, (err: BusinessError) => {})
+ */
}
onBackground(): void {
diff --git a/BptaUseResources/entry/src/main/ets/pages/WebSocket.ets b/BptaUseResources/entry/src/main/ets/pages/WebSocket.ets
index 0afda565d00790761b0d2a911df53af0e1ff74e0..89ff8307be64a9c51e459441ab2f4e32dcfe0fec 100644
--- a/BptaUseResources/entry/src/main/ets/pages/WebSocket.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/WebSocket.ets
@@ -11,7 +11,7 @@ import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
// Create a websocket based on service requirements
- ws = webSocket.createWebSocket();
+ ws: webSocket.WebSocket = webSocket.createWebSocket();
onForeground(): void {
diff --git a/BptaUseResources/entry/src/main/ets/pages/music/AvPlayer.ets b/BptaUseResources/entry/src/main/ets/pages/music/AvPlayer.ets
index 3664d1f95aa8060810a29d04c57767e3d6c3e228..a7a93ff8a95b028bac61748b588634b201fb8021 100644
--- a/BptaUseResources/entry/src/main/ets/pages/music/AvPlayer.ets
+++ b/BptaUseResources/entry/src/main/ets/pages/music/AvPlayer.ets
@@ -2,28 +2,41 @@
* 最佳实践:合理使用音频资源
* 场景二:播音场景(AVPlayer)
*/
-
+// [Start sound_pool]
import { fileIo as fs } from '@kit.CoreFileKit';
import { media } from '@kit.MediaKit';
+import { BusinessError } from '@kit.BasicServicesKit';
+
+// [End sound_pool]
+
// [Start av_player]
import { UIAbility } from '@kit.AbilityKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
// [StartExclude av_player]
let avPlayer: media.AVPlayer
+
// [EndExclude av_player]
export default class EntryAbility extends UIAbility {
// ...
onForeground(): void {
//Playing according to service requirements in the foreground
- avPlayer.play();
+ avPlayer.play()
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `avPlayer play failed, code=${err.code}, message=${err.message}`)
+ })
}
onBackground(): void {
// Return to the background to stop playing or pause
- avPlayer.stop(); // Or pause();
+ avPlayer.stop() // Or pause();
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `avPlayer stop failed, code=${err.code}, message=${err.message}`)
+ })
}
}
+
// [End av_player]
/**
@@ -35,16 +48,32 @@ let soundId: number;
let streamId: number;
let uri: string;
let soundPool: media.SoundPool;
+// [Start sound_pool]
const SoundPool = async () => {
- // [Start sound_pool]
+
//Construct the audio stream to play
await fs.open('/test_01.mp3', fs.OpenMode.READ_ONLY).then((file: fs.File) => {
console.info("filefd:" + file.fd);
uri = 'fd://' + (file.fd).toString()
- }); // '/test_01.mp3' is used as an example. The path of the file needs to be transferred
- soundId = await soundPool.load(uri);
- //The foreground scene starts to play
- streamId = await soundPool.play(soundId);
- //Stop playing in the background scenario: soundPool.stop (streamId);
- // [End sound_pool]
-}
\ No newline at end of file
+ }) // '/test_01.mp3' is used as an example. The path of the file needs to be transferred
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `avPlayer stop failed, code=${err.code}, message=${err.message}`);
+ })
+ await soundPool.load(uri)
+ .then((soundId: number) => {
+ //The foreground scene starts to play
+ soundPool.play(soundId)
+ .then((data: number) => {
+ streamId = data;
+ hilog.info(0x000, 'testTag', 'setPreferredOrientation success');
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `soundPool play failed, code=${err.code}, message=${err.message}`);
+ })
+ //Stop playing in the background scenario: soundPool.stop (streamId);
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `soundPool load failed, code=${err.code}, message=${err.message}`);
+ })
+}
+// [End sound_pool]
diff --git a/BptaUseResources/entry/src/main/ets/pages/music/OpenSL.cpp b/BptaUseResources/entry/src/main/ets/pages/music/OpenSL.cpp
deleted file mode 100644
index 23a867c9363ded2a61b64c68845df72723b832d1..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/main/ets/pages/music/OpenSL.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 最佳实践:合理使用音频资源
- * 场景三:播音场景(OpenSL ES)
- */
-
-// [Start open_sl_es]
-//The foreground scene starts to play
-SLPlayItfplayItf=nullptr;
-(*pcmPlayerObject)->GetInterface(pcmPlayerObject,SL_IID_PLAY,&playItf);
-(*playItf)->SetPlayState(playItf,SL_PLAYSTATE_PLAYING);
-// Stop playing the background scene
-(*playItf)->SetPlayState(playItf,SL_PLAYSTATE_STOPPED);
-(*pcmPlayerObject)->Destroy(pcmPlayerObject);
-(*engineObject)->Destroy(engineObject);
-// [End open_sl_es]
-
-/**
- * 最佳实践:合理使用音频资源
- * 场景四:播音场景(OHAudio)
- */
-
-// [Start oh_audio]
-//Construct the audio stream to play
-OH_AudioRenderer*audioRenderer;
-ret=OH_AudioStreamBuilder_GenerateRenderer(builder,&audioRenderer);
-
-//The foreground scene starts to play
-ret=OH_AudioRenderer_Start(audioRenderer);
-// Stop playing the background scene
-ret=OH_AudioRenderer_Stop(audioRenderer);
-// [End oh_audio]
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/main/module.json5 b/BptaUseResources/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..2695312b12d7bbaf393763583192e727d45ce5ac 100644
--- a/BptaUseResources/entry/src/main/module.json5
+++ b/BptaUseResources/entry/src/main/module.json5
@@ -5,9 +5,7 @@
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
- "phone",
- "tablet",
- "2in1"
+ "phone"
],
"deliveryWithInstall": true,
"installationFree": false,
@@ -45,7 +43,49 @@
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
- ],
+ ]
+ }
+ ],
+ "requestPermissions": [
+ {
+ "name": "ohos.permission.ACCESS_BLUETOOTH",
+ "reason": "$string:app_name",
+ "usedScene": {
+ "abilities": [
+ "EntryAbility"
+ ],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.APPROXIMATELY_LOCATION",
+ "reason": "$string:app_name",
+ "usedScene": {
+ "abilities": [
+ "EntryAbility"
+ ],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.ACCELEROMETER",
+ "reason": "$string:app_name",
+ "usedScene": {
+ "abilities": [
+ "EntryAbility"
+ ],
+ "when": "always"
+ }
+ },
+ {
+ "name": "ohos.permission.INTERNET",
+ "reason": "$string:app_name",
+ "usedScene": {
+ "abilities": [
+ "EntryAbility"
+ ],
+ "when": "always"
+ }
}
]
}
diff --git a/BptaUseResources/entry/src/main/resources/base/element/string.json b/BptaUseResources/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..6c3318398d1ad6008ddce90cb9435814a1ee3d41 100644
--- a/BptaUseResources/entry/src/main/resources/base/element/string.json
+++ b/BptaUseResources/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "BptaUseResources"
}
]
}
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/mock/mock-config.json5 b/BptaUseResources/entry/src/mock/mock-config.json5
deleted file mode 100644
index 7a73a41bfdf76d6f793007240d80983a52f15f97..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/mock/mock-config.json5
+++ /dev/null
@@ -1,2 +0,0 @@
-{
-}
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/ohosTest/ets/test/Ability.test.ets b/BptaUseResources/entry/src/ohosTest/ets/test/Ability.test.ets
deleted file mode 100644
index 85c78f67579d6e31b5f5aeea463e216b9b141048..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/ohosTest/ets/test/Ability.test.ets
+++ /dev/null
@@ -1,35 +0,0 @@
-import { hilog } from '@kit.PerformanceAnalysisKit';
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function abilityTest() {
- describe('ActsAbilityTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- })
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- })
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- })
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- })
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- })
- })
-}
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/ohosTest/ets/test/List.test.ets b/BptaUseResources/entry/src/ohosTest/ets/test/List.test.ets
deleted file mode 100644
index 794c7dc4ed66bd98fa3865e07922906e2fcef545..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/ohosTest/ets/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import abilityTest from './Ability.test';
-
-export default function testsuite() {
- abilityTest();
-}
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/ohosTest/module.json5 b/BptaUseResources/entry/src/ohosTest/module.json5
deleted file mode 100644
index 55725a929993a8a18b3808d41ef037759440488b..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/ohosTest/module.json5
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "module": {
- "name": "entry_test",
- "type": "feature",
- "deviceTypes": [
- "phone",
- "tablet",
- "2in1"
- ],
- "deliveryWithInstall": true,
- "installationFree": false
- }
-}
diff --git a/BptaUseResources/entry/src/test/List.test.ets b/BptaUseResources/entry/src/test/List.test.ets
deleted file mode 100644
index bb5b5c3731e283dd507c847560ee59bde477bbc7..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import localUnitTest from './LocalUnit.test';
-
-export default function testsuite() {
- localUnitTest();
-}
\ No newline at end of file
diff --git a/BptaUseResources/entry/src/test/LocalUnit.test.ets b/BptaUseResources/entry/src/test/LocalUnit.test.ets
deleted file mode 100644
index 165fc1615ee8618b4cb6a622f144a9a707eee99f..0000000000000000000000000000000000000000
--- a/BptaUseResources/entry/src/test/LocalUnit.test.ets
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function localUnitTest() {
- describe('localUnitTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- });
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- });
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- });
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- });
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- });
- });
-}
\ No newline at end of file
diff --git a/BptaUseResources/oh-package-lock.json5 b/BptaUseResources/oh-package-lock.json5
deleted file mode 100644
index 7fcf818273347b97063c0c0a151bb14770ca1c79..0000000000000000000000000000000000000000
--- a/BptaUseResources/oh-package-lock.json5
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "meta": {
- "stableOrder": true
- },
- "lockfileVersion": 3,
- "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
- "specifiers": {
- "@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0",
- "@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21"
- },
- "packages": {
- "@ohos/hamock@1.0.0": {
- "name": "@ohos/hamock",
- "version": "1.0.0",
- "integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==",
- "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hamock/-/hamock-1.0.0.har",
- "registryType": "ohpm"
- },
- "@ohos/hypium@1.0.21": {
- "name": "@ohos/hypium",
- "version": "1.0.21",
- "integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==",
- "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.21.har",
- "registryType": "ohpm"
- }
- }
-}
\ No newline at end of file
diff --git a/BptaUseSoftware/.gitignore b/BptaUseSoftware/.gitignore
deleted file mode 100644
index d2ff20141ceed86d87c0ea5d99481973005bab2b..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-/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/BptaUseSoftware/README.md b/BptaUseSoftware/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..1a2f33a56bbc27d5108accdc784831d5ec2bc99b
--- /dev/null
+++ b/BptaUseSoftware/README.md
@@ -0,0 +1,62 @@
+# 后台软件资源合理使用样例代码工程
+
+### 介绍
+
+本示例为后台软件资源合理使用样例代码工程,包含最佳实践文档中的后台上传下载合理使用、后台音频播放合理使用、后台定位导航服务合理使用、后台系统资源合理使用等内容的局部样例代码。工程本身不具备实际功能,开发者请直接阅读具体源码结合文档来理解。
+
+
+### 效果预览
+
+不涉及
+
+### 工程目录
+```
+├──entry/src/main/ets
+│ ├──entryability
+│ │ └──EntryAbility.ets // 程序入口类
+│ ├──entrybackupability
+│ │ └──EntryBackupAbility.ets // 应用数据备份恢复类
+│ └──pages
+│ ├─Audio.ets // 音频类示例代码
+│ ├─Download.ets // 上传下载示例代码
+│ ├─GpsOne.ets // 定位导航服务示例代码1
+│ ├─GpsTwo.ets // 定位导航服务示例代码2
+│ ├─Index.ets // 首页
+│ ├─LockByApplication.ets // 系统资源示例代码1
+│ ├─LockBySystem.ets // 系统资源示例代码2
+│ └─Upload.ets // 上传下载类示例代码
+└──entry/src/main/resources // 应用静态资源目录
+```
+
+### 具体实现
+
+不涉及。
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机、华为PC/2in1设备、华为平板。
+
+2. HarmonyOS系统:HarmonyOS NEXT 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio NEXT 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS NEXT 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set BptaUseSoftware
+git checkout
+```
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/.gitignore b/BptaUseSoftware/entry/.gitignore
deleted file mode 100644
index e2713a2779c5a3e0eb879efe6115455592caeea5..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-/node_modules
-/oh_modules
-/.preview
-/build
-/.cxx
-/.test
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/src/main/ets/entryability/EntryAbility.ets b/BptaUseSoftware/entry/src/main/ets/entryability/EntryAbility.ets
index ea1bd6886f92a2fa8bc8e31b646d47ebf620f2a9..2d0f5e06e283a254cbc63c81e2cf6b69754cb4b7 100644
--- a/BptaUseSoftware/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/BptaUseSoftware/entry/src/main/ets/entryability/EntryAbility.ets
@@ -1,4 +1,5 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -6,7 +7,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
@@ -24,8 +30,13 @@ export default class EntryAbility extends UIAbility {
return;
}
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
- let uiContext: UIContext | undefined = windowStage.getMainWindowSync().getUIContext()
- AppStorage.setOrCreate('uiContext', uiContext);
+ try {
+ let uiContext: UIContext | undefined = windowStage.getMainWindowSync().getUIContext()
+ AppStorage.setOrCreate('uiContext', uiContext);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `getUIContext failed, code=${err.code}, message=${err.message}`);
+ }
});
}
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/Audio.ets b/BptaUseSoftware/entry/src/main/ets/pages/Audio.ets
index b1d823641545e3a90209c4a25fd63cd3b8ec300f..415bb3e629fc7a2d775f185815bceddde34844b2 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/Audio.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/Audio.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:合理使用音频播放
*/
@@ -6,6 +21,8 @@
import { fileIo as fs } from '@kit.CoreFileKit';
// [StartExclude audio_bpta]
import { audio } from '@kit.AudioKit';
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
let audioStreamInfo: audio.AudioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
@@ -43,9 +60,13 @@ async function read() {
let path = context.filesDir; // Path of the file
const filePath = path + '/voice_call_data.wav'; // Prohibit the file from being played silently
- let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY); // Open the file
- let buf = new ArrayBuffer(bufferSize);
- let readSize: number = await fs.read(file.fd, buf); // Read the file content
- let writeSize: number = await audioRenderer.write(buf); // Play the file content
+ try {
+ let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY); // Open the file
+ let buf = new ArrayBuffer(bufferSize);
+ let readSize: number = await fs.read(file.fd, buf); // Read the file content
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `openSync or read failed, code=${err.code}, message=${err.message}`);
+ }
}
// [End audio_bpta]
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/Download.ets b/BptaUseSoftware/entry/src/main/ets/pages/Download.ets
index f48d442ea24adb5f153788568e5b319ecdf86f2b..8691ab2add75ce930f1a047ad6f7679626c6a651 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/Download.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/Download.ets
@@ -1,23 +1,54 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:后台合理使用上传下载
* 场景二:下载
*/
-
// [Start software_download]
import { BusinessError, request } from '@kit.BasicServicesKit';
+import { common } from '@kit.AbilityKit';
+
+// [End software_download]
-try {
- request.downloadFile(this.getUIContext().getHostContext(), {
- url: 'https://xxxx/xxxxx.hap', // IP address of the server to download the file
- filePath: 'xxx/xxxxx.hap'
- }, (err: BusinessError, data: request.DownloadTask) => {
- if (err) {
- console.error(`Failedtorequestthedownload.Code:${err.code},message:${err.message}`);
- return;
+@Entry
+@Component
+struct Download {
+ build() {
+ }
+
+
+ funcA() {
+ // [Start software_download]
+ try {
+ let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
+ request.downloadFile(context, {
+ url: 'https://xxxx/xxxxx.hap', // IP address of the server to download the file
+ filePath: 'xxx/xxxxx.hap'
+ }, (err: BusinessError, data: request.DownloadTask) => {
+ if (err) {
+ console.error(`Failedtorequestthedownload.Code:${err.code},message:${err.message}`);
+ return;
+ }
+ let downloadTask: request.DownloadTask = data;
+ });
+ } catch (err) {
+ console.error(`Failedtorequestthedownload.err:${JSON.stringify(err)}`);
}
- let downloadTask: request.DownloadTask = data;
- });
-} catch (err) {
- console.error(`Failedtorequestthedownload.err:${JSON.stringify(err)}`);
+ // [End software_download]
+ }
}
-// [End software_download]
\ No newline at end of file
+
+
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/GpsOne.ets b/BptaUseSoftware/entry/src/main/ets/pages/GpsOne.ets
index 46c3c4f46d75eda0667aa9dde5bd694ec8db7fb4..3ddcde7939f8ac5f6dedae934b45e1a026497e2e 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/GpsOne.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/GpsOne.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:后台合理使用定位导航服务
* 场景一:方式1
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/GpsTwo.ets b/BptaUseSoftware/entry/src/main/ets/pages/GpsTwo.ets
index a3661fd5e8014e3c80410b817e5a8a0c75662ad5..fa9124056a4fe7bde06ea83aa6d42fe4aa0636d7 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/GpsTwo.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/GpsTwo.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:后台合理使用定位导航服务
* 场景二:方式2
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/Index.ets b/BptaUseSoftware/entry/src/main/ets/pages/Index.ets
index 8e2d24ad42693fc877d51bb7820f0a9da68fa135..0f481f696485b8c840d49ad9e7d7dff7f6b71241 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/Index.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/Index.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
@Entry
@Component
struct Index {
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/LockByApplication.ets b/BptaUseSoftware/entry/src/main/ets/pages/LockByApplication.ets
index 236f0d5bc4d351d30cd3ff27711b1cc39c1afa27..fe063ec6ba797c814bfc54fea61815019bba22fe 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/LockByApplication.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/LockByApplication.ets
@@ -1,15 +1,36 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:后台合理使用系统资源
* 场景一:应用直接持锁
*/
// [Start bpta_lock_by_application]
import { runningLock } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { BusinessError } from '@kit.BasicServicesKit';
// Return to the background to release the lock
runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND)
.then((lock: runningLock.RunningLock) => {
- lock.unhold();
- console.info('create running lock and unlock success');
+ try {
+ lock.unhold();
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
})
.catch((err: Error) => {
console.error('create running lock failed, err: ' + err);
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/LockBySystem.ets b/BptaUseSoftware/entry/src/main/ets/pages/LockBySystem.ets
index ba481213a06987c151297f6967ee7eda5af5a0cd..37dd742f201cd991973db9bba9636a555d6db862 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/LockBySystem.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/LockBySystem.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:后台合理使用系统资源
* 场景一:系统帮助应用持锁
diff --git a/BptaUseSoftware/entry/src/main/ets/pages/Upload.ets b/BptaUseSoftware/entry/src/main/ets/pages/Upload.ets
index 56f5cb42e1dc13eef4931028aec8a6f32dc47156..902ecae1a1fd59d7025813be306a6355f82316cc 100644
--- a/BptaUseSoftware/entry/src/main/ets/pages/Upload.ets
+++ b/BptaUseSoftware/entry/src/main/ets/pages/Upload.ets
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
/**
* 最佳实践:后台合理使用上传下载
* 场景一:上传
diff --git a/BptaUseSoftware/entry/src/main/module.json5 b/BptaUseSoftware/entry/src/main/module.json5
index a1cea8b6a4560cee7bda7a2db52f310c035ab6c8..1da6fb5663deb76fabe8914ebe7bb408f54e52c9 100644
--- a/BptaUseSoftware/entry/src/main/module.json5
+++ b/BptaUseSoftware/entry/src/main/module.json5
@@ -45,7 +45,15 @@
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
- ],
+ ]
+ }
+ ],
+ "requestPermissions": [
+ {
+ "name": "ohos.permission.RUNNING_LOCK"
+ },
+ {
+ "name": "ohos.permission.INTERNET"
}
]
}
diff --git a/BptaUseSoftware/entry/src/mock/mock-config.json5 b/BptaUseSoftware/entry/src/mock/mock-config.json5
deleted file mode 100644
index 7a73a41bfdf76d6f793007240d80983a52f15f97..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/src/mock/mock-config.json5
+++ /dev/null
@@ -1,2 +0,0 @@
-{
-}
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/src/ohosTest/ets/test/Ability.test.ets b/BptaUseSoftware/entry/src/ohosTest/ets/test/Ability.test.ets
deleted file mode 100644
index 85c78f67579d6e31b5f5aeea463e216b9b141048..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/src/ohosTest/ets/test/Ability.test.ets
+++ /dev/null
@@ -1,35 +0,0 @@
-import { hilog } from '@kit.PerformanceAnalysisKit';
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function abilityTest() {
- describe('ActsAbilityTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- })
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- })
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- })
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- })
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- })
- })
-}
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/src/ohosTest/ets/test/List.test.ets b/BptaUseSoftware/entry/src/ohosTest/ets/test/List.test.ets
deleted file mode 100644
index 794c7dc4ed66bd98fa3865e07922906e2fcef545..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/src/ohosTest/ets/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import abilityTest from './Ability.test';
-
-export default function testsuite() {
- abilityTest();
-}
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/src/ohosTest/module.json5 b/BptaUseSoftware/entry/src/ohosTest/module.json5
deleted file mode 100644
index 55725a929993a8a18b3808d41ef037759440488b..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/src/ohosTest/module.json5
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "module": {
- "name": "entry_test",
- "type": "feature",
- "deviceTypes": [
- "phone",
- "tablet",
- "2in1"
- ],
- "deliveryWithInstall": true,
- "installationFree": false
- }
-}
diff --git a/BptaUseSoftware/entry/src/test/List.test.ets b/BptaUseSoftware/entry/src/test/List.test.ets
deleted file mode 100644
index bb5b5c3731e283dd507c847560ee59bde477bbc7..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/src/test/List.test.ets
+++ /dev/null
@@ -1,5 +0,0 @@
-import localUnitTest from './LocalUnit.test';
-
-export default function testsuite() {
- localUnitTest();
-}
\ No newline at end of file
diff --git a/BptaUseSoftware/entry/src/test/LocalUnit.test.ets b/BptaUseSoftware/entry/src/test/LocalUnit.test.ets
deleted file mode 100644
index 165fc1615ee8618b4cb6a622f144a9a707eee99f..0000000000000000000000000000000000000000
--- a/BptaUseSoftware/entry/src/test/LocalUnit.test.ets
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
-
-export default function localUnitTest() {
- describe('localUnitTest', () => {
- // Defines a test suite. Two parameters are supported: test suite name and test suite function.
- beforeAll(() => {
- // Presets an action, which is performed only once before all test cases of the test suite start.
- // This API supports only one parameter: preset action function.
- });
- beforeEach(() => {
- // Presets an action, which is performed before each unit test case starts.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: preset action function.
- });
- afterEach(() => {
- // Presets a clear action, which is performed after each unit test case ends.
- // The number of execution times is the same as the number of test cases defined by **it**.
- // This API supports only one parameter: clear action function.
- });
- afterAll(() => {
- // Presets a clear action, which is performed after all test cases of the test suite end.
- // This API supports only one parameter: clear action function.
- });
- it('assertContain', 0, () => {
- // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
- let a = 'abc';
- let b = 'b';
- // Defines a variety of assertion methods, which are used to declare expected boolean conditions.
- expect(a).assertContain(b);
- expect(a).assertEqual(a);
- });
- });
-}
\ No newline at end of file
diff --git a/BptaUseSoftware/oh-package.json5 b/BptaUseSoftware/oh-package.json5
index a8aff0c5aff22d78aa26fd19c3861f4320e951ff..f440d114b8a9d9aeadd0e891bba0d0d076e70936 100644
--- a/BptaUseSoftware/oh-package.json5
+++ b/BptaUseSoftware/oh-package.json5
@@ -3,8 +3,5 @@
"description": "Please describe the basic information.",
"dependencies": {
},
- "devDependencies": {
- "@ohos/hypium": "1.0.21",
- "@ohos/hamock": "1.0.0"
- }
+ "devDependencies": {}
}
diff --git a/CanvasDraw/build-profile.json5 b/CanvasDraw/build-profile.json5
index 19b2d1d0b868064df8c461ecdbbdbb5f6755b07f..e5f3b3c8a7cc93d377d31d5616c9c5603a009d63 100644
--- a/CanvasDraw/build-profile.json5
+++ b/CanvasDraw/build-profile.json5
@@ -20,7 +20,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "targetSdkVersion": "5.0.5(17)",
+ "compatibleSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
}
],
diff --git a/ClickResponseOptimization/.gitignore b/ClickResponseOptimization/.gitignore
deleted file mode 100644
index d2ff20141ceed86d87c0ea5d99481973005bab2b..0000000000000000000000000000000000000000
--- a/ClickResponseOptimization/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-/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/ClickResponseOptimization/README.en.md b/ClickResponseOptimization/README.en.md
deleted file mode 100644
index 9d38a44356b0addb0ce8c11f883c622ae9a9dc9e..0000000000000000000000000000000000000000
--- a/ClickResponseOptimization/README.en.md
+++ /dev/null
@@ -1,4 +0,0 @@
-
-### Introduction
-
-Sample codes accompanying the best practice articles "Click Response Delay Analysis" and "Click Response Optimization"
diff --git a/ClickResponseOptimization/README.md b/ClickResponseOptimization/README.md
index ce522f87e3870661daa9d23eaab66a6e76d39606..71d7913acc6fbbe222edba05690edf4df6cd1bf0 100644
--- a/ClickResponseOptimization/README.md
+++ b/ClickResponseOptimization/README.md
@@ -1,4 +1,74 @@
+# 点击响应时延分析
-### 简介
+### 介绍
-与最佳实践文章《点击响应时延分析》和《点击响应优化》配套的示例代码
+本示例是《点击响应时延分析》最佳实践中的代码示例片段。
+
+### 使用说明
+
+进入首面,加载示例逻辑。
+
+
+### 工程目录
+
+```
+├──entry/src/main/ets
+│ ├──common/constants
+│ │ ├──AppConstant.ets // app常量
+│ │ ├──ChatConstants.ets // chat常量
+│ │ ├──WorldCommonConstants.ets // 公共常量
+│ │ └──WorldConstants.ets // 公共常量
+│ ├──common/db
+│ │ ├──AccountData.ets // account数据
+│ │ ├──AccountTable.ets // account表
+│ │ └──Rdb.ets // rdb工具类
+│ ├──entryability
+│ │ └──EntryAbility.ets // 入口类
+│ ├──model
+│ │ └──ChatModel.ets // chat数据模型
+│ ├──pages
+│ │ ├──CameraOptPage.ets // 示例页面
+│ │ ├──CameraPage.ets // 示例页面
+│ │ ├──CityListPage.ets // 示例页面
+│ │ ├──ConcurrentOptPage.ets // 示例页面
+│ │ ├──Index.ets // 首页
+│ │ ├──PanGestureDistanceOptPage.ets // 示例页面
+│ │ ├──PanGestureDistancePage.ets // 示例页面
+│ │ ├──ProfilePage.ets // 示例页面
+│ │ └──VisionOptPage.ets // 示例页面
+│ └──view
+│ ├──ArticleSkeletonView.ets // 骨架屏view
+│ ├──LoadingView.ets // 加载view
+│ └──OptChatItemView.ets // 优化后的chat view
+└──entry/src/main/resources // 应用资源目录
+```
+
+
+### 具体实现
+
+1. 针对点击响应时延分析经,介绍这方面的常见性能优化方法。
+
+### 相关权限
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机。
+
+2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ClickResponseOptimization
+git checkout
+```
\ No newline at end of file
diff --git a/ClickResponseOptimization/build-profile.json5 b/ClickResponseOptimization/build-profile.json5
index c033ce4278fb0641d84107c3c134047ac487368e..a33e1f2b1fb22dcb09d8042de60fd767ec874a2a 100644
--- a/ClickResponseOptimization/build-profile.json5
+++ b/ClickResponseOptimization/build-profile.json5
@@ -5,7 +5,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "targetSdkVersion": "5.0.5(17)",
+ "compatibleSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
}
],
diff --git a/ClickResponseOptimization/entry/.gitignore b/ClickResponseOptimization/entry/.gitignore
deleted file mode 100644
index e2713a2779c5a3e0eb879efe6115455592caeea5..0000000000000000000000000000000000000000
--- a/ClickResponseOptimization/entry/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-/node_modules
-/oh_modules
-/.preview
-/build
-/.cxx
-/.test
\ No newline at end of file
diff --git a/ClickResponseOptimization/entry/obfuscation-rules.txt b/ClickResponseOptimization/entry/obfuscation-rules.txt
index 985b2aeb7658286b17bd26eab8f217c3fe75ea8b..a1dfa0bd175984dc49e641436aa67b1de1b8abeb 100644
--- a/ClickResponseOptimization/entry/obfuscation-rules.txt
+++ b/ClickResponseOptimization/entry/obfuscation-rules.txt
@@ -15,4 +15,8 @@
# 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
+# -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/ClickResponseOptimization/entry/src/main/ets/pages/CityListPage.ets b/ClickResponseOptimization/entry/src/main/ets/pages/CityListPage.ets
index a681610fb040e908915e2358c1f279f390c53b0d..c4e7e8dd96a8ec7849e8efa6ef6118e25250eaa1 100644
--- a/ClickResponseOptimization/entry/src/main/ets/pages/CityListPage.ets
+++ b/ClickResponseOptimization/entry/src/main/ets/pages/CityListPage.ets
@@ -20,7 +20,10 @@ import taskpool from '@ohos.taskpool';
import hiTraceMeter from '@ohos.hiTraceMeter';
import { AppConstant } from '../common/constants/AppConstant';
import router from '@ohos.router';
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+const DOMAIN = 0x0000;
const alphabets = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
@@ -52,9 +55,15 @@ struct CityList {
// asynchronous thread
computeTaskAsync() {
let task: taskpool.Task = new taskpool.Task(computeTask);
- taskpool.execute(task).then((res) => {
- this.citys = res as string[]
- })
+ try {
+ taskpool.execute(task).then((res) => {
+ this.citys = res as string[]
+ });
+ } catch (e) {
+ let err = e as BusinessError;
+ hilog.error(DOMAIN, 'testTag', `failed code=${err.code}, message=${err.message}`);
+ }
+
}
// [StartExclude onpage_show]
diff --git a/ClickResponseOptimization/entry/src/main/resources/base/element/string.json b/ClickResponseOptimization/entry/src/main/resources/base/element/string.json
index f94595515a99e0c828807e243494f57f09251930..c622bd7ced26f4ec40d3baefc11a90f1502469db 100644
--- a/ClickResponseOptimization/entry/src/main/resources/base/element/string.json
+++ b/ClickResponseOptimization/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "ClickResponseOptimization"
}
]
}
\ No newline at end of file
diff --git a/ClickResponseOptimization/entry/src/main/resources/en_US/element/string.json b/ClickResponseOptimization/entry/src/main/resources/en_US/element/string.json
index f94595515a99e0c828807e243494f57f09251930..c622bd7ced26f4ec40d3baefc11a90f1502469db 100644
--- a/ClickResponseOptimization/entry/src/main/resources/en_US/element/string.json
+++ b/ClickResponseOptimization/entry/src/main/resources/en_US/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "ClickResponseOptimization"
}
]
}
\ No newline at end of file
diff --git a/ClickResponseOptimization/entry/src/main/resources/zh_CN/element/string.json b/ClickResponseOptimization/entry/src/main/resources/zh_CN/element/string.json
index 597ecf95e61d7e30367c22fe2f8638008361b044..c999478abae583b3eaa8c936905ab327cb3d5127 100644
--- a/ClickResponseOptimization/entry/src/main/resources/zh_CN/element/string.json
+++ b/ClickResponseOptimization/entry/src/main/resources/zh_CN/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "点击响应优化"
}
]
}
\ No newline at end of file
diff --git a/ComponentEncapsulation/README.md b/ComponentEncapsulation/README.md
index 93420a375eca3eaad8685b0600b9693b6a0bffe0..fe88e79f131c18cdc7d2be627c0d081d44282841 100644
--- a/ComponentEncapsulation/README.md
+++ b/ComponentEncapsulation/README.md
@@ -4,7 +4,7 @@
本示例展示组件封装中的常见问题代码。
-##### 使用说明
+### 使用说明
进入首面,点击按钮,分别进入示例页面。
@@ -42,4 +42,15 @@
3. DevEco Studio版本:DevEco Studio 5.1.0 Release及以上。
-4. HarmonyOS SDK版本:HarmonyOS 5.1.0 Release SDK及以上。
\ No newline at end of file
+4. HarmonyOS SDK版本:HarmonyOS 5.1.0 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ComponentEncapsulation
+git checkout
+```
\ No newline at end of file
diff --git a/ComponentEncapsulation/entry/src/main/ets/entryability/EntryAbility.ets b/ComponentEncapsulation/entry/src/main/ets/entryability/EntryAbility.ets
index 2dae1b50919e646712c2dea0429b084b1ab2647b..89f547e65f66f3007f43211a90c5fc4753004bce 100644
--- a/ComponentEncapsulation/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ComponentEncapsulation/entry/src/main/ets/entryability/EntryAbility.ets
@@ -13,6 +13,7 @@
* limitations under the License.
*/
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
+import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
@@ -20,7 +21,12 @@ const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ try {
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `setColorMode failed, code=${err.code}, message=${err.message}`);
+ }
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
diff --git a/ComponentEncapsulation/entry/src/main/ets/pages/Index.ets b/ComponentEncapsulation/entry/src/main/ets/pages/Index.ets
index 550bf16fdb7463f5b865a6e1c8c172d31f91b5d4..9730d0f240a698ef07319ad9749bd1942fe92c65 100644
--- a/ComponentEncapsulation/entry/src/main/ets/pages/Index.ets
+++ b/ComponentEncapsulation/entry/src/main/ets/pages/Index.ets
@@ -1,3 +1,5 @@
+import { hilog } from '@kit.PerformanceAnalysisKit';
+
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,6 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
+import { BusinessError } from '@kit.BasicServicesKit';
+
@Entry
@Component
struct Index {
@@ -21,26 +26,56 @@ struct Index {
.width(120).margin({ top: 16 })
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/BuilderParamPage' })
+ .then(() => {
+ hilog.info(0x000, 'testTag', 'pushUrl success');
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `pushUrl failed, code=${err.code}, message=${err.message}`);
+ })
})
Button('ControllerCallPage')
.width(120).margin({ top: 16 })
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/ControllerCallPage' })
+ .then(() => {
+ hilog.info(0x000, 'testTag', 'pushUrl success');
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `pushUrl failed, code=${err.code}, message=${err.message}`);
+ })
})
Button('EmitterCallPage')
.width(120).margin({ top: 16 })
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/EmitterCallPage' })
+ .then(() => {
+ hilog.info(0x000, 'testTag', 'pushUrl success');
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `pushUrl failed, code=${err.code}, message=${err.message}`);
+ })
})
Button('ParentCallPage')
.width(120).margin({ top: 16 })
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/ParentCallPage' })
+ .then(() => {
+ hilog.info(0x000, 'testTag', 'pushUrl success');
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `pushUrl failed, code=${err.code}, message=${err.message}`);
+ })
})
Button('WatchCallPage')
.width(120).margin({ top: 16 })
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/WatchCallPage' })
+ .then(() => {
+ hilog.info(0x000, 'testTag', 'pushUrl success');
+ })
+ .catch((err: BusinessError) => {
+ hilog.error(0x000, 'testTag', `pushUrl failed, code=${err.code}, message=${err.message}`);
+ })
})
}
.height('100%')
diff --git a/ComponentEncapsulation/entry/src/main/ets/pages/ParentCallPage.ets b/ComponentEncapsulation/entry/src/main/ets/pages/ParentCallPage.ets
index c906ba0533a646335f32094dd6543fb57fbab681..2f5cc59d3d73c40abfa591ae70422ebbb56710bf 100644
--- a/ComponentEncapsulation/entry/src/main/ets/pages/ParentCallPage.ets
+++ b/ComponentEncapsulation/entry/src/main/ets/pages/ParentCallPage.ets
@@ -13,6 +13,9 @@
* limitations under the License.
*/
// [Start parent_call]
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
+
@Component
export struct ChildComponent {
call = () => {
@@ -32,7 +35,12 @@ export struct ChildComponent {
@Component
struct Index {
parentAction() {
- this.getUIContext().getPromptAction().showToast({ message: 'Parent Action' })
+ try {
+ this.getUIContext().getPromptAction().showToast({ message: 'Parent Action' });
+ } catch (error) {
+ let err = error as BusinessError;
+ hilog.warn(0x000, 'testTag', `showToast failed, code=${err.code}, message=${err.message}`);
+ }
}
build() {
diff --git a/ComponentReuse/.idea/vcs.xml b/ComponentReuse/.idea/vcs.xml
deleted file mode 100644
index 6c0b8635858dc7ad44b93df54b762707ce49eefc..0000000000000000000000000000000000000000
--- a/ComponentReuse/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/ComponentReuse/.idea/workspace.xml b/ComponentReuse/.idea/workspace.xml
deleted file mode 100644
index aa7035bfde535a189ae87072a34953d6ce847616..0000000000000000000000000000000000000000
--- a/ComponentReuse/.idea/workspace.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/ComponentReuse/README.md b/ComponentReuse/README.md
index a80fde3f487d85235cdb2e2edab05d2797607aa7..44865381250786e2c8d1a788e74d4f9f812ab21a 100644
--- a/ComponentReuse/README.md
+++ b/ComponentReuse/README.md
@@ -3,8 +3,7 @@
### 介绍
HarmonyOS应用框架提供了组件复用能力:可复用组件树上移除时,会进入一个回收缓存区,后续创建新组件节点时,会复用缓存区中的节点,节约组件重新创建的时间。
-本工程配套官网[组件复用最佳实践](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-component-reuse),
-文章介绍如何使用组件复用机制提升应用帧率。
+
### 预览效果
@@ -16,18 +15,24 @@ HarmonyOS应用框架提供了组件复用能力:可复用组件树上移除
|-----------------------------------------|-----------------------------------------|
|  |  |
-#### 使用说明
+### 使用说明
-1. 点击“减少组件复用的嵌套层级”按钮,进入二级页面“附近的人”, 滑动列表。
-2. 点击“精准控制组件刷新范围”按钮,进入二级页面“附近的人”, 滑动列表。
-3. 点击“使用reuseId标记不同的组件”按钮,进入二级页面“附近的人”, 滑动列表。
-4. 点击“复用组件创建时的@State变量入参”按钮,进入二级页面“附近的人”, 滑动列表。
+#### 选择entry模块运行
+1. 点击“减少组件复用的嵌套层级”按钮,进入二级页面, 滑动列表。
+2. 点击“精准控制组件刷新范围”按钮,进入二级页面, 滑动列表。
+3. 点击“使用reuseId标记不同的组件”按钮,进入二级页面, 滑动列表。
+4. 点击“复用组件创建时的@State变量入参”按钮,进入二级页面, 滑动列表。
+#### 选择negative或positive模块运行
+可使用Tools-AppAnalyzer体检工具,
+验证最佳实践[组件复用问题诊断分析](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-component-reuse-issue-diagnosis-and-analysis)
+中的反例或正例代码。
-## 工程目录
+### 工程目录
```
├──entry/src/main/ets
│ ├──common
+│ │ ├──CommonConstants.ets // 组件复用DataSource类
│ │ ├──Constants.ets // 公共常量
│ │ └──GlobalBuilderContext.ets // 缓存全局@Builder
│ ├──entryability
@@ -38,8 +43,11 @@ HarmonyOS应用框架提供了组件复用能力:可复用组件树上移除
│ │ ├──BasicDataSource.ets // 数据适配器基类
│ │ ├──ColorData.ets // 二级页面“文字列表”的数据适配器
│ │ └──FriendMomentData.ets // 二级页面“附近的人”/“图文列表”/“网名列表”的数据适配器
-│ ├──pages.ets
-│ │ └──Index.ets // 首页
+│ ├──pages
+│ │ ├──ImproveReuseHitRate.ets // 提升复用命中率
+│ │ ├──Index.ets // 首页
+│ │ ├──ReuseNested.ets // 复用嵌套
+│ │ └──UseComponentReuse.ets // 使用组件复用
│ └──view
│ ├──OneMoment.ets // 二级页面“附近的人”中列表的每条item UI
│ ├──PageListSlideToHistory.ets // 二级页面“附近的人”UI
@@ -53,9 +61,20 @@ HarmonyOS应用框架提供了组件复用能力:可复用组件树上移除
不涉及
-## 约束与限制
+### 约束与限制
* 本示例仅支持标准系统上运行,支持设备:华为手机。
-* HarmonyOS系统:HarmonyOS 5.0.0 Release及以上。
-* DevEco Studio版本:DevEco Studio 5.0.0 Release及以上。
-* HarmonyOS SDK版本:HarmonyOS 5.0.0 Release SDK及以上。
\ No newline at end of file
+* HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。
+* DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+* HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ComponentReuse
+git checkout
+```
\ No newline at end of file
diff --git a/ComponentReuse/README_EN.md b/ComponentReuse/README_EN.md
index 4d88d2be83056664679bb05eb24534489fa18e88..199a8821a476bc7e8bd6c056b53125fa7bd57945 100644
--- a/ComponentReuse/README_EN.md
+++ b/ComponentReuse/README_EN.md
@@ -3,8 +3,6 @@
### Overview
The HarmonyOS application framework provides the component reuse capability. When a reusable component is removed from the component tree, it enters a recycling buffer. When a new component node is created, the node in the buffer is reused, saving the time for recreating the component.
-This sample is used with the [Best Practices for Component Reuse](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-component-reuse).
-The practices describe how to use the component reuse mechanism to improve the application frame rate.
### Preview
@@ -18,16 +16,23 @@ The practices describe how to use the component reuse mechanism to improve the a
#### How to Use
+#### Choose entry module to Run
1. Tap **Reducing component reuse nesting** to enter **Nearby people** on the level-2 page, and slide the list.
2. Tap **Precisely controlling the component update scope** to enter **Text list** on the level-2 page, and slide the list.
3. Tap **Using reuseId to mark different components** to enter **Image-text list** on the level-2 page, and slide the list.
4. Tap **Using @State as input parameter for reusable components** to enter **Username list** on the level-2 page, and slide the list.
-## Project Directory
+#### Choose negative or positive module to Run
+You can use the Tools-AppAnalyzer health check tool,
+Verification Best Practices [Component Reuse Issue Diagnosis and Analysis](https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-component-reuse-issue-diagnosis-and-analysis)
+negative examples or positive examples in code.
+
+### Project Directory
```
├──entry/src/main/ets
│ ├──common
+│ │ ├──CommonConstants.ets // Component reuse DataSource class
│ │ ├──Constants.ets // Common constants
│ │ └──GlobalBuilderContext.ets // Caching the global @Builder
│ ├──entryability
@@ -38,8 +43,11 @@ The practices describe how to use the component reuse mechanism to improve the a
│ │ ├──BasicDataSource.ets // Basic data adapter
│ │ ├──ColorData.ets // Data adapter of Text list on the level-2 page
│ │ └──FriendMomentData.ets // Data adapter of Nearby people, Image-text list, and Username list on the level-2 page
-│ ├──pages.ets
-│ │ └──Index.ets // Home page
+│ ├──pages
+│ │ ├──ImproveReuseHitRate.ets // Improve reuse HitRate
+│ │ ├──Index.ets // Home page
+│ │ ├──ReuseNested.ets // Reuse nested
+│ │ └──UseComponentReuse.ets // Use component reuse
│ └──view
│ ├──OneMoment.ets // Each item UI in Nearby people on the level-2 page
│ ├──PageListSlideToHistory.ets // Nearby people UI on the level-2 page
@@ -53,9 +61,20 @@ The practices describe how to use the component reuse mechanism to improve the a
N/A
-## Constraints
+### Constraints
* This sample is supported only on Huawei phones running the standard system.
-* The HarmonyOS version must be HarmonyOS 5.0.0 Release or later.
-* The DevEco Studio version must be DevEco Studio 5.0.0 Release or later.
-* The HarmonyOS SDK version must be HarmonyOS 5.0.0 Release SDK or later.
+* The HarmonyOS version must be HarmonyOS 5.0.5 Release or later.
+* The DevEco Studio version must be DevEco Studio 5.0.5 Release or later.
+* The HarmonyOS SDK version must be HarmonyOS 5.0.5 Release SDK or later.
+
+### Download
+
+To download this project separately, execute the following command:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set ComponentReuse
+git checkout
+```
diff --git a/ComponentReuse/build-profile.json5 b/ComponentReuse/build-profile.json5
index 90a9741e1b74bdafe09b7e6574aa2a84ee331425..2b8af09623cb36fb810098e4a4569d99d2132f98 100644
--- a/ComponentReuse/build-profile.json5
+++ b/ComponentReuse/build-profile.json5
@@ -4,7 +4,8 @@
{
"name": "default",
"signingConfig": "default",
- "compatibleSdkVersion": "5.0.0(12)",
+ "compatibleSdkVersion": "5.0.5(17)",
+ "targetSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
@@ -21,7 +22,8 @@
{
"name": "release"
}
- ]
+ ],
+ "signingConfigs": []
},
"modules": [
{
@@ -35,6 +37,30 @@
]
}
]
+ },
+ {
+ "name": "negative",
+ "srcPath": "./negative",
+ "targets": [
+ {
+ "name": "default",
+ "applyToProducts": [
+ "default"
+ ]
+ }
+ ]
+ },
+ {
+ "name": "positive",
+ "srcPath": "./positive",
+ "targets": [
+ {
+ "name": "default",
+ "applyToProducts": [
+ "default"
+ ]
+ }
+ ]
}
]
}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/entryability/EntryAbility.ets b/ComponentReuse/entry/src/main/ets/entryability/EntryAbility.ets
index 658b37ad825e994dbaae500a620986562981d06a..deafa0de972ea9cbb2c0be9cc2804c480e63dc4d 100644
--- a/ComponentReuse/entry/src/main/ets/entryability/EntryAbility.ets
+++ b/ComponentReuse/entry/src/main/ets/entryability/EntryAbility.ets
@@ -38,6 +38,8 @@ export default class EntryAbility extends UIAbility {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
+ let uiContext: UIContext | undefined = windowStage.getMainWindowSync().getUIContext();
+ AppStorage.setOrCreate('uiContext', uiContext);
this.windowClass = windowStage.getMainWindowSync();
this.windowClass.setWindowLayoutFullScreen(true).then(() => {
hilog.info(0x0000, 'testTag', 'Success in setting the window layout to full-screen mode.');
@@ -52,13 +54,18 @@ export default class EntryAbility extends UIAbility {
private immersive(): void {
let type: window.AvoidAreaType = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR;
- let avoidArea: window.AvoidArea = this.windowClass?.getWindowAvoidArea(type) as window.AvoidArea;
- let bottomRectHeight: number = avoidArea.bottomRect.height;
- AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
- type = window.AvoidAreaType.TYPE_SYSTEM;
- avoidArea = this.windowClass?.getWindowAvoidArea(type) as window.AvoidArea;
- let topRectHeight: number = avoidArea.topRect.height;
- AppStorage.setOrCreate('topRectHeight', topRectHeight);
+ try {
+ let avoidArea: window.AvoidArea = this.windowClass?.getWindowAvoidArea(type) as window.AvoidArea;
+ let bottomRectHeight: number = avoidArea.bottomRect.height;
+ AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);
+ type = window.AvoidAreaType.TYPE_SYSTEM;
+ avoidArea = this.windowClass?.getWindowAvoidArea(type) as window.AvoidArea;
+ let topRectHeight: number = avoidArea.topRect.height;
+ AppStorage.setOrCreate('topRectHeight', topRectHeight);
+ } catch (e) {
+ let err = e as BusinessError;
+ hilog.error(0x0000, 'testTag', `failed code=${err.code}, message=${err.message}`);
+ }
}
onWindowStageDestroy(): void {
diff --git a/ComponentReuse/entry/src/main/ets/model/ColorData.ets b/ComponentReuse/entry/src/main/ets/model/ColorData.ets
index 2477328f8f42ba7e28b93ca08a37ec7b22bb90b5..1133c0c78374e460d26e26e0c67f5bece3b9914b 100644
--- a/ComponentReuse/entry/src/main/ets/model/ColorData.ets
+++ b/ComponentReuse/entry/src/main/ets/model/ColorData.ets
@@ -14,9 +14,17 @@
*/
import { BasicDataSource, ColorModel } from './BasicDataSource';
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
export class ColorData extends BasicDataSource {
textColorData: Array = [];
+ private context: Context | undefined = undefined;
+
+ constructor(context?: Context) {
+ super();
+ this.context = context;
+ }
public totalCount(): number {
return this.textColorData.length;
@@ -38,13 +46,19 @@ export class ColorData extends BasicDataSource {
let color: Color[] =
[Color.Black, Color.Blue, Color.Red, Color.Green, Color.Pink, Color.Black, Color.Blue, Color.Red, Color.Green,
Color.Pink];
- for (let i = 0; i < 10; i++) {
- let colorModel: ColorModel = new ColorModel('', '', Color.White);
- colorModel.id = Math.floor(this.totalCount() / 10) + i.toString();
- colorModel.text =
- getContext().resourceManager.getStringSync($r('app.string.update_component_title'), parseInt(colorModel.id) + 1);
- colorModel.color = color[i];
- this.pushData(colorModel);
+ try {
+ for (let i = 0; i < 10; i++) {
+ let colorModel: ColorModel = new ColorModel('', '', Color.White);
+ colorModel.id = Math.floor(this.totalCount() / 10) + i.toString();
+ colorModel.text =
+ this.context!.resourceManager.getStringSync($r('app.string.update_component_title').id, parseInt(colorModel.id) + 1);
+ colorModel.color = color[i];
+ this.pushData(colorModel);
+ }
+ } catch (e) {
+ let err = e as BusinessError;
+ hilog.error(0x0000, 'testTag', `failed code=${err.code}, message=${err.message}`);
}
+
}
}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/model/FriendMomentData.ets b/ComponentReuse/entry/src/main/ets/model/FriendMomentData.ets
index d7cdbaef9672f94331277a89eae619a0646059bb..6a7970f12c877329fe0ebff97a4719f888a8b2d9 100644
--- a/ComponentReuse/entry/src/main/ets/model/FriendMomentData.ets
+++ b/ComponentReuse/entry/src/main/ets/model/FriendMomentData.ets
@@ -16,13 +16,17 @@
import { BasicDataSource, FriendMoment } from './BasicDataSource';
import { util } from '@kit.ArkTS';
import { Constants } from '../common/Constants';
+import { BusinessError } from '@kit.BasicServicesKit';
+import { hilog } from '@kit.PerformanceAnalysisKit';
export class FriendMomentsData extends BasicDataSource {
private friendMoments: Array = [];
private mode: string | undefined = '';
+ private context: Context | undefined = undefined;
- constructor(mode?: string) {
+ constructor(context?: Context,mode?: string) {
super();
+ this.context = context;
this.mode = mode;
}
@@ -43,22 +47,26 @@ export class FriendMomentsData extends BasicDataSource {
}
public async getFriendMomentFromRawFile(): Promise {
- const resourceManager = getContext().resourceManager;
- const res = await resourceManager.getRawFileContent('mockFriendMomentOneModelData.json');
- const textDecoder = util.TextDecoder.create();
- const friendMomentArray = (JSON.parse(textDecoder.decodeToString(res)) as FriendMomentsData).friendMoments;
-
- friendMomentArray.forEach(item => {
- if (item.id) {
- item.id = Math.floor(this.totalCount() / 10) + item.id;
- }
- item.userName = resourceManager.getStringSync($r('app.string.userName').id, parseInt(item.id) + 1);
- if (this.mode === Constants.NAV_DESTINATION_ITEM_3) {
- item.text = resourceManager.getStringSync($r('app.string.with_func_title'), parseInt(item.id) + 1);
- } else {
- item.text = resourceManager.getStringSync($r('app.string.jump_text_one'), parseInt(item.id) + 1);
- }
- this.pushData(item);
- })
+ const resourceManager = this.context!.resourceManager;
+ try {
+ const res = await resourceManager.getRawFileContent('mockFriendMomentOneModelData.json');
+ const textDecoder = util.TextDecoder.create();
+ const friendMomentArray = (JSON.parse(textDecoder.decodeToString(res)) as FriendMomentsData).friendMoments;
+ friendMomentArray.forEach(item => {
+ if (item.id) {
+ item.id = Math.floor(this.totalCount() / 10) + item.id;
+ }
+ item.userName = resourceManager.getStringSync($r('app.string.userName').id, parseInt(item.id) + 1);
+ if (this.mode === Constants.NAV_DESTINATION_ITEM_3) {
+ item.text = resourceManager.getStringSync($r('app.string.with_func_title').id, parseInt(item.id) + 1);
+ } else {
+ item.text = resourceManager.getStringSync($r('app.string.jump_text_one').id, parseInt(item.id) + 1);
+ }
+ this.pushData(item);
+ })
+ } catch (e) {
+ let err = e as BusinessError;
+ hilog.error(0x0000, 'testTag', `failed code=${err.code}, message=${err.message}`);
+ }
}
}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/model/ItemData.ets b/ComponentReuse/entry/src/main/ets/model/ItemData.ets
new file mode 100644
index 0000000000000000000000000000000000000000..313d871f343d0f3ab383041b8f3f0807af9a6da6
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/model/ItemData.ets
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Observed
+export class ItemData {
+ id: string = '';
+ title: string | Resource = '';
+ content: string = '';
+ from: string | Resource = '';
+ tail: string | Resource = '';
+ type: number = 0;
+ pics: Resource[] = [];
+ preview: Resource | string = '';
+ duration: string = '';
+ isShowTitle?: Visibility = Visibility.Hidden;
+
+ constructor(id: string, type: number) {
+ this.id = id;
+ this.type = type;
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/model/ItemDataSource.ets b/ComponentReuse/entry/src/main/ets/model/ItemDataSource.ets
new file mode 100644
index 0000000000000000000000000000000000000000..0056109375c97c16fa7075b877c94013a6d7fa4a
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/model/ItemDataSource.ets
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2025 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 { ItemData } from './ItemData';
+
+export class ItemDataSource implements IDataSource {
+ private listeners: DataChangeListener[] = [];
+ private originDataArray: ItemData[] = [];
+
+ public totalCount(): number {
+ return this.originDataArray.length;
+ }
+
+ public getData(index: number): ItemData {
+ return this.originDataArray[index];
+ }
+
+ registerDataChangeListener(listener: DataChangeListener): void {
+ if (this.listeners.indexOf(listener) < 0) {
+ this.listeners.push(listener);
+ }
+ }
+
+ unregisterDataChangeListener(listener: DataChangeListener): void {
+ const pos = this.listeners.indexOf(listener);
+ if (pos >= 0) {
+ this.listeners.splice(pos, 1);
+ }
+ }
+
+ notifyDataReload(): void {
+ this.listeners.forEach(listener => {
+ listener.onDataReloaded();
+ });
+ }
+
+ notifyDataAdd(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataAdd(index);
+ });
+ }
+
+ notifyDataChange(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataChange(index);
+ });
+ }
+
+ notifyDataDelete(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataDelete(index);
+ });
+ }
+
+ notifyDataMove(from: number, to: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataMove(from, to);
+ });
+ }
+
+ notifyDatasetChange(operations: DataOperation[]): void {
+ this.listeners.forEach(listener => {
+ listener.onDatasetChange(operations);
+ });
+ }
+
+ public pushArray(newData: ItemData[]): void {
+ this.originDataArray.push(...newData);
+ this.notifyDataReload();
+ }
+
+ public addItems(items: ItemData[]) {
+ this.originDataArray.push(...items);
+ this.notifyDataReload();
+ }
+
+ public add1stItem(item: ItemData): void {
+ this.originDataArray.splice(0, 0, item);
+ this.notifyDataAdd(0);
+ }
+
+ public addLastItem(item: ItemData): void {
+ this.originDataArray.splice(this.originDataArray.length, 0, item);
+ this.notifyDataAdd(this.originDataArray.length - 1);
+ }
+
+ public addItem(index: number, item: ItemData): void {
+ this.originDataArray.splice(index, 0, item);
+ this.notifyDataAdd(index);
+ }
+
+ public delete1stItem(): void {
+ this.originDataArray.splice(0, 1);
+ this.notifyDataDelete(0);
+ }
+
+ public delete2ndItem(): void {
+ this.originDataArray.splice(1, 1);
+ this.notifyDataDelete(1);
+ }
+
+ public deleteLastItem(): void {
+ this.originDataArray.splice(-1, 1);
+ this.notifyDataDelete(this.originDataArray.length);
+ }
+
+ public reload() {
+ this.originDataArray.splice(1, 1);
+ this.originDataArray.splice(3, 2);
+ this.reload();
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneOnePositiveExample.ets b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneOnePositiveExample.ets
new file mode 100644
index 0000000000000000000000000000000000000000..56596d9e5ff91ac152ca7e3adc6710bb4c5c282a
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneOnePositiveExample.ets
@@ -0,0 +1,86 @@
+import { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+
+@Entry
+@Component
+struct NoComponentReuseSceneOnePositiveExample {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ build() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ }
+ }
+}
+
+// [Start NoComponentReuseSceneOnePositiveExample]
+@Reusable
+@Component
+struct NewsContent {
+ // [StartExclude NoComponentReuseSceneOnePositiveExample]
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneOnePositiveExample]
+}
+
+// [End NoComponentReuseSceneOnePositiveExample]
+
+// [Start ComponentReuseImproperUseSceneTwoPositiveExample]
+@Component
+struct TopView {
+ // [StartExclude ComponentReuseImproperUseSceneTwoPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude ComponentReuseImproperUseSceneTwoPositiveExample]
+}
+
+@Component
+struct BottomView {
+ // [StartExclude ComponentReuseImproperUseSceneTwoPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude ComponentReuseImproperUseSceneTwoPositiveExample]
+}
+
+@Component
+struct MiddleSingleImageView {
+ // [StartExclude ComponentReuseImproperUseSceneTwoPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude ComponentReuseImproperUseSceneTwoPositiveExample]
+}
+
+// [End ComponentReuseImproperUseSceneTwoPositiveExample]
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneThreePositiveExample.ets b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneThreePositiveExample.ets
new file mode 100644
index 0000000000000000000000000000000000000000..10b5b5bf45896addd454fdfd06b24eb775b90d90
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneThreePositiveExample.ets
@@ -0,0 +1,121 @@
+import { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+
+@Entry
+@Component
+struct NoComponentReuseSceneThreePositiveExample {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ @Builder
+ itemBuilderSingleImage(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+ }
+
+ @Builder
+ itemBuilderThreeImage(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+ }
+
+ @Builder
+ itemBuilderVideo(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+ }
+
+ build() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ if (item.type === 0) {
+ this.itemBuilderSingleImage(item)
+ } else if (item.type === 1) {
+ this.itemBuilderThreeImage(item)
+ } else {
+ this.itemBuilderVideo(item)
+ }
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ }
+ }
+}
+
+// [Start NoComponentReuseSceneTwoSubPositiveExample]
+@Reusable
+@Component
+struct TopView {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+@Reusable
+@Component
+struct BottomView {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+@Reusable
+@Component
+struct MiddleSingleImageView {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+@Reusable
+@Component
+struct MiddleThreeImageView {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+@Reusable
+@Component
+struct MiddleVideoView {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+// [End NoComponentReuseSceneTwoSubPositiveExample]
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneTwoPositiveExample.ets b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneTwoPositiveExample.ets
new file mode 100644
index 0000000000000000000000000000000000000000..71d7554eab96423346d32660d1cf60cabd2793ef
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneTwoPositiveExample.ets
@@ -0,0 +1,101 @@
+import { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+
+@Entry
+@Component
+struct NoComponentReuseSceneTwoPositiveExample {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ build() {
+ Column() {
+ // [Start NoComponentReuseSceneTwoPositiveExample01]
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item }).reuseId(`${item.type}`)
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+
+ // [Start NoComponentReuseSceneTwoPositiveExample01]
+ }
+ }
+}
+
+// [Start NoComponentReuseSceneTwoPositiveExample02]
+@Reusable
+@Component
+struct NewsContent {
+ // [StartExclude NoComponentReuseSceneTwoPositiveExample02]
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ if (item.type === 0) {
+ MiddleSingleImageView({ item: item })
+ } else if (item.type === 1) {
+ MiddleThreeImageView({ item: item })
+ } else {
+ MiddleVideoView({ item: item })
+ }
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoPositiveExample02]
+}
+
+// [End NoComponentReuseSceneTwoPositiveExample02]
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneTwoSubPositiveExample.ets b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneTwoSubPositiveExample.ets
new file mode 100644
index 0000000000000000000000000000000000000000..43f9a1b39cf43b183daa2c15edb696e0386ad491
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/view/NoComponentReuseSceneTwoSubPositiveExample.ets
@@ -0,0 +1,146 @@
+import { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+
+@Entry
+@Component
+struct NoComponentReuseSceneTwoSubPositiveExample {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ build() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ if (item.type === 0) {
+ SingleImageNewsContent({ item: item })
+ } else if (item.type === 1) {
+ ThreeImageNewsContent({ item: item })
+ } else {
+ VideoNewsContent({ item: item })
+ }
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ }
+ }
+}
+
+// [Start NoComponentReuseSceneTwoSubPositiveExample]
+@Reusable
+@Component
+struct SingleImageNewsContent {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+@Reusable
+@Component
+struct ThreeImageNewsContent {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleThreeImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+@Reusable
+@Component
+struct VideoNewsContent {
+ // [StartExclude NoComponentReuseSceneTwoSubPositiveExample]
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleVideoView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+
+ // ...
+ }
+
+ // [EndExclude NoComponentReuseSceneTwoSubPositiveExample]
+}
+
+// [End NoComponentReuseSceneTwoSubPositiveExample]
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/view/PageListSlideToHistory.ets b/ComponentReuse/entry/src/main/ets/view/PageListSlideToHistory.ets
index cc35bc15018a5fec9b0f7591b96c3b816221287c..fe641679fcb3fcf0e359a75db0d7e38850cfede2 100644
--- a/ComponentReuse/entry/src/main/ets/view/PageListSlideToHistory.ets
+++ b/ComponentReuse/entry/src/main/ets/view/PageListSlideToHistory.ets
@@ -25,7 +25,7 @@ export struct PageListSlideToHistory {
private readonly ANIMATION_DURATION: number = 500;
private readonly DEFAULT_VISIBLE_BTN_INDEX: number = 3; // Show jump history button when scroll more than 3 item
private readonly LIST_CACHE_COUNT: number = 3;
- private momentData: FriendMomentsData = new FriendMomentsData();
+ private momentData: FriendMomentsData = new FriendMomentsData(this.getUIContext().getHostContext());
private listScroller: ListScroller = new ListScroller();
private historyOffset: number = 0;
private isHistoricalRecord: boolean = false;
diff --git a/ComponentReuse/entry/src/main/ets/view/ReuseIdClassificationIsTooDetailedScenePositiveExample.ets b/ComponentReuse/entry/src/main/ets/view/ReuseIdClassificationIsTooDetailedScenePositiveExample.ets
new file mode 100644
index 0000000000000000000000000000000000000000..184843e204f1e42aed0c5acbc38edc89515bf35e
--- /dev/null
+++ b/ComponentReuse/entry/src/main/ets/view/ReuseIdClassificationIsTooDetailedScenePositiveExample.ets
@@ -0,0 +1,127 @@
+import { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+
+@Entry
+@Component
+struct NoComponentReuseSceneTwoPositiveExample {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ build() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item }).reuseId(`${item.type}`)
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ if (item.type === 0) {
+ MiddleTextView({ item: item })
+ } else if (item.type === 1) {
+ MiddleTextNoTitleView({ item: item })
+ } else if (item.type === 2) {
+ MiddleSingleImageView({ item: item })
+ } else if (item.type === 3) {
+ MiddleThreeImageView({ item: item })
+ } else if (item.type === 4) {
+ MiddleVideoView({ item: item })
+ } else if (item.type === 5) {
+ // ...
+ } else {
+ // ...
+ }
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+
+ // ...
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
+
+// [Start ReuseIdClassificationIsTooDetailedScenePositiveExample]
+@Component
+struct MiddleTextView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Column() {
+ Text('title')
+ .visibility(this.item.isShowTitle) // Switch effects through the visibility property.
+ Text()
+ }
+
+ // ...
+ }
+}
+
+// [Start ReuseIdClassificationIsTooDetailedScenePositiveExample]
+
+@Component
+struct MiddleTextNoTitleView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ // ...
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/entry/src/main/ets/view/UpdaterComponent.ets b/ComponentReuse/entry/src/main/ets/view/UpdaterComponent.ets
index 8dc2597a837b51e6b95a44d2f414ebfa3a680af0..b8843afbe2952840a1350d1461eb42c94f35bcf6 100644
--- a/ComponentReuse/entry/src/main/ets/view/UpdaterComponent.ets
+++ b/ComponentReuse/entry/src/main/ets/view/UpdaterComponent.ets
@@ -39,7 +39,7 @@ export class MyTextUpdater extends AttributeUpdater {
// [StartExclude opt_updater]
@Component
export struct UpdaterComponent {
- private colorData: ColorData = new ColorData();
+ private colorData: ColorData = new ColorData(this.getUIContext().getHostContext());
private readonly LIST_CACHE_COUNT: number = 5;
private readonly LIST_SPACE: number = 18;
diff --git a/ComponentReuse/entry/src/main/ets/view/WithFuncParam.ets b/ComponentReuse/entry/src/main/ets/view/WithFuncParam.ets
index 963ea7b67ec78ccc03d80bb29cd94fed420cdc72..2c8ff2a9373281b2cd43c82819909c155bafa3f4 100644
--- a/ComponentReuse/entry/src/main/ets/view/WithFuncParam.ets
+++ b/ComponentReuse/entry/src/main/ets/view/WithFuncParam.ets
@@ -24,7 +24,8 @@ import { FriendMomentsData } from '../model/FriendMomentData';
struct WithFuncParam {
@State sum: number = 0;
// [StartExclude opt_funcParam]
- private momentData: FriendMomentsData = new FriendMomentsData(Constants.NAV_DESTINATION_ITEM_3);
+ private momentData: FriendMomentsData =
+ new FriendMomentsData(this.getUIContext().getHostContext(), Constants.NAV_DESTINATION_ITEM_3);
private readonly LIST_CACHE_COUNT: number = 5;
private readonly LIST_SPACE: number = 18;
// [EndExclude opt_funcParam]
diff --git a/ComponentReuse/entry/src/main/ets/view/WithReuseId.ets b/ComponentReuse/entry/src/main/ets/view/WithReuseId.ets
index 462b1a7afa32b27d0d3f5914fb1435c749538d96..c702345d2244c108315602c26532671871144874 100644
--- a/ComponentReuse/entry/src/main/ets/view/WithReuseId.ets
+++ b/ComponentReuse/entry/src/main/ets/view/WithReuseId.ets
@@ -23,7 +23,7 @@ import { FriendMomentsData } from '../model/FriendMomentData'
@Component
struct WithReuseId {
// [StartExclude opt_reuseId]
- private momentData: FriendMomentsData = new FriendMomentsData();
+ private momentData: FriendMomentsData = new FriendMomentsData(this.getUIContext().getHostContext());
private readonly LIST_CACHE_COUNT: number = 5;
private readonly LIST_SPACE: number = 18;
diff --git a/ComponentReuse/entry/src/main/resources/base/element/string.json b/ComponentReuse/entry/src/main/resources/base/element/string.json
index 1c04e82de4ae97336282418d1fad24937a2689c0..02cb0a9a0dc390b10bb7c79737968c21db6bb6cc 100644
--- a/ComponentReuse/entry/src/main/resources/base/element/string.json
+++ b/ComponentReuse/entry/src/main/resources/base/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "ComponentReuse"
},
{
"name": "nav_destination_item0",
diff --git a/ComponentReuse/entry/src/main/resources/en_US/element/string.json b/ComponentReuse/entry/src/main/resources/en_US/element/string.json
index 1c04e82de4ae97336282418d1fad24937a2689c0..02cb0a9a0dc390b10bb7c79737968c21db6bb6cc 100644
--- a/ComponentReuse/entry/src/main/resources/en_US/element/string.json
+++ b/ComponentReuse/entry/src/main/resources/en_US/element/string.json
@@ -10,7 +10,7 @@
},
{
"name": "EntryAbility_label",
- "value": "label"
+ "value": "ComponentReuse"
},
{
"name": "nav_destination_item0",
diff --git a/ComponentReuse/negative/build-profile.json5 b/ComponentReuse/negative/build-profile.json5
new file mode 100644
index 0000000000000000000000000000000000000000..6bd6457a2fed846cc10698666fa1268219f1bee1
--- /dev/null
+++ b/ComponentReuse/negative/build-profile.json5
@@ -0,0 +1,33 @@
+{
+ "apiType": "stageMode",
+ "buildOption": {
+ "resOptions": {
+ "copyCodeResource": {
+ "enable": false
+ }
+ }
+ },
+ "buildOptionSet": [
+ {
+ "name": "release",
+ "arkOptions": {
+ "obfuscation": {
+ "ruleOptions": {
+ "enable": false,
+ "files": [
+ "./obfuscation-rules.txt"
+ ]
+ }
+ }
+ }
+ },
+ ],
+ "targets": [
+ {
+ "name": "default"
+ },
+ {
+ "name": "ohosTest",
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/hvigorfile.ts b/ComponentReuse/negative/hvigorfile.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b0e3a1ab98a91bc918d6404b2413111a5011f14a
--- /dev/null
+++ b/ComponentReuse/negative/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. */
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/oh-package.json5 b/ComponentReuse/negative/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..3c409fae6359c99d9e16e6933be27125bd4a0c6d
--- /dev/null
+++ b/ComponentReuse/negative/oh-package.json5
@@ -0,0 +1,10 @@
+{
+ "name": "negative",
+ "version": "1.0.0",
+ "description": "Please describe the basic information.",
+ "main": "",
+ "author": "",
+ "license": "",
+ "dependencies": {}
+}
+
diff --git a/ComponentReuse/negative/src/main/ets/common/CommonConstants.ets b/ComponentReuse/negative/src/main/ets/common/CommonConstants.ets
new file mode 100644
index 0000000000000000000000000000000000000000..eacde21b6eb129221c51fc97d32907706c03e926
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/common/CommonConstants.ets
@@ -0,0 +1,24 @@
+/*
+* 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 class CommonConstants {
+ static readonly Full_WIDTH: string = '100%';
+ static readonly Full_HIIGHT: string = '100%';
+ static readonly INDEX_CONTENT_WIDTH: string = '91.1%';
+ static readonly DIVIDER_HEIGHT: number = 0.5;
+ static readonly DIVIDER_WIDTH: string = '93%';
+ static readonly INDEX_TITLE_HEIGHT: number = 112;
+ static readonly LIST_CONTENT_HEIGHT: string = '110%';
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/common/CustomRoutes.ets b/ComponentReuse/negative/src/main/ets/common/CustomRoutes.ets
new file mode 100644
index 0000000000000000000000000000000000000000..90dd397157be51de3e416c59e918373e64559ca4
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/common/CustomRoutes.ets
@@ -0,0 +1,48 @@
+/*
+* 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 class CustomRoutes {
+ static readonly ROUTES: Route[] = [
+ {
+ title: '未使用组件复用',
+ child: [
+ { text: '场景1', title: '列表项结构类型相同', to: 'NoReuseScene1' },
+ { text: '场景2', title: '列表项结构类型相同-结构一', to: 'NoReuseScene2_StructureOne' },
+ { text: '场景2', title: '列表项结构类型相同-结构二', to: 'NoReuseScene2_StructureTwo' },
+ { text: '场景3', title: '列表项内子组件可拆分组合', to: 'NoReuseScene3' }
+ ]
+ },
+ {
+ title: '组件复用使用不当',
+ child: [
+ { text: '场景1', title: '父组件未使用复用,子组件使用复用', to: 'ImproperReuseOfComponentsScene1' },
+ { text: '场景2', title: '复用嵌套', to: 'ImproperReuseOfComponentsScene2' },
+ { text: '场景3', title: 'reuseId分类过粗', to: 'ImproperReuseOfComponentsScene3' }
+ ]
+ }
+ ]
+}
+
+export interface Route {
+ title: string | Resource;
+ child: Array;
+}
+
+export interface ChildRoute {
+ text: string | Resource;
+ title?: string | Resource | null;
+ description?: string;
+ to: string;
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/common/MockData.ets b/ComponentReuse/negative/src/main/ets/common/MockData.ets
new file mode 100644
index 0000000000000000000000000000000000000000..8e0a668e5ea427987d431575ec7f3dfcbb2df81e
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/common/MockData.ets
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2025 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 { ItemData } from '../model/ItemData';
+
+export const TAB_TITLES: string[] = ['News', 'Hot', 'Video', 'Tech', 'Travel'];
+
+const NEWS_TITLES: string[] =
+ ['Embark on the journey of integrating intelligence and innovation, join hands to build a new generation of demonstration cities, collaborate on creation, provide new solutions, and create a new era',
+ 'In the era of data awakening, redefining data storage',
+ 'High end all flash memory won the top recommendation on annual storage data list, ranking first in the recommendation list',
+ 'Deeply integrating new technologies with the aviation industry, based on cloud, data, and intelligence as the core of the digital base, jointly cooperating to create solutions to help aviation efficiency',
+ 'Innovation leads, with actions and words, to jointly build new high-quality communication and new development',
+ 'To jointly build new high-quality communication and new development'];
+
+const NEWS_FROMS: string[] = ['Comment', 'News', 'Discuss'];
+
+let imageArray: Resource[] = [$r("app.media.img0"), $r("app.media.img1"),
+ $r("app.media.img2"), $r("app.media.img3"), $r("app.media.img4"), $r("app.media.img5")];
+
+let PREVIEW_IMAGES: Resource[] = [$r("app.media.img6"), $r("app.media.img7"),
+ $r("app.media.img8")];
+
+export function genMockItemData(size: number): ItemData[] {
+ const res: ItemData[] = [];
+ for (let i = 0; i < size; i++) {
+ const data = new ItemData('' + i, i % 3);
+ data.title = NEWS_TITLES[Math.floor(Math.random() * NEWS_TITLES.length)];
+ data.from = NEWS_FROMS[Math.floor(Math.random() * NEWS_FROMS.length)];
+ data.tail = '15 minutes ago';
+ imageArray = shuffleArray(imageArray);
+ data.pics = imageArray;
+ data.preview = PREVIEW_IMAGES[Math.floor(Math.random() * PREVIEW_IMAGES.length)];
+ data.duration = '03:12';
+ res.push(data);
+ }
+ return res;
+}
+
+function shuffleArray(array: T[]): T[] {
+ const shuffled = [...array];
+ for (let i = shuffled.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ const tmp = shuffled[i];
+ shuffled[i] = shuffled[j];
+ shuffled[j] = tmp;
+ }
+ return shuffled;
+}
diff --git a/ComponentReuse/negative/src/main/ets/model/ItemData.ets b/ComponentReuse/negative/src/main/ets/model/ItemData.ets
new file mode 100644
index 0000000000000000000000000000000000000000..113eccbd7bde15caefdabb51720ec150931bf0a4
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/model/ItemData.ets
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Observed
+export class ItemData {
+ id: string = '';
+ title: string | Resource = '';
+ content: string = '';
+ from: string | Resource = '';
+ tail: string | Resource = '';
+ type: number = 0;
+ pics: Resource[] = [];
+ preview: Resource | string = '';
+ duration: string = '';
+
+ constructor(id: string, type: number) {
+ this.id = id;
+ this.type = type;
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/model/ItemDataSource.ets b/ComponentReuse/negative/src/main/ets/model/ItemDataSource.ets
new file mode 100644
index 0000000000000000000000000000000000000000..0056109375c97c16fa7075b877c94013a6d7fa4a
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/model/ItemDataSource.ets
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2025 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 { ItemData } from './ItemData';
+
+export class ItemDataSource implements IDataSource {
+ private listeners: DataChangeListener[] = [];
+ private originDataArray: ItemData[] = [];
+
+ public totalCount(): number {
+ return this.originDataArray.length;
+ }
+
+ public getData(index: number): ItemData {
+ return this.originDataArray[index];
+ }
+
+ registerDataChangeListener(listener: DataChangeListener): void {
+ if (this.listeners.indexOf(listener) < 0) {
+ this.listeners.push(listener);
+ }
+ }
+
+ unregisterDataChangeListener(listener: DataChangeListener): void {
+ const pos = this.listeners.indexOf(listener);
+ if (pos >= 0) {
+ this.listeners.splice(pos, 1);
+ }
+ }
+
+ notifyDataReload(): void {
+ this.listeners.forEach(listener => {
+ listener.onDataReloaded();
+ });
+ }
+
+ notifyDataAdd(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataAdd(index);
+ });
+ }
+
+ notifyDataChange(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataChange(index);
+ });
+ }
+
+ notifyDataDelete(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataDelete(index);
+ });
+ }
+
+ notifyDataMove(from: number, to: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataMove(from, to);
+ });
+ }
+
+ notifyDatasetChange(operations: DataOperation[]): void {
+ this.listeners.forEach(listener => {
+ listener.onDatasetChange(operations);
+ });
+ }
+
+ public pushArray(newData: ItemData[]): void {
+ this.originDataArray.push(...newData);
+ this.notifyDataReload();
+ }
+
+ public addItems(items: ItemData[]) {
+ this.originDataArray.push(...items);
+ this.notifyDataReload();
+ }
+
+ public add1stItem(item: ItemData): void {
+ this.originDataArray.splice(0, 0, item);
+ this.notifyDataAdd(0);
+ }
+
+ public addLastItem(item: ItemData): void {
+ this.originDataArray.splice(this.originDataArray.length, 0, item);
+ this.notifyDataAdd(this.originDataArray.length - 1);
+ }
+
+ public addItem(index: number, item: ItemData): void {
+ this.originDataArray.splice(index, 0, item);
+ this.notifyDataAdd(index);
+ }
+
+ public delete1stItem(): void {
+ this.originDataArray.splice(0, 1);
+ this.notifyDataDelete(0);
+ }
+
+ public delete2ndItem(): void {
+ this.originDataArray.splice(1, 1);
+ this.notifyDataDelete(1);
+ }
+
+ public deleteLastItem(): void {
+ this.originDataArray.splice(-1, 1);
+ this.notifyDataDelete(this.originDataArray.length);
+ }
+
+ public reload() {
+ this.originDataArray.splice(1, 1);
+ this.originDataArray.splice(3, 2);
+ this.reload();
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/model/TitleDataSource.ets b/ComponentReuse/negative/src/main/ets/model/TitleDataSource.ets
new file mode 100644
index 0000000000000000000000000000000000000000..d37993baa67ef5cbe2331a50ded9a41334922b00
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/model/TitleDataSource.ets
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2025 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 class TitleDataSource implements IDataSource {
+ private listeners: DataChangeListener[] = [];
+ private originDataArray: string[] = [];
+
+ totalCount(): number {
+ return this.originDataArray.length;
+ }
+
+ getData(index: number): string {
+ return this.originDataArray[index];
+ }
+
+ public addItem(title: string): void {
+ this.originDataArray.push(title);
+ this.notifyDataAdd(this.originDataArray.length - 1);
+ }
+
+ notifyDataAdd(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataAdd(index);
+ })
+ }
+
+ registerDataChangeListener(listener: DataChangeListener): void {
+ if (this.listeners.indexOf(listener) < 0) {
+ this.listeners.push(listener);
+ }
+ }
+
+ unregisterDataChangeListener(listener: DataChangeListener): void {
+ const pos = this.listeners.indexOf(listener);
+ if (pos > 0) {
+ this.listeners.splice(pos, 1);
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/negativeability/NegativeAbility.ets b/ComponentReuse/negative/src/main/ets/negativeability/NegativeAbility.ets
new file mode 100644
index 0000000000000000000000000000000000000000..2552addcb41de9903218efb5fb112591ec844ef9
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/negativeability/NegativeAbility.ets
@@ -0,0 +1,58 @@
+/*
+* 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';
+
+const DOMAIN = 0x0000;
+
+export default class NegativeAbility extends UIAbility {
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
+ }
+
+ onDestroy(): void {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
+ }
+
+ onWindowStageCreate(windowStage: window.WindowStage): void {
+ // Main window is created, set main page for this ability
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
+
+ windowStage.loadContent('pages/Index', (err) => {
+ if (err.code) {
+ hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
+ return;
+ }
+ hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
+ });
+ }
+
+ onWindowStageDestroy(): void {
+ // Main window is destroyed, release UI related resources
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
+ }
+
+ onForeground(): void {
+ // Ability has brought to foreground
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
+ }
+
+ onBackground(): void {
+ // Ability has back to background
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
+ }
+}
diff --git a/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene1.ets b/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene1.ets
new file mode 100644
index 0000000000000000000000000000000000000000..135c64880b2e58ef49f1960100cdc204433373b3
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene1.ets
@@ -0,0 +1,132 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildImproperReuseOfComponentsScene1() {
+ ImproperReuseOfComponentsScene1()
+}
+
+// 父组件未使用复用,子组件使用复用
+@Component
+struct ImproperReuseOfComponentsScene1 {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Reusable
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Reusable
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Reusable
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene2.ets b/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene2.ets
new file mode 100644
index 0000000000000000000000000000000000000000..68a4636fb3f4e74dfa17fda4f0ddccc11f5681c3
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene2.ets
@@ -0,0 +1,133 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildImproperReuseOfComponentsScene2() {
+ ImproperReuseOfComponentsScene2()
+}
+
+// 复用嵌套
+@Component
+struct ImproperReuseOfComponentsScene2 {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Reusable
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Reusable
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Reusable
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene3.ets b/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene3.ets
new file mode 100644
index 0000000000000000000000000000000000000000..cf5480258732bc1e5006946102767ce2ee7b91ce
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/ImproperReuseOfComponentsScene3.ets
@@ -0,0 +1,188 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildImproperReuseOfComponentsScene3() {
+ ImproperReuseOfComponentsScene3()
+}
+
+// reuseId分类过粗
+@Component
+struct ImproperReuseOfComponentsScene3 {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ // MiddleSingleImageView({ item: item })
+ if (item.type === 0) {
+ MiddleSingleImageView({ item: item })
+ } else if (item.type === 1) {
+ MiddleThreeImageView({ item: item })
+ } else {
+ MiddleVideoView({ item: item })
+ }
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/Index.ets b/ComponentReuse/negative/src/main/ets/pages/Index.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a26dc549f1f79a93a247824a332b7dd3bda60cef
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/Index.ets
@@ -0,0 +1,126 @@
+/*
+* 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 { CustomRoutes, Route, ChildRoute } from '../common/CustomRoutes';
+import { CommonConstants } from '../common/CommonConstants';
+
+@Entry
+@Component
+struct Index {
+ private routes: Route[] = CustomRoutes.ROUTES;
+ pathStack: NavPathStack = new NavPathStack();
+
+ @Builder
+ buildList() {
+ ForEach(this.routes, (item: Route) => {
+ Row() {
+ Text(item.title)
+ .width(CommonConstants.INDEX_CONTENT_WIDTH)
+ .fontSize(18)
+ .fontColor(Color.Black)
+ }
+ .height(20)
+
+ Column() {
+ ForEach(item.child, (itemChild: ChildRoute, index: number) => {
+ Column() {
+ Row() {
+ Text(itemChild.text)
+ .height(48)
+ .fontWeight(FontWeight.Medium)
+ .padding({ left: 12 })
+ .fontSize(16)
+ .fontColor($r('app.color.black_E6'))
+ Column().layoutWeight(1)
+
+ Text(itemChild.title ?? '')
+ .height(48)
+ .textAlign(TextAlign.End)
+ .fontWeight(FontWeight.Normal)
+ .fontSize(14)
+ .fontColor($r('app.color.black_99'))
+
+ Image($r('app.media.chevron_right'))
+ .width(24)
+ .height(24)
+ .margin({ right: 8 })
+ .fillColor($r('app.color.black_33'))
+ }
+ .justifyContent(FlexAlign.Start)
+ .alignItems(VerticalAlign.Center)
+
+ Text(itemChild.description)
+ .fontWeight(FontWeight.Medium)
+ .fontColor($r('app.color.gray_3'))
+ .padding({
+ left: 12,
+ right: 12,
+ bottom: (itemChild.description ?? '').length > 0 ? 10 : 0
+ })
+ .fontSize(12)
+
+ Stack() {
+ if (item.child.length - 1 !== index) {
+ Row()
+ .backgroundColor($r('app.color.gray_6'))
+ .width(CommonConstants.DIVIDER_WIDTH)
+ .height(CommonConstants.DIVIDER_HEIGHT)
+ }
+ }
+ }
+ .onClick(() => {
+ this.pathStack.pushPathByName(itemChild.to, null);
+ })
+ .width(CommonConstants.INDEX_CONTENT_WIDTH)
+ }, (item: ChildRoute, index: number) => JSON.stringify(item) + index)
+ }
+ .margin({ top: 14, bottom: 18 })
+ .borderRadius(18)
+ .backgroundColor(Color.White)
+ }, (item: Route, index: number) => JSON.stringify(item) + index)
+ }
+
+ build() {
+ Navigation(this.pathStack) {
+ Column() {
+ Row() {
+ Text('组件复用使用示例')
+ .fontWeight(FontWeight.Bold)
+ .fontSize(30)
+ .width('100%')
+ .fontColor('#FF333333')
+ }
+ .width(CommonConstants.INDEX_CONTENT_WIDTH)
+ .height(CommonConstants.INDEX_TITLE_HEIGHT)
+
+ Scroll() {
+ Column() {
+ this.buildList()
+ }
+ .padding({ bottom: 200 })
+ }
+ .scrollBar(BarState.Off)
+ .width(CommonConstants.Full_WIDTH)
+ .scrollable(ScrollDirection.Vertical)
+ }
+ .alignItems(HorizontalAlign.Center)
+ }
+ .hideNavBar(false)
+ .backgroundColor('#FFF5F5F5')
+ .mode(NavigationMode.Stack)
+ .width(CommonConstants.Full_WIDTH)
+ .height(CommonConstants.Full_HIIGHT)
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/NoReuseScene1.ets b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene1.ets
new file mode 100644
index 0000000000000000000000000000000000000000..815d6283d02d69fdb84dc038122ee41543af7488
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene1.ets
@@ -0,0 +1,129 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene1() {
+ NoReuseScene1()
+}
+
+// 未使用组件复用:场景1
+@Component
+struct NoReuseScene1 {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/NoReuseScene2_StructureOne.ets b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene2_StructureOne.ets
new file mode 100644
index 0000000000000000000000000000000000000000..57b482db2aa0d784e0873ea6420262f1c6d953e0
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene2_StructureOne.ets
@@ -0,0 +1,187 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene2_StructureOne() {
+ NoReuseScene2_StructureOne()
+}
+
+// 未使用组件复用:场景2 结构一
+@Component
+struct NoReuseScene2_StructureOne {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ // MiddleSingleImageView({ item: item })
+ if (item.type === 0) {
+ MiddleSingleImageView({ item: item })
+ } else if (item.type === 1) {
+ MiddleThreeImageView({ item: item })
+ } else {
+ MiddleVideoView({ item: item })
+ }
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/NoReuseScene2_StructureTwo.ets b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene2_StructureTwo.ets
new file mode 100644
index 0000000000000000000000000000000000000000..8eaad66ba7c3098156cd48728df2e216bce95da8
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene2_StructureTwo.ets
@@ -0,0 +1,250 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene2_StructureTwo() {
+ NoReuseScene2_StructureTwo()
+}
+
+// 未使用组件复用:场景2 结构二
+@Component
+struct NoReuseScene2_StructureTwo {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ if (item.type === 0) {
+ SingleImageNewsContent({ item: item })
+ } else if (item.type === 1) {
+ ThreeImageNewsContent({ item: item })
+ } else {
+ VideoNewsContent({ item: item })
+ }
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Component
+struct SingleImageNewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct ThreeImageNewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleThreeImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct VideoNewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleVideoView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/ets/pages/NoReuseScene3.ets b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene3.ets
new file mode 100644
index 0000000000000000000000000000000000000000..85697a4a48669f7c64045d709011f06c26866a53
--- /dev/null
+++ b/ComponentReuse/negative/src/main/ets/pages/NoReuseScene3.ets
@@ -0,0 +1,224 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene3() {
+ NoReuseScene3()
+}
+
+// 未使用组件复用:场景3
+@Component
+struct NoReuseScene3 {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ @Builder
+ itemBuilderSingleImage(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+
+ @Builder
+ itemBuilderThreeImage(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleThreeImageView({ item: item })
+ BottomView({ item: item })
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+
+ @Builder
+ itemBuilderVideo(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleVideoView({ item: item })
+ BottomView({ item: item })
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ if (item.type === 0) {
+ this.itemBuilderSingleImage(item)
+ } else if (item.type === 1) {
+ this.itemBuilderThreeImage(item)
+ } else {
+ this.itemBuilderVideo(item)
+ }
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/module.json5 b/ComponentReuse/negative/src/main/module.json5
new file mode 100644
index 0000000000000000000000000000000000000000..a3ef12ce150d60ec34a2e6c16469b94d6920fa47
--- /dev/null
+++ b/ComponentReuse/negative/src/main/module.json5
@@ -0,0 +1,27 @@
+{
+ "module": {
+ "name": "negative",
+ "type": "feature",
+ "description": "$string:module_desc",
+ "mainElement": "NegativeAbility",
+ "deviceTypes": [
+ "phone"
+ ],
+ "deliveryWithInstall": true,
+ "installationFree": false,
+ "pages": "$profile:main_pages",
+ "routerMap": "$profile:route_map",
+ "abilities": [
+ {
+ "name": "NegativeAbility",
+ "srcEntry": "./ets/negativeability/NegativeAbility.ets",
+ "description": "$string:NegativeAbility_desc",
+ "icon": "$media:layered_image",
+ "label": "$string:NegativeAbility_label",
+ "startWindowIcon": "$media:startIcon",
+ "startWindowBackground": "$color:start_window_background",
+ "exported": true
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/negative/src/main/resources/base/element/color.json b/ComponentReuse/negative/src/main/resources/base/element/color.json
new file mode 100644
index 0000000000000000000000000000000000000000..3a0c6cea26e20e4f98146759d70e7e24da0e1d83
--- /dev/null
+++ b/ComponentReuse/negative/src/main/resources/base/element/color.json
@@ -0,0 +1,60 @@
+{
+ "color": [
+ {
+ "name": "start_window_background",
+ "value": "#FFFFFF"
+ },
+ {
+ "name": "text",
+ "value": "#2c2c2c"
+ },
+ {
+ "name": "home_background_color",
+ "value": "#F1F3F5"
+ },
+ {
+ "name": "gray_3",
+ "value": "#FF333333"
+ },
+ {
+ "name": "gray_6",
+ "value": "#FF666666"
+ },
+ {
+ "name": "gray_9",
+ "value": "#FF999999"
+ },
+ {
+ "name": "black_03",
+ "value": "#0D000000"
+ },
+ {
+ "name": "black_0D",
+ "value": "#0D000000"
+ },
+ {
+ "name": "black_12",
+ "value": "#12000000"
+ },
+ {
+ "name": "black_33",
+ "value": "#33000000"
+ },
+ {
+ "name": "black_66",
+ "value": "#66000000"
+ },
+ {
+ "name": "black_80",
+ "value": "#80000000"
+ },
+ {
+ "name": "black_99",
+ "value": "#99000000"
+ },
+ {
+ "name": "black_E6",
+ "value": "#E6000000"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Privacy/ContactData/src/main/resources/base/element/float.json b/ComponentReuse/negative/src/main/resources/base/element/float.json
similarity index 100%
rename from Privacy/ContactData/src/main/resources/base/element/float.json
rename to ComponentReuse/negative/src/main/resources/base/element/float.json
diff --git a/ComponentReuse/negative/src/main/resources/base/element/string.json b/ComponentReuse/negative/src/main/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..08a0271a9ca15cb687d645897035e239ccab8e1a
--- /dev/null
+++ b/ComponentReuse/negative/src/main/resources/base/element/string.json
@@ -0,0 +1,16 @@
+{
+ "string": [
+ {
+ "name": "module_desc",
+ "value": "module description"
+ },
+ {
+ "name": "NegativeAbility_desc",
+ "value": "description"
+ },
+ {
+ "name": "NegativeAbility_label",
+ "value": "label"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/NativeSoIntegration/Ndk/src/main/resources/base/media/background.png b/ComponentReuse/negative/src/main/resources/base/media/background.png
similarity index 100%
rename from NativeSoIntegration/Ndk/src/main/resources/base/media/background.png
rename to ComponentReuse/negative/src/main/resources/base/media/background.png
diff --git a/ComponentReuse/negative/src/main/resources/base/media/chevron_right.png b/ComponentReuse/negative/src/main/resources/base/media/chevron_right.png
new file mode 100644
index 0000000000000000000000000000000000000000..4844d0b25d462fb2168b96efd9b6ae3c641e8bf9
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/chevron_right.png differ
diff --git a/Privacy/ContactData/src/main/resources/base/media/foreground.png b/ComponentReuse/negative/src/main/resources/base/media/foreground.png
similarity index 100%
rename from Privacy/ContactData/src/main/resources/base/media/foreground.png
rename to ComponentReuse/negative/src/main/resources/base/media/foreground.png
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img0.png b/ComponentReuse/negative/src/main/resources/base/media/img0.png
new file mode 100644
index 0000000000000000000000000000000000000000..1d967400f83bb0f5e2df4581415ed2e4cbb564d4
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img0.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img1.png b/ComponentReuse/negative/src/main/resources/base/media/img1.png
new file mode 100644
index 0000000000000000000000000000000000000000..b254fba00dcee070e90baf945e920a8f2f0646c6
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img1.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img2.jpg b/ComponentReuse/negative/src/main/resources/base/media/img2.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..4d36c1f9f8435424323ff12df2b0992bb09f8af5
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img2.jpg differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img3.png b/ComponentReuse/negative/src/main/resources/base/media/img3.png
new file mode 100644
index 0000000000000000000000000000000000000000..89214745c537495119e0e78c49e602f1c4933baa
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img3.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img4.png b/ComponentReuse/negative/src/main/resources/base/media/img4.png
new file mode 100644
index 0000000000000000000000000000000000000000..54e59fc403d92d11911498f7d3c7d39d6e437cf5
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img4.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img5.png b/ComponentReuse/negative/src/main/resources/base/media/img5.png
new file mode 100644
index 0000000000000000000000000000000000000000..a38a0eaab71c8c6ba4b94bff09b7d86e96510043
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img5.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img6.png b/ComponentReuse/negative/src/main/resources/base/media/img6.png
new file mode 100644
index 0000000000000000000000000000000000000000..c1175890f2f43f92082e40299d7bda81094e9c06
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img6.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img7.png b/ComponentReuse/negative/src/main/resources/base/media/img7.png
new file mode 100644
index 0000000000000000000000000000000000000000..cd29997cfc3b0f30e1d393d49961da58d691ab2f
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img7.png differ
diff --git a/ComponentReuse/negative/src/main/resources/base/media/img8.png b/ComponentReuse/negative/src/main/resources/base/media/img8.png
new file mode 100644
index 0000000000000000000000000000000000000000..1cff5e45d286fb3bc058d326fc9b31caf690ac63
Binary files /dev/null and b/ComponentReuse/negative/src/main/resources/base/media/img8.png differ
diff --git a/MultiFinancialManagement/product/phone/src/main/resources/base/media/layered_image.json b/ComponentReuse/negative/src/main/resources/base/media/layered_image.json
similarity index 100%
rename from MultiFinancialManagement/product/phone/src/main/resources/base/media/layered_image.json
rename to ComponentReuse/negative/src/main/resources/base/media/layered_image.json
diff --git a/ComponentReuse/negative/src/main/resources/base/media/play_fill.svg b/ComponentReuse/negative/src/main/resources/base/media/play_fill.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d1750a9cc4dc77103c03b7e11674b4e0b2b278d9
--- /dev/null
+++ b/ComponentReuse/negative/src/main/resources/base/media/play_fill.svg
@@ -0,0 +1,8 @@
+
+
\ No newline at end of file
diff --git a/MultiCommunityApplication/products/phone/src/main/resources/base/media/startIcon.png b/ComponentReuse/negative/src/main/resources/base/media/startIcon.png
similarity index 100%
rename from MultiCommunityApplication/products/phone/src/main/resources/base/media/startIcon.png
rename to ComponentReuse/negative/src/main/resources/base/media/startIcon.png
diff --git a/MultiDeviceCommunication/common/base/src/main/resources/base/profile/main_pages.json b/ComponentReuse/negative/src/main/resources/base/profile/main_pages.json
similarity index 100%
rename from MultiDeviceCommunication/common/base/src/main/resources/base/profile/main_pages.json
rename to ComponentReuse/negative/src/main/resources/base/profile/main_pages.json
diff --git a/ComponentReuse/negative/src/main/resources/base/profile/route_map.json b/ComponentReuse/negative/src/main/resources/base/profile/route_map.json
new file mode 100644
index 0000000000000000000000000000000000000000..96d1b687ea92dc43fb6985b9c69dc89711a5b930
--- /dev/null
+++ b/ComponentReuse/negative/src/main/resources/base/profile/route_map.json
@@ -0,0 +1,39 @@
+{
+ "routerMap": [
+ {
+ "name": "NoReuseScene1",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene1.ets",
+ "buildFunction": "buildNoReuseScene1"
+ },
+ {
+ "name": "NoReuseScene2_StructureOne",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene2_StructureOne.ets",
+ "buildFunction": "buildNoReuseScene2_StructureOne"
+ },
+ {
+ "name": "NoReuseScene2_StructureTwo",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene2_StructureTwo.ets",
+ "buildFunction": "buildNoReuseScene2_StructureTwo"
+ },
+ {
+ "name": "NoReuseScene3",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene3.ets",
+ "buildFunction": "buildNoReuseScene3"
+ },
+ {
+ "name": "ImproperReuseOfComponentsScene1",
+ "pageSourceFile": "src/main/ets/pages/ImproperReuseOfComponentsScene1.ets",
+ "buildFunction": "buildImproperReuseOfComponentsScene1"
+ },
+ {
+ "name": "ImproperReuseOfComponentsScene2",
+ "pageSourceFile": "src/main/ets/pages/ImproperReuseOfComponentsScene2.ets",
+ "buildFunction": "buildImproperReuseOfComponentsScene2"
+ },
+ {
+ "name": "ImproperReuseOfComponentsScene3",
+ "pageSourceFile": "src/main/ets/pages/ImproperReuseOfComponentsScene3.ets",
+ "buildFunction": "buildImproperReuseOfComponentsScene3"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/build-profile.json5 b/ComponentReuse/positive/build-profile.json5
new file mode 100644
index 0000000000000000000000000000000000000000..6bd6457a2fed846cc10698666fa1268219f1bee1
--- /dev/null
+++ b/ComponentReuse/positive/build-profile.json5
@@ -0,0 +1,33 @@
+{
+ "apiType": "stageMode",
+ "buildOption": {
+ "resOptions": {
+ "copyCodeResource": {
+ "enable": false
+ }
+ }
+ },
+ "buildOptionSet": [
+ {
+ "name": "release",
+ "arkOptions": {
+ "obfuscation": {
+ "ruleOptions": {
+ "enable": false,
+ "files": [
+ "./obfuscation-rules.txt"
+ ]
+ }
+ }
+ }
+ },
+ ],
+ "targets": [
+ {
+ "name": "default"
+ },
+ {
+ "name": "ohosTest",
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/hvigorfile.ts b/ComponentReuse/positive/hvigorfile.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b0e3a1ab98a91bc918d6404b2413111a5011f14a
--- /dev/null
+++ b/ComponentReuse/positive/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. */
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/oh-package.json5 b/ComponentReuse/positive/oh-package.json5
new file mode 100644
index 0000000000000000000000000000000000000000..a7cfe7716ef3bd24bea42826906c685fdcab50a9
--- /dev/null
+++ b/ComponentReuse/positive/oh-package.json5
@@ -0,0 +1,10 @@
+{
+ "name": "positive",
+ "version": "1.0.0",
+ "description": "Please describe the basic information.",
+ "main": "",
+ "author": "",
+ "license": "",
+ "dependencies": {}
+}
+
diff --git a/ComponentReuse/positive/src/main/ets/common/CommonConstants.ets b/ComponentReuse/positive/src/main/ets/common/CommonConstants.ets
new file mode 100644
index 0000000000000000000000000000000000000000..eacde21b6eb129221c51fc97d32907706c03e926
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/common/CommonConstants.ets
@@ -0,0 +1,24 @@
+/*
+* 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 class CommonConstants {
+ static readonly Full_WIDTH: string = '100%';
+ static readonly Full_HIIGHT: string = '100%';
+ static readonly INDEX_CONTENT_WIDTH: string = '91.1%';
+ static readonly DIVIDER_HEIGHT: number = 0.5;
+ static readonly DIVIDER_WIDTH: string = '93%';
+ static readonly INDEX_TITLE_HEIGHT: number = 112;
+ static readonly LIST_CONTENT_HEIGHT: string = '110%';
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/common/CustomRoutes.ets b/ComponentReuse/positive/src/main/ets/common/CustomRoutes.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a545a5adf2f74112e7aacf66069943a6d42c2366
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/common/CustomRoutes.ets
@@ -0,0 +1,48 @@
+/*
+* 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 class CustomRoutes {
+ static readonly ROUTES: Route[] = [
+ {
+ title: '未使用组件复用',
+ child: [
+ { text: '场景1', title: '列表项结构类型相同', to: 'NoReuseScene1Positive' },
+ { text: '场景2', title: '列表项结构类型相同-结构一', to: 'NoReuseScene2_StructureOnePositive' },
+ { text: '场景2', title: '列表项结构类型相同-结构二', to: 'NoReuseScene2_StructureTwoPositive' },
+ { text: '场景3', title: '列表项内子组件可拆分组合', to: 'NoReuseScene3Positive' }
+ ]
+ },
+ {
+ title: '组件复用使用不当',
+ child: [
+ { text: '场景1', title: '父组件未使用复用,子组件使用复用', to: 'ImproperReuseOfComponentsScene1Positive' },
+ { text: '场景2', title: '复用嵌套', to: 'ImproperReuseOfComponentsScene2Positive' },
+ { text: '场景3', title: 'reuseId分类过粗', to: 'ImproperReuseOfComponentsScene3Positive' }
+ ]
+ }
+ ]
+}
+
+export interface Route {
+ title: string | Resource;
+ child: Array;
+}
+
+export interface ChildRoute {
+ text: string | Resource;
+ title?: string | Resource | null;
+ description?: string;
+ to: string;
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/common/MockData.ets b/ComponentReuse/positive/src/main/ets/common/MockData.ets
new file mode 100644
index 0000000000000000000000000000000000000000..8e0a668e5ea427987d431575ec7f3dfcbb2df81e
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/common/MockData.ets
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2025 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 { ItemData } from '../model/ItemData';
+
+export const TAB_TITLES: string[] = ['News', 'Hot', 'Video', 'Tech', 'Travel'];
+
+const NEWS_TITLES: string[] =
+ ['Embark on the journey of integrating intelligence and innovation, join hands to build a new generation of demonstration cities, collaborate on creation, provide new solutions, and create a new era',
+ 'In the era of data awakening, redefining data storage',
+ 'High end all flash memory won the top recommendation on annual storage data list, ranking first in the recommendation list',
+ 'Deeply integrating new technologies with the aviation industry, based on cloud, data, and intelligence as the core of the digital base, jointly cooperating to create solutions to help aviation efficiency',
+ 'Innovation leads, with actions and words, to jointly build new high-quality communication and new development',
+ 'To jointly build new high-quality communication and new development'];
+
+const NEWS_FROMS: string[] = ['Comment', 'News', 'Discuss'];
+
+let imageArray: Resource[] = [$r("app.media.img0"), $r("app.media.img1"),
+ $r("app.media.img2"), $r("app.media.img3"), $r("app.media.img4"), $r("app.media.img5")];
+
+let PREVIEW_IMAGES: Resource[] = [$r("app.media.img6"), $r("app.media.img7"),
+ $r("app.media.img8")];
+
+export function genMockItemData(size: number): ItemData[] {
+ const res: ItemData[] = [];
+ for (let i = 0; i < size; i++) {
+ const data = new ItemData('' + i, i % 3);
+ data.title = NEWS_TITLES[Math.floor(Math.random() * NEWS_TITLES.length)];
+ data.from = NEWS_FROMS[Math.floor(Math.random() * NEWS_FROMS.length)];
+ data.tail = '15 minutes ago';
+ imageArray = shuffleArray(imageArray);
+ data.pics = imageArray;
+ data.preview = PREVIEW_IMAGES[Math.floor(Math.random() * PREVIEW_IMAGES.length)];
+ data.duration = '03:12';
+ res.push(data);
+ }
+ return res;
+}
+
+function shuffleArray(array: T[]): T[] {
+ const shuffled = [...array];
+ for (let i = shuffled.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ const tmp = shuffled[i];
+ shuffled[i] = shuffled[j];
+ shuffled[j] = tmp;
+ }
+ return shuffled;
+}
diff --git a/ComponentReuse/positive/src/main/ets/model/ItemData.ets b/ComponentReuse/positive/src/main/ets/model/ItemData.ets
new file mode 100644
index 0000000000000000000000000000000000000000..113eccbd7bde15caefdabb51720ec150931bf0a4
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/model/ItemData.ets
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+
+@Observed
+export class ItemData {
+ id: string = '';
+ title: string | Resource = '';
+ content: string = '';
+ from: string | Resource = '';
+ tail: string | Resource = '';
+ type: number = 0;
+ pics: Resource[] = [];
+ preview: Resource | string = '';
+ duration: string = '';
+
+ constructor(id: string, type: number) {
+ this.id = id;
+ this.type = type;
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/model/ItemDataSource.ets b/ComponentReuse/positive/src/main/ets/model/ItemDataSource.ets
new file mode 100644
index 0000000000000000000000000000000000000000..0056109375c97c16fa7075b877c94013a6d7fa4a
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/model/ItemDataSource.ets
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2025 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 { ItemData } from './ItemData';
+
+export class ItemDataSource implements IDataSource {
+ private listeners: DataChangeListener[] = [];
+ private originDataArray: ItemData[] = [];
+
+ public totalCount(): number {
+ return this.originDataArray.length;
+ }
+
+ public getData(index: number): ItemData {
+ return this.originDataArray[index];
+ }
+
+ registerDataChangeListener(listener: DataChangeListener): void {
+ if (this.listeners.indexOf(listener) < 0) {
+ this.listeners.push(listener);
+ }
+ }
+
+ unregisterDataChangeListener(listener: DataChangeListener): void {
+ const pos = this.listeners.indexOf(listener);
+ if (pos >= 0) {
+ this.listeners.splice(pos, 1);
+ }
+ }
+
+ notifyDataReload(): void {
+ this.listeners.forEach(listener => {
+ listener.onDataReloaded();
+ });
+ }
+
+ notifyDataAdd(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataAdd(index);
+ });
+ }
+
+ notifyDataChange(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataChange(index);
+ });
+ }
+
+ notifyDataDelete(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataDelete(index);
+ });
+ }
+
+ notifyDataMove(from: number, to: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataMove(from, to);
+ });
+ }
+
+ notifyDatasetChange(operations: DataOperation[]): void {
+ this.listeners.forEach(listener => {
+ listener.onDatasetChange(operations);
+ });
+ }
+
+ public pushArray(newData: ItemData[]): void {
+ this.originDataArray.push(...newData);
+ this.notifyDataReload();
+ }
+
+ public addItems(items: ItemData[]) {
+ this.originDataArray.push(...items);
+ this.notifyDataReload();
+ }
+
+ public add1stItem(item: ItemData): void {
+ this.originDataArray.splice(0, 0, item);
+ this.notifyDataAdd(0);
+ }
+
+ public addLastItem(item: ItemData): void {
+ this.originDataArray.splice(this.originDataArray.length, 0, item);
+ this.notifyDataAdd(this.originDataArray.length - 1);
+ }
+
+ public addItem(index: number, item: ItemData): void {
+ this.originDataArray.splice(index, 0, item);
+ this.notifyDataAdd(index);
+ }
+
+ public delete1stItem(): void {
+ this.originDataArray.splice(0, 1);
+ this.notifyDataDelete(0);
+ }
+
+ public delete2ndItem(): void {
+ this.originDataArray.splice(1, 1);
+ this.notifyDataDelete(1);
+ }
+
+ public deleteLastItem(): void {
+ this.originDataArray.splice(-1, 1);
+ this.notifyDataDelete(this.originDataArray.length);
+ }
+
+ public reload() {
+ this.originDataArray.splice(1, 1);
+ this.originDataArray.splice(3, 2);
+ this.reload();
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/model/TitleDataSource.ets b/ComponentReuse/positive/src/main/ets/model/TitleDataSource.ets
new file mode 100644
index 0000000000000000000000000000000000000000..d37993baa67ef5cbe2331a50ded9a41334922b00
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/model/TitleDataSource.ets
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2025 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 class TitleDataSource implements IDataSource {
+ private listeners: DataChangeListener[] = [];
+ private originDataArray: string[] = [];
+
+ totalCount(): number {
+ return this.originDataArray.length;
+ }
+
+ getData(index: number): string {
+ return this.originDataArray[index];
+ }
+
+ public addItem(title: string): void {
+ this.originDataArray.push(title);
+ this.notifyDataAdd(this.originDataArray.length - 1);
+ }
+
+ notifyDataAdd(index: number): void {
+ this.listeners.forEach(listener => {
+ listener.onDataAdd(index);
+ })
+ }
+
+ registerDataChangeListener(listener: DataChangeListener): void {
+ if (this.listeners.indexOf(listener) < 0) {
+ this.listeners.push(listener);
+ }
+ }
+
+ unregisterDataChangeListener(listener: DataChangeListener): void {
+ const pos = this.listeners.indexOf(listener);
+ if (pos > 0) {
+ this.listeners.splice(pos, 1);
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene1Positive.ets b/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene1Positive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..23ba2254217f616caf97cbf79dda173745401569
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene1Positive.ets
@@ -0,0 +1,130 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildImproperReuseOfComponentsScene1Positive() {
+ ImproperReuseOfComponentsScene1Positive()
+}
+
+// 父组件未使用复用,子组件使用复用
+@Component
+struct ImproperReuseOfComponentsScene1Positive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene2Positive.ets b/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene2Positive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..e6e02d6b022d02c8db19562409f5b171382f8159
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene2Positive.ets
@@ -0,0 +1,130 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildImproperReuseOfComponentsScene2Positive() {
+ ImproperReuseOfComponentsScene2Positive()
+}
+
+// 复用嵌套
+@Component
+struct ImproperReuseOfComponentsScene2Positive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene3Positive.ets b/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene3Positive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..edbe5aba6cbf7d6bed341fb21ebe2ae54351e1ab
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/ImproperReuseOfComponentsScene3Positive.ets
@@ -0,0 +1,188 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildImproperReuseOfComponentsScene3Positive() {
+ ImproperReuseOfComponentsScene3Positive()
+}
+
+// reuseId分类过粗
+@Component
+struct ImproperReuseOfComponentsScene3Positive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item }).reuseId(`${item.type}`)
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ // MiddleSingleImageView({ item: item })
+ if (item.type === 0) {
+ MiddleSingleImageView({ item: item })
+ } else if (item.type === 1) {
+ MiddleThreeImageView({ item: item })
+ } else {
+ MiddleVideoView({ item: item })
+ }
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/Index.ets b/ComponentReuse/positive/src/main/ets/pages/Index.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a26dc549f1f79a93a247824a332b7dd3bda60cef
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/Index.ets
@@ -0,0 +1,126 @@
+/*
+* 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 { CustomRoutes, Route, ChildRoute } from '../common/CustomRoutes';
+import { CommonConstants } from '../common/CommonConstants';
+
+@Entry
+@Component
+struct Index {
+ private routes: Route[] = CustomRoutes.ROUTES;
+ pathStack: NavPathStack = new NavPathStack();
+
+ @Builder
+ buildList() {
+ ForEach(this.routes, (item: Route) => {
+ Row() {
+ Text(item.title)
+ .width(CommonConstants.INDEX_CONTENT_WIDTH)
+ .fontSize(18)
+ .fontColor(Color.Black)
+ }
+ .height(20)
+
+ Column() {
+ ForEach(item.child, (itemChild: ChildRoute, index: number) => {
+ Column() {
+ Row() {
+ Text(itemChild.text)
+ .height(48)
+ .fontWeight(FontWeight.Medium)
+ .padding({ left: 12 })
+ .fontSize(16)
+ .fontColor($r('app.color.black_E6'))
+ Column().layoutWeight(1)
+
+ Text(itemChild.title ?? '')
+ .height(48)
+ .textAlign(TextAlign.End)
+ .fontWeight(FontWeight.Normal)
+ .fontSize(14)
+ .fontColor($r('app.color.black_99'))
+
+ Image($r('app.media.chevron_right'))
+ .width(24)
+ .height(24)
+ .margin({ right: 8 })
+ .fillColor($r('app.color.black_33'))
+ }
+ .justifyContent(FlexAlign.Start)
+ .alignItems(VerticalAlign.Center)
+
+ Text(itemChild.description)
+ .fontWeight(FontWeight.Medium)
+ .fontColor($r('app.color.gray_3'))
+ .padding({
+ left: 12,
+ right: 12,
+ bottom: (itemChild.description ?? '').length > 0 ? 10 : 0
+ })
+ .fontSize(12)
+
+ Stack() {
+ if (item.child.length - 1 !== index) {
+ Row()
+ .backgroundColor($r('app.color.gray_6'))
+ .width(CommonConstants.DIVIDER_WIDTH)
+ .height(CommonConstants.DIVIDER_HEIGHT)
+ }
+ }
+ }
+ .onClick(() => {
+ this.pathStack.pushPathByName(itemChild.to, null);
+ })
+ .width(CommonConstants.INDEX_CONTENT_WIDTH)
+ }, (item: ChildRoute, index: number) => JSON.stringify(item) + index)
+ }
+ .margin({ top: 14, bottom: 18 })
+ .borderRadius(18)
+ .backgroundColor(Color.White)
+ }, (item: Route, index: number) => JSON.stringify(item) + index)
+ }
+
+ build() {
+ Navigation(this.pathStack) {
+ Column() {
+ Row() {
+ Text('组件复用使用示例')
+ .fontWeight(FontWeight.Bold)
+ .fontSize(30)
+ .width('100%')
+ .fontColor('#FF333333')
+ }
+ .width(CommonConstants.INDEX_CONTENT_WIDTH)
+ .height(CommonConstants.INDEX_TITLE_HEIGHT)
+
+ Scroll() {
+ Column() {
+ this.buildList()
+ }
+ .padding({ bottom: 200 })
+ }
+ .scrollBar(BarState.Off)
+ .width(CommonConstants.Full_WIDTH)
+ .scrollable(ScrollDirection.Vertical)
+ }
+ .alignItems(HorizontalAlign.Center)
+ }
+ .hideNavBar(false)
+ .backgroundColor('#FFF5F5F5')
+ .mode(NavigationMode.Stack)
+ .width(CommonConstants.Full_WIDTH)
+ .height(CommonConstants.Full_HIIGHT)
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/NoReuseScene1Positive.ets b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene1Positive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..093206de353b19686644af81451daf8b3e826c89
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene1Positive.ets
@@ -0,0 +1,130 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene1Positive() {
+ NoReuseScene1Positive()
+}
+
+// 未使用组件复用:场景1
+@Component
+struct NoReuseScene1Positive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item })
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/NoReuseScene2_StructureOnePositive.ets b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene2_StructureOnePositive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..bfefc19df708df5b784a5faf11f36ae8f90e070d
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene2_StructureOnePositive.ets
@@ -0,0 +1,187 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene2_StructureOnePositive() {
+ NoReuseScene2_StructureOnePositive()
+}
+
+// 未使用组件复用:场景2 结构一
+@Component
+struct NoReuseScene2_StructureOnePositive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ NewsContent({ item: item }).reuseId(`${item.type}`)
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Component
+struct NewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ // MiddleSingleImageView({ item: item })
+ if (item.type === 0) {
+ MiddleSingleImageView({ item: item })
+ } else if (item.type === 1) {
+ MiddleThreeImageView({ item: item })
+ } else {
+ MiddleVideoView({ item: item })
+ }
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/NoReuseScene2_StructureTwoPositive.ets b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene2_StructureTwoPositive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..6457b5a7b2e3b569cd42643aaaee6b6c514ab523
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene2_StructureTwoPositive.ets
@@ -0,0 +1,253 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene2_StructureTwoPositive() {
+ NoReuseScene2_StructureTwoPositive()
+}
+
+// 未使用组件复用:场景2 结构二
+@Component
+struct NoReuseScene2_StructureTwoPositive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ if (item.type === 0) {
+ SingleImageNewsContent({ item: item })
+ } else if (item.type === 1) {
+ ThreeImageNewsContent({ item: item })
+ } else {
+ VideoNewsContent({ item: item })
+ }
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct SingleImageNewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Reusable
+@Component
+struct ThreeImageNewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleThreeImageView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Reusable
+@Component
+struct VideoNewsContent {
+ @ObjectLink item: ItemData;
+
+ @Builder
+ myBuilder(item: ItemData) {
+ TopView({ item: item })
+ MiddleVideoView({ item: item })
+ BottomView({ item: item })
+ }
+
+ build() {
+ Column() {
+ this.myBuilder(this.item)
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+}
+
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/pages/NoReuseScene3Positive.ets b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene3Positive.ets
new file mode 100644
index 0000000000000000000000000000000000000000..a6247d555077583335632d142a239ba07e2b7da4
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/pages/NoReuseScene3Positive.ets
@@ -0,0 +1,228 @@
+/*
+* 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 { ItemDataSource } from '../model/ItemDataSource';
+import { ItemData } from '../model/ItemData';
+import { genMockItemData } from '../common/MockData';
+
+@Builder
+function buildNoReuseScene3Positive() {
+ NoReuseScene3Positive()
+}
+
+// 未使用组件复用:场景3
+@Component
+struct NoReuseScene3Positive {
+ private dataSource: ItemDataSource = new ItemDataSource();
+
+ aboutToAppear(): void {
+ this.dataSource.pushArray(genMockItemData(1000));
+ }
+
+ @Builder
+ itemBuilderSingleImage(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleSingleImageView({ item: item })
+ BottomView({ item: item })
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+
+ @Builder
+ itemBuilderThreeImage(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleThreeImageView({ item: item })
+ BottomView({ item: item })
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+
+ @Builder
+ itemBuilderVideo(item: ItemData) {
+ Column() {
+ TopView({ item: item })
+ MiddleVideoView({ item: item })
+ BottomView({ item: item })
+ }
+ .alignItems(HorizontalAlign.Start)
+ .padding({
+ top: 16,
+ bottom: 12,
+ left: 16,
+ right: 16
+ })
+ .margin({
+ top: 12,
+ left: 16,
+ right: 16
+ })
+ .borderRadius(12)
+ .backgroundColor(Color.White)
+ }
+
+ build() {
+ NavDestination() {
+ Column() {
+ List() {
+ LazyForEach(this.dataSource, (item: ItemData) => {
+ ListItem() {
+ if (item.type === 0) {
+ this.itemBuilderSingleImage(item)
+ } else if (item.type === 1) {
+ this.itemBuilderThreeImage(item)
+ } else {
+ this.itemBuilderVideo(item)
+ }
+ }
+ }, (item: ItemData) => item.id.toString())
+ }
+ .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
+ .cachedCount(1)
+ .width('100%')
+ .height('100%')
+ }
+ .width('100%')
+ .height('100%')
+ }
+ }
+}
+
+@Reusable
+@Component
+struct TopView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.title)
+ .fontSize(16)
+ .fontWeight(FontWeight.Medium)
+ .fontColor(Color.Black)
+ .maxLines(2)
+ .lineHeight(22)
+ .opacity(0.9)
+ .textOverflow({ overflow: TextOverflow.Ellipsis })
+ .width('100%')
+ }
+}
+
+@Reusable
+@Component
+struct BottomView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Text(this.item.tail)
+ .fontSize(12)
+ .opacity(0.4)
+ .fontWeight(FontWeight.Regular)
+ .margin({ left: 6, top: 12 })
+ .width('100%')
+ }
+}
+
+@Reusable
+@Component
+struct MiddleSingleImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Image(this.item.preview)
+ .width(158)
+ .height(96)
+ .borderRadius(8)
+ .margin({ top: 8 })
+ }
+}
+
+@Reusable
+@Component
+struct MiddleThreeImageView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Row() {
+ Image(this.item.pics[0])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[1])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ Divider().width(2)
+ Image(this.item.pics[2])
+ .layoutWeight(1)
+ .height(98)
+ .borderRadius({ topLeft: 8, bottomLeft: 8 })
+ }
+ .margin({ top: 8 })
+ }
+}
+
+@Reusable
+@Component
+struct MiddleVideoView {
+ @ObjectLink item: ItemData;
+
+ build() {
+ Stack() {
+ Image(this.item.preview)
+ .width(112)
+ .height(112)
+ .borderRadius(8)
+ .margin({ top: 8 })
+
+ Row() {
+ Image($r('app.media.play_fill'))
+ .width(12).height(12)
+ Text(this.item.duration)
+ .fontColor(Color.White)
+ .fontSize(11)
+ .margin({ left: 2 })
+ .fontWeight(FontWeight.Medium)
+ }
+ .margin(6)
+ }
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/ets/positiveability/PositiveAbility.ets b/ComponentReuse/positive/src/main/ets/positiveability/PositiveAbility.ets
new file mode 100644
index 0000000000000000000000000000000000000000..c6c34586a69ccdff9727bc0ca43a9052a81618e7
--- /dev/null
+++ b/ComponentReuse/positive/src/main/ets/positiveability/PositiveAbility.ets
@@ -0,0 +1,58 @@
+/*
+* 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';
+
+const DOMAIN = 0x0000;
+
+export default class PositiveAbility extends UIAbility {
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
+ }
+
+ onDestroy(): void {
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
+ }
+
+ onWindowStageCreate(windowStage: window.WindowStage): void {
+ // Main window is created, set main page for this ability
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
+
+ windowStage.loadContent('pages/Index', (err) => {
+ if (err.code) {
+ hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
+ return;
+ }
+ hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
+ });
+ }
+
+ onWindowStageDestroy(): void {
+ // Main window is destroyed, release UI related resources
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
+ }
+
+ onForeground(): void {
+ // Ability has brought to foreground
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
+ }
+
+ onBackground(): void {
+ // Ability has back to background
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
+ }
+}
diff --git a/ComponentReuse/positive/src/main/module.json5 b/ComponentReuse/positive/src/main/module.json5
new file mode 100644
index 0000000000000000000000000000000000000000..3f84b258f76f6a25277fbb69ec1847c15759a34b
--- /dev/null
+++ b/ComponentReuse/positive/src/main/module.json5
@@ -0,0 +1,27 @@
+{
+ "module": {
+ "name": "positive",
+ "type": "feature",
+ "description": "$string:module_desc",
+ "mainElement": "PositiveAbility",
+ "deviceTypes": [
+ "phone"
+ ],
+ "deliveryWithInstall": true,
+ "installationFree": false,
+ "pages": "$profile:main_pages",
+ "routerMap": "$profile:route_map",
+ "abilities": [
+ {
+ "name": "PositiveAbility",
+ "srcEntry": "./ets/positiveability/PositiveAbility.ets",
+ "description": "$string:PositiveAbility_desc",
+ "icon": "$media:layered_image",
+ "label": "$string:PositiveAbility_label",
+ "startWindowIcon": "$media:startIcon",
+ "startWindowBackground": "$color:start_window_background",
+ "exported": true
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/ComponentReuse/positive/src/main/resources/base/element/color.json b/ComponentReuse/positive/src/main/resources/base/element/color.json
new file mode 100644
index 0000000000000000000000000000000000000000..3a0c6cea26e20e4f98146759d70e7e24da0e1d83
--- /dev/null
+++ b/ComponentReuse/positive/src/main/resources/base/element/color.json
@@ -0,0 +1,60 @@
+{
+ "color": [
+ {
+ "name": "start_window_background",
+ "value": "#FFFFFF"
+ },
+ {
+ "name": "text",
+ "value": "#2c2c2c"
+ },
+ {
+ "name": "home_background_color",
+ "value": "#F1F3F5"
+ },
+ {
+ "name": "gray_3",
+ "value": "#FF333333"
+ },
+ {
+ "name": "gray_6",
+ "value": "#FF666666"
+ },
+ {
+ "name": "gray_9",
+ "value": "#FF999999"
+ },
+ {
+ "name": "black_03",
+ "value": "#0D000000"
+ },
+ {
+ "name": "black_0D",
+ "value": "#0D000000"
+ },
+ {
+ "name": "black_12",
+ "value": "#12000000"
+ },
+ {
+ "name": "black_33",
+ "value": "#33000000"
+ },
+ {
+ "name": "black_66",
+ "value": "#66000000"
+ },
+ {
+ "name": "black_80",
+ "value": "#80000000"
+ },
+ {
+ "name": "black_99",
+ "value": "#99000000"
+ },
+ {
+ "name": "black_E6",
+ "value": "#E6000000"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Privacy/ContactDataError/src/main/resources/base/element/float.json b/ComponentReuse/positive/src/main/resources/base/element/float.json
similarity index 100%
rename from Privacy/ContactDataError/src/main/resources/base/element/float.json
rename to ComponentReuse/positive/src/main/resources/base/element/float.json
diff --git a/ComponentReuse/positive/src/main/resources/base/element/string.json b/ComponentReuse/positive/src/main/resources/base/element/string.json
new file mode 100644
index 0000000000000000000000000000000000000000..9457c23ad27ff744455cace91589c49dd8ad0d55
--- /dev/null
+++ b/ComponentReuse/positive/src/main/resources/base/element/string.json
@@ -0,0 +1,16 @@
+{
+ "string": [
+ {
+ "name": "module_desc",
+ "value": "module description"
+ },
+ {
+ "name": "PositiveAbility_desc",
+ "value": "description"
+ },
+ {
+ "name": "PositiveAbility_label",
+ "value": "label"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Privacy/ContactData/src/main/resources/base/media/background.png b/ComponentReuse/positive/src/main/resources/base/media/background.png
similarity index 100%
rename from Privacy/ContactData/src/main/resources/base/media/background.png
rename to ComponentReuse/positive/src/main/resources/base/media/background.png
diff --git a/ComponentReuse/positive/src/main/resources/base/media/chevron_right.png b/ComponentReuse/positive/src/main/resources/base/media/chevron_right.png
new file mode 100644
index 0000000000000000000000000000000000000000..4844d0b25d462fb2168b96efd9b6ae3c641e8bf9
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/chevron_right.png differ
diff --git a/Privacy/ContactDataError/src/main/resources/base/media/foreground.png b/ComponentReuse/positive/src/main/resources/base/media/foreground.png
similarity index 100%
rename from Privacy/ContactDataError/src/main/resources/base/media/foreground.png
rename to ComponentReuse/positive/src/main/resources/base/media/foreground.png
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img0.png b/ComponentReuse/positive/src/main/resources/base/media/img0.png
new file mode 100644
index 0000000000000000000000000000000000000000..1d967400f83bb0f5e2df4581415ed2e4cbb564d4
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img0.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img1.png b/ComponentReuse/positive/src/main/resources/base/media/img1.png
new file mode 100644
index 0000000000000000000000000000000000000000..b254fba00dcee070e90baf945e920a8f2f0646c6
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img1.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img2.jpg b/ComponentReuse/positive/src/main/resources/base/media/img2.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..4d36c1f9f8435424323ff12df2b0992bb09f8af5
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img2.jpg differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img3.png b/ComponentReuse/positive/src/main/resources/base/media/img3.png
new file mode 100644
index 0000000000000000000000000000000000000000..89214745c537495119e0e78c49e602f1c4933baa
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img3.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img4.png b/ComponentReuse/positive/src/main/resources/base/media/img4.png
new file mode 100644
index 0000000000000000000000000000000000000000..54e59fc403d92d11911498f7d3c7d39d6e437cf5
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img4.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img5.png b/ComponentReuse/positive/src/main/resources/base/media/img5.png
new file mode 100644
index 0000000000000000000000000000000000000000..a38a0eaab71c8c6ba4b94bff09b7d86e96510043
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img5.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img6.png b/ComponentReuse/positive/src/main/resources/base/media/img6.png
new file mode 100644
index 0000000000000000000000000000000000000000..c1175890f2f43f92082e40299d7bda81094e9c06
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img6.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img7.png b/ComponentReuse/positive/src/main/resources/base/media/img7.png
new file mode 100644
index 0000000000000000000000000000000000000000..cd29997cfc3b0f30e1d393d49961da58d691ab2f
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img7.png differ
diff --git a/ComponentReuse/positive/src/main/resources/base/media/img8.png b/ComponentReuse/positive/src/main/resources/base/media/img8.png
new file mode 100644
index 0000000000000000000000000000000000000000..1cff5e45d286fb3bc058d326fc9b31caf690ac63
Binary files /dev/null and b/ComponentReuse/positive/src/main/resources/base/media/img8.png differ
diff --git a/MultiVideoApplication/AppScope/resources/base/media/layered_image.json b/ComponentReuse/positive/src/main/resources/base/media/layered_image.json
similarity index 100%
rename from MultiVideoApplication/AppScope/resources/base/media/layered_image.json
rename to ComponentReuse/positive/src/main/resources/base/media/layered_image.json
diff --git a/ComponentReuse/positive/src/main/resources/base/media/play_fill.svg b/ComponentReuse/positive/src/main/resources/base/media/play_fill.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d1750a9cc4dc77103c03b7e11674b4e0b2b278d9
--- /dev/null
+++ b/ComponentReuse/positive/src/main/resources/base/media/play_fill.svg
@@ -0,0 +1,8 @@
+
+
\ No newline at end of file
diff --git a/MultiFinancialManagement/product/phone/src/main/resources/base/media/startIcon.png b/ComponentReuse/positive/src/main/resources/base/media/startIcon.png
similarity index 100%
rename from MultiFinancialManagement/product/phone/src/main/resources/base/media/startIcon.png
rename to ComponentReuse/positive/src/main/resources/base/media/startIcon.png
diff --git a/MultiDeviceCommunication/features/home/src/main/resources/base/profile/main_pages.json b/ComponentReuse/positive/src/main/resources/base/profile/main_pages.json
similarity index 100%
rename from MultiDeviceCommunication/features/home/src/main/resources/base/profile/main_pages.json
rename to ComponentReuse/positive/src/main/resources/base/profile/main_pages.json
diff --git a/ComponentReuse/positive/src/main/resources/base/profile/route_map.json b/ComponentReuse/positive/src/main/resources/base/profile/route_map.json
new file mode 100644
index 0000000000000000000000000000000000000000..15c6ca4fc92f90d395073d9f1e7d274f81077150
--- /dev/null
+++ b/ComponentReuse/positive/src/main/resources/base/profile/route_map.json
@@ -0,0 +1,39 @@
+{
+ "routerMap": [
+ {
+ "name": "NoReuseScene1Positive",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene1Positive.ets",
+ "buildFunction": "buildNoReuseScene1Positive"
+ },
+ {
+ "name": "NoReuseScene2_StructureOnePositive",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene2_StructureOnePositive.ets",
+ "buildFunction": "buildNoReuseScene2_StructureOnePositive"
+ },
+ {
+ "name": "NoReuseScene2_StructureTwoPositive",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene2_StructureTwoPositive.ets",
+ "buildFunction": "buildNoReuseScene2_StructureTwoPositive"
+ },
+ {
+ "name": "NoReuseScene3Positive",
+ "pageSourceFile": "src/main/ets/pages/NoReuseScene3Positive.ets",
+ "buildFunction": "buildNoReuseScene3Positive"
+ },
+ {
+ "name": "ImproperReuseOfComponentsScene1Positive",
+ "pageSourceFile": "src/main/ets/pages/ImproperReuseOfComponentsScene1Positive.ets",
+ "buildFunction": "buildImproperReuseOfComponentsScene1Positive"
+ },
+ {
+ "name": "ImproperReuseOfComponentsScene2Positive",
+ "pageSourceFile": "src/main/ets/pages/ImproperReuseOfComponentsScene2Positive.ets",
+ "buildFunction": "buildImproperReuseOfComponentsScene2Positive"
+ },
+ {
+ "name": "ImproperReuseOfComponentsScene3Positive",
+ "pageSourceFile": "src/main/ets/pages/ImproperReuseOfComponentsScene3Positive.ets",
+ "buildFunction": "buildImproperReuseOfComponentsScene3Positive"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/CppCrash/README.md b/CppCrash/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..db47470722e62a89946960bb8e3844f16a4a034a
--- /dev/null
+++ b/CppCrash/README.md
@@ -0,0 +1,73 @@
+# Native崩溃(Cpp Crash)样例代码工程
+
+### 介绍
+
+本示例为Native崩溃(Cpp Crash)样例代码工程,包含最佳实践文档中涉及的分析方法、优化建议、问题案例等内容的局部样例代码。工程本身不具备实际功能,开发者请直接阅读具体源码结合文档来理解Native崩溃(Cpp Crash)类问题的产生原因,规避方法等。
+
+
+### 效果预览
+
+不涉及
+
+### 工程目录
+```
+├──entry/src/main/
+│ └──cpp
+│ │ ├── CMakeLists.txt
+│ │ ├── CppCrashAdvise1.cpp // C++ 样例代码
+│ │ ├── CppCrashAdvise2.cpp // C++ 样例代码
+│ │ ├── CppCrashAdvise3.cpp // C++ 样例代码
+│ │ ├── CppCrashAdvise4.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse1.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse2.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse3.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse4.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse5.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse6.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalyse7.cpp // C++ 样例代码
+│ │ ├── CppCrashCaseAnalysis8.cpp // C++ 样例代码
+│ │ ├── CppCrashQuestionCheck1.cpp // C++ 样例代码
+│ │ ├── CppCrashQuestionCheck2.cpp // C++ 样例代码
+│ │ └── napi_init.cpp // C++ 样例代码
+│ └──ets
+│ ├──pages
+│ │ └──Index.ets // 首页
+│ ├──entryability
+│ │ └──EntryAbility.ets // Ability的生命周期回调内容
+│ └──entrybackupability
+│ └──EntryBackupAbility.ets // 应用数据备份恢复类
+└──entry/src/main/resources // 应用资源目录
+```
+
+### 具体实现
+
+不涉及。
+
+### 相关权限
+
+不涉及。
+
+### 依赖
+
+不涉及。
+
+### 约束与限制
+
+1. 本示例仅支持标准系统上运行,支持设备:华为手机、华为PC/2in1设备、华为平板。
+
+2. HarmonyOS系统:HarmonyOS NEXT 5.0.5 Release及以上。
+
+3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。
+
+4. HarmonyOS SDK版本:HarmonyOS NEXT 5.0.5 Release SDK及以上。
+
+### 下载
+
+如需单独下载本工程,执行如下命令:
+```
+git clone --filter=blob:none --no-checkout https://gitee.com/harmonyos_samples/BestPracticeSnippets.git
+cd BestPracticeSnippets
+git sparse-checkout init --cone
+git sparse-checkout set CppCrash
+git checkout
+```
\ No newline at end of file
diff --git a/CppCrash/build-profile.json5 b/CppCrash/build-profile.json5
index adff6a0e3095f2c79f2fede08f299e7658c3dbca..9e87e7e6f19020fe21192844709f192cec80fd44 100644
--- a/CppCrash/build-profile.json5
+++ b/CppCrash/build-profile.json5
@@ -6,7 +6,7 @@
"name": "default",
"signingConfig": "default",
"targetSdkVersion": "5.0.5(17)",
- "compatibleSdkVersion": "5.0.0(12)",
+ "compatibleSdkVersion": "5.0.5(17)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
diff --git a/CppCrash/entry/src/main/cpp/CMakeLists.txt b/CppCrash/entry/src/main/cpp/CMakeLists.txt
index 1acd3ec1c568e86cb70911ecc57edfbb21bcd1ea..a5c06660812f7ed74934a6a93282d445f974a451 100644
--- a/CppCrash/entry/src/main/cpp/CMakeLists.txt
+++ b/CppCrash/entry/src/main/cpp/CMakeLists.txt
@@ -2,6 +2,9 @@
cmake_minimum_required(VERSION 3.5.0)
project(CppCrash)
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
if(DEFINED PACKAGE_FIND_FILE)
@@ -11,5 +14,10 @@ endif()
include_directories(${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/include)
-add_library(entry SHARED napi_init.cpp)
+#add_library(entry SHARED napi_init.cpp CppCrashAdvise1.cpp CppCrashCaseAnalyse1.cpp CppCrashCaseAnalyse2.cpp
+# CppCrashCaseAnalyse3.cpp CppCrashCaseAnalyse4.cpp CppCrashCaseAnalyse5.cpp CppCrashCaseAnalyse6.cpp
+# CppCrashCaseAnalyse7.cpp CppCrashCaseAnalysis8.cpp CppCrashQuestionCheck1.cpp CppCrashQuestionCheck2.cpp)
+add_library(entry SHARED napi_init.cpp CppCrashAdvise1.cpp CppCrashAdvise2.cpp CppCrashAdvise3.cpp CppCrashAdvise4.cpp
+ CppCrashQuestionCheck1.cpp CppCrashQuestionCheck2.cpp CppCrashCaseAnalyse5.cpp CppCrashCaseAnalyse6.cpp
+ CppCrashCaseAnalyse7.cpp CppCrashCaseAnalysis8.cpp)
target_link_libraries(entry PUBLIC libace_napi.z.so)
\ No newline at end of file
diff --git a/CppCrash/entry/src/main/cpp/CppCrashAdvise1.cpp b/CppCrash/entry/src/main/cpp/CppCrashAdvise1.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c8ff6d68c40f0f5626466352a55d8fcb0dd3a705
--- /dev/null
+++ b/CppCrash/entry/src/main/cpp/CppCrashAdvise1.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2025 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.
+ */
+/**
+ * 最佳实践:CppCrash类问题优化建议
+ */
+
+#include
+#include
+#include