update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai
2021-06-02 00:05:05 +08:00
parent 402efcee42
commit 16b11fc8d1
446 changed files with 103646 additions and 73 deletions
View File
+14
View File
@@ -0,0 +1,14 @@
# Copyright (c) 2021 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("//build/ohos.gni")
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
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:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) 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
(d) 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
+70
View File
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2021 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.
Notes:
This is project config file for OpenHarmony OSS Audit Tool, if you have any questions or concerns, please email chenyaxun@huawei.com.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
<filteritem type="filename" name="*.hap|*.rpk" desc="valid and invalid bundle files for tests"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>
-36
View File
@@ -1,36 +0,0 @@
# aafwk_standard
#### Description
Ability management framework | 元能力框架
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
-37
View File
@@ -1,37 +0,0 @@
# aafwk_standard
#### 介绍
Ability management framework | 元能力框架
#### 软件架构
软件架构说明
#### 安装教程
1. xxxx
2. xxxx
3. xxxx
#### 使用说明
1. xxxx
2. xxxx
3. xxxx
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
#### 特技
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
Executable
+134
View File
@@ -0,0 +1,134 @@
# 元能力子系统
## 简介
**元能力子系统**实现对Ability的运行及生命周期进行统一的调度和管理,应用进程能够支撑多个Ability,Ability具有跨应用进程间和同一进程内调用的能力。Ability管理服务统一调度和管理应用中各Ability,并对Ability的生命周期变更进行管理。
![](figures/aafwk.png)
**元能力子系统架构图说明:**
- **Ability Kit**为Ability的运行提供基础的运行环境支撑。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。Ability分为FAFeature Ability)和PAParticle Ability)两种类,其中FA支持Page AbilityPA支持Service Ability和Data Ability。
- **Ability管理服务(AbilityManagerService**:用于协调各Ability运行关系、及对生命周期进行调度的系统服务。
- Ability栈管理模块(AbilityStackManager)负责维护各个Ability之间跳转的先后关系。
- 连接管理模块(AbilityConnectManager)是Ability管理服务对Service类型Ability连接管理的模块。
- 数据管理模块(DataAbilityManager)是Ability管理服务对Data类型Ability管理的模块。
- App管理服务调度模块(AppScheduler)提供Ability管理服务对用户程序管理服务进行调度管理的能力。
- Ability调度模块(AbilityScheduler)提供对Ability进行调度管理的能力。
- 生命周期调度模块(LifecycleDeal)是Ability管理服务对Ability的生命周期事件进行管理调度的模块。
**Ability生命周期介绍**Ability Life Cycle)是Ability被调度到INACTIVE、ACTIVE、BACKGROUND等各个状态的统称(主要涉及PageAbility类型和ServiceAbility类型的Ability)。
- **PageAbility类型的Ability生命周期流转如下图所示**
![PageAbility-Lifecycle](figures/page-ability-lifecycle.png)
- **ServiceAbility类型的Ability生命周期流转如下图所示**
![ServiceAbility-Lifecycle](figures/service-ability-lifecycle.png)
**Ability生命周期状态说明:**
- **UNINITIALIZED**:未初始状态,为临时状态,Ability被创建后会由UNINITIALIZED状态进入INITIAL状态。
- **INITIAL**:初始化状态,也表示停止状态,表示当前Ability未运行,Ability被启动后由INITIAL态进入INACTIVE状态。
- **INACTIVE**:未激活状态,表示当前窗口已显示但是无焦点状态,由于Window暂未支持焦点的概念,当前状态与ACTIVE一致。
- **ACTIVE**:前台激活状态,表示当前窗口已显示,并获取焦点,Ability在退到后台之前先由ACTIVE状态进入INACTIVE状态。
- **BACKGROUND**: 后台状态,表示当前Ability退到后台,Ability在被销毁后由BACKGROUND状态进入INITIAL状态,或者重新被激活后由BACKGROUND状态进入ACTIVE状态。
**PageAbility类型Ability生命周期回调如下图所示:**
![PageAbility-Lifecycel-Callbacks](figures/page-ability-lifecycle-callbacks.png)
**ServiceAbility类型Ability生命周期回调如下图所示:**
![Service-Ability-Lifecycle-Callbacks](figures/service-ability-lifecycle-callbacks.jpg)
## 目录
```
foundation/
└──foundation/aafwk/standard
   ├── frameworks
   │   └── kits
   │   └── ability # AbilityKit实现的核心代码
   ├── interfaces
   │   └── innerkits
   │      └── want # Ability之间交互的信息载体的对外接口
└── services
├── abilitymgr # Ability管理服务框架代码
  ├── common # 日志组件目录
  ├── test # 测试目录
  └── tools # aa命令代码目录
```
## 使用说明
当前版本用户程序框架不具备权限管理的能力。
以下模块的JS接口为非正式API,仅供Launcher、Settings、SystemUI等系统应用使用,不排除对这些接口进行变更的可能性,后续版本将提供正式API。
- @ohos.feature_ability.d.ts
- @ohos.napi_ability_manager.d.ts
- abilityinfo.d.ts
- abilitymissioninfo.d.ts
- applicationinfo.d.ts
- appprocessstate.ts
- common.d.ts
- elementname.d.ts
- moduleinfo.d.ts
- processinfo.d.ts
- want.d.ts
## **aa命令**
**aa help**
| 命令 | 描述 |
| ------- | ------------------ |
| aa help | 显示aa命令帮助信息 |
**aa start**
| 命令 | 描述 |
| --------------------------------------------------------- | ------------------------ |
| aa start [-d <device>] -a <ability-name> -b <bundle-name> | 启动ability,设备ID 可空 |
```
示例:
aa start -d 12345 -a com.ohos.app.MainAbility -b com.ohos.app
```
**aa dump**
| 命令 | 描述 |
| ---------- | --------------------- |
| aa dump -a | 打印栈中的Ability信息 |
## 相关仓
元能力子系统
appexecfwk_standard
**aafwk_standard**
+21
View File
@@ -0,0 +1,21 @@
# Copyright (c) 2021 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.
aafwk_path = "//foundation/aafwk/standard"
appexecfwk_path = "//foundation/appexecfwk/standard"
services_path = "${aafwk_path}/services"
kits_path = "${aafwk_path}/frameworks/kits"
innerkits_path = "${aafwk_path}/interfaces/innerkits"
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+147
View File
@@ -0,0 +1,147 @@
# Copyright (c) 2021 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("//build/ohos.gni")
SUBSYSTEM_DIR = "//foundation/aafwk/standard/frameworks/kits/ability/native"
SUBSYSTEM_APPEXEXFWK_DIR = "//foundation/appexecfwk/standard"
INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits"
config("ability_config") {
visibility = [ ":*" ]
include_dirs = [
"${INNERKITS_PATH}/base/include",
"//utils/native/base/include",
"${SUBSYSTEM_DIR}/include",
"${SUBSYSTEM_APPEXEXFWK_DIR}/kits/appkit/native/app/include",
"${SUBSYSTEM_APPEXEXFWK_DIR}/interfaces/innerkits/appexecfwk_core/include/appmgr",
"${INNERKITS_PATH}/want/include/ohos/aafwk/content",
"${INNERKITS_PATH}/ability_manager/include",
"//foundation/aafwk/standard/services/abilitymgr/include",
"//foundation/appexecfwk/standard/common/log/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//base/global/resmgr_standard/interfaces/innerkits/include",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/context",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility",
"//foundation/ace/napi/interfaces/kits",
"//third_party/node/src",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"Ability\"",
"LOG_DOMAIN = 0xD002200",
]
}
config("ability_public_config") {
visibility = [ ":*" ]
include_dirs = [
"${INNERKITS_PATH}/base/include",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
"${SUBSYSTEM_DIR}/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base",
"//base/global/resmgr_standard/interfaces/innerkits/include",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event/include",
]
}
ohos_shared_library("abilitykit_native") {
sources = [
"${SUBSYSTEM_APPEXEXFWK_DIR}/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp",
"${SUBSYSTEM_DIR}/src/ability.cpp",
"${SUBSYSTEM_DIR}/src/ability_context.cpp",
"${SUBSYSTEM_DIR}/src/ability_handler.cpp",
"${SUBSYSTEM_DIR}/src/ability_impl.cpp",
"${SUBSYSTEM_DIR}/src/ability_impl_factory.cpp",
"${SUBSYSTEM_DIR}/src/ability_lifecycle.cpp",
"${SUBSYSTEM_DIR}/src/ability_lifecycle_executor.cpp",
"${SUBSYSTEM_DIR}/src/ability_loader.cpp",
"${SUBSYSTEM_DIR}/src/ability_local_record.cpp",
"${SUBSYSTEM_DIR}/src/ability_process.cpp",
"${SUBSYSTEM_DIR}/src/ability_thread.cpp",
"${SUBSYSTEM_DIR}/src/ability_window.cpp",
"${SUBSYSTEM_DIR}/src/data_ability_helper.cpp",
"${SUBSYSTEM_DIR}/src/data_ability_impl.cpp",
"${SUBSYSTEM_DIR}/src/data_uri_utils.cpp",
"${SUBSYSTEM_DIR}/src/dummy_data_ability_predicates.cpp",
"${SUBSYSTEM_DIR}/src/dummy_values_bucket.cpp",
"${SUBSYSTEM_DIR}/src/page_ability_impl.cpp",
"${SUBSYSTEM_DIR}/src/service_ability_impl.cpp",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/context/napi_context.cpp",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ability_start_setting.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/sys_mgr_client.cpp",
]
configs = [ ":ability_config" ]
public_configs = [ ":ability_public_config" ]
deps = [
"${INNERKITS_PATH}/base:base",
"${INNERKITS_PATH}/want:want",
# "//foundation/graphic/standard/prebuilts/librarys/display_gralloc:libdisplay_gralloc",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/ace/napi:ace_napi",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
public_deps = [ "//foundation/graphic/standard:libwms_client" ]
subsystem_name = "aafwk"
part_name = "aafwk_standard"
}
ohos_shared_library("dummy_classes") {
sources = [
"${SUBSYSTEM_DIR}/src/dummy_data_ability_predicates.cpp",
"${SUBSYSTEM_DIR}/src/dummy_result_set.cpp",
"${SUBSYSTEM_DIR}/src/dummy_values_bucket.cpp",
]
configs = [ ":ability_config" ]
public_configs = [ ":ability_public_config" ]
deps = [
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
subsystem_name = "aafwk"
part_name = "aafwk_standard"
}
@@ -0,0 +1,849 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_H
#include "iremote_object.h"
#include "ability_context.h"
#include "ability_event_interface.h"
#include <functional>
#include <string>
#include <unistd.h>
#include "context.h"
#include "want.h"
#include "key_event.h"
#include "dummy_component_container.h"
#include "pac_map.h"
#include "touch_event.h"
#include "dummy_notification_request.h"
#include "dummy_data_ability_predicates.h"
#include "dummy_values_bucket.h"
#include "dummy_raw_file_descriptor.h"
#include "dummy_result_set.h"
#include "dummy_continuation_state.h"
#include "dummy_ability_package.h"
#include "dummy_file_descriptor.h"
#include "dummy_configuration.h"
#include "ability_window.h"
#include "ability_lifecycle_interface.h"
#include "ability_lifecycle_executor.h"
#define WMS_COMPILE
using Uri = OHOS::Uri;
namespace OHOS {
namespace AppExecFwk {
class OHOSApplication;
class AbilityHandler;
class AbilityWindow;
class ILifeCycle;
class Ability : public IAbilityEvent,
public ILifeCycle,
public AbilityContext,
public std::enable_shared_from_this<Ability> {
public:
Ability() = default;
virtual ~Ability() = default;
/**
* @brief Destroys ability.
*
* @param want Indicates the want containing information about TerminateAbility
*
* @return Returns the result of TerminateAbility
*/
using AbilityContext::TerminateAbility;
int TerminateAbility(Want &want);
/**
* @brief By binding an action, you can set different action parameters in Intent to present different initial
* pages. You must register actions in the profile file.
*
* @param action Indicates the action to bind.
*
* @param entry Indicates the entry, which is the fully qualified name of your AbilitySlice class.
*
* @return Returns the result of AddActionRoute
*/
virtual void AddActionRoute(const std::string &action, const std::string &entry) final;
/**
* @brief Sets the background color of the window in RGB color mode.
*
* @param red The value ranges from 0 to 255.
*
* @param green The value ranges from 0 to 255.
*
* @param blue The value ranges from 0 to 255.
*
* @return Returns the result of SetWindowBackgroundColor
*/
virtual int SetWindowBackgroundColor(int red, int green, int blue) final;
/**
* @brief Destroys this Page or Service ability.
* After a Page or Service ability performs all operations, it can use this method to destroy itself
* to free up memory. This method can be called only after the ability is initialized.
*/
virtual void TerminateAbility() final;
/**
* @brief Obtains the Lifecycle object of the current ability.
*
* @return Returns the Lifecycle object.
*/
virtual std::shared_ptr<LifeCycle> GetLifecycle() override final;
/**
* @brief Obtains a resource manager.
*
* @return Returns a ResourceManager object.
*/
std::shared_ptr<Global::Resource::ResourceManager> GetResourceManager() const override;
/**
* @brief Inflates UI controls by using ComponentContainer.
* You can create a ComponentContainer instance that contains multiple components.
*
* @param componentContainer Indicates a set of customized components.
*/
virtual void SetUIContent(const ComponentContainer &componentContainer);
/**
* @brief Inflates layout resources by using the layout resource ID.
*
* @param layoutRes Indicates the layout resource ID, which cannot be a negative number.
*/
virtual void SetUIContent(int layoutRes) final;
/**
* Start other ability for result.
*
* @param want information of other ability
* @param requestCode request code for abilityMS to return result
*/
virtual void StartAbilityForResult(const Want &want, int requestCode) final;
/**
* Starts an ability with specific start settings and returns the execution result when the ability is destroyed.
* When the ability is destroyed, onAbilityResult(int,int,ohos.aafwk.content.Want) is called and the returned
* requestCode is transferred to the current method. The given requestCode is customized and cannot be a negative
* number.
*
* @param want Indicates the ability to start.
* @param requestCode Indicates the request code returned after the ability is started. You can define the request
* code to identify the results returned by abilities. The value ranges from 0 to 65535.
* @param abilityStartSetting Indicates the setting ability used to start.
*/
virtual void StartAbilityForResult(
const Want &want, int requestCode, AbilityStartSetting abilityStartSetting) final;
/**
* Starts a new ability with specific start settings.
* A Page or Service ability uses this method to start a specific ability.
* The system locates the target ability from installed abilities based on
* the value of the intent parameter and then starts it. You can specify the
* ability to start using the intent parameter.
*
* @param want Indicates the ability to start.
* @param abilityStartSetting Indicates the setting ability used to start.
*/
void StartAbility(const Want &want, AbilityStartSetting abilityStartSetting);
// lifecycle callback
virtual void Init(const std::shared_ptr<AbilityInfo> &abilityInfo,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token);
/**
* @brief Called when this ability is started. You must override this function if you want to perform some
* initialization operations during ability startup.
*
* This function can be called only once in the entire lifecycle of an ability.
* @param Want Indicates the {@link Want} structure containing startup information about the ability.
*/
virtual void OnStart(const Want &want);
/**
* @brief Called when this ability enters the <b>STATE_STOP</b> state.
*
* The ability in the <b>STATE_STOP</b> is being destroyed.
* You can override this function to implement your own processing logic.
*/
virtual void OnStop();
/**
* @brief Called when this ability enters the <b>STATE_ACTIVE</b> state.
*
* The ability in the <b>STATE_ACTIVE</b> state is visible and has focus.
* You can override this function to implement your own processing logic.
*
* @param Want Indicates the {@link Want} structure containing activation information about the ability.
*/
virtual void OnActive();
/**
* @brief Called when this ability enters the <b>STATE_INACTIVE</b> state.
*
* <b>STATE_INACTIVE</b> is an instantaneous state. The ability in this state may be visible but does not have
* focus.You can override this function to implement your own processing logic.
*/
virtual void OnInactive();
/**
* @brief Called when this ability enters the <b>STATE_FOREGROUND</b> state.
*
*
* The ability in the <b>STATE_FOREGROUND</b> state is visible.
* You can override this function to implement your own processing logic.
*/
virtual void OnForeground(const Want &want);
/**
* @brief Called when this ability enters the <b>STATE_BACKGROUND</b> state.
*
*
* The ability in the <b>STATE_BACKGROUND</b> state is invisible.
* You can override this function to implement your own processing logic.
*/
virtual void OnBackground();
/**
* @brief Called when a key is pressed. When any component in the Ability gains focus, the key-down event for
* the component will be handled first. This callback will not be invoked if the callback triggered for the
* key-down event of the component returns true. The default implementation of this callback does nothing
* and returns false.
*
* @param keyCode Indicates the code of the key pressed.
* @param keyEvent Indicates the key-down event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event
* is not handled and should be passed to other handlers.
*/
virtual bool OnKeyDown(int keyCode, const KeyEvent &keyEvent);
/**
* @brief Called when a key is released. When any component in the Ability gains focus, the key-up event for
* the component will be handled first. This callback will not be invoked if the callback triggered for the
* key-up event of the component returns true. The default implementation of this callback does nothing and
* returns false.
*
* @param keyCode Indicates the code of the key released.
* @param keyEvent Indicates the key-up event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event
* is not handled and should be passed to other handlers.
*/
virtual bool OnKeyUp(int keyCode, const KeyEvent &keyEvent);
/**
* @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
* does nothing and returns false.
*
* @param event Indicates information about the touch event.
*
* @return Returns true if the event is handled; returns false otherwise.
*/
virtual bool OnTouchEvent(const TouchEvent &touchEvent);
/**
* @brief Called when this Service ability is connected for the first time.
*
* You can override this function to implement your own processing logic.
*
* @param want Indicates the {@link Want} structure containing connection information about the Service ability.
* @return Returns a pointer to the <b>sid</b> of the connected Service ability.
*/
virtual sptr<IRemoteObject> OnConnect(const Want &want);
/**
* @brief Called when all abilities connected to this Service ability are disconnected.
*
* You can override this function to implement your own processing logic.
*
*/
virtual void OnDisconnect(const Want &want);
/**
* @brief Inflates UI controls by using ComponentContainer.
* You can create a ComponentContainer instance that contains multiple components.
*
* @param componentContainer Indicates the component layout defined by the user.
* @param context Indicates the context to use.
* @param typeFlag Indicates the window type.
*/
virtual void SetUIContent(
const ComponentContainer &componentContainer, std::shared_ptr<Context> &context, int typeFlag);
/**
* @brief Inflates layout resources by using the layout resource ID.
*
* @param layoutRes Indicates the layout resource ID, which cannot be a negative number.
* @param context Indicates the context to use.
* @param typeFlag Indicates the window type.
*/
virtual void SetUIContent(int layoutRes, std::shared_ptr<Context> &context, int typeFlag);
#ifdef WMS_COMPILE
/**
* @brief Inflates UI controls by using WindowConfig.
*
* @param config Indicates the window config defined by the user.
*/
virtual void SetUIContent(const WindowConfig &config);
/**
* @brief Get the window belong to the ability.
*
* @return Returns a Window object pointer.
*/
virtual const std::unique_ptr<Window> &GetWindow();
#endif // WMS_COMPILE
/**
* @brief Checks whether the main window of this ability has window focus.
*
* @return Returns true if this ability currently has window focus; returns false otherwise.
*/
bool HasWindowFocus();
/**
* @brief Called when a key is lone pressed.
*
* @param keyCode Indicates the code of the key long pressed.
* @param keyEvent Indicates the key-long-press event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event
* is not handled and should be passed to other handlers.
*/
virtual bool OnKeyPressAndHold(int keyCode, const std::shared_ptr<KeyEvent> &keyEvent);
/**
* @brief Called back after permissions are requested by using
* AbilityContext.requestPermissionsFromUser(java.lang.String[],int).
*
* @param requestCode Indicates the request code passed to this method from
* AbilityContext.requestPermissionsFromUser(java.lang.String[],int).
* @param permissions Indicates the list of permissions requested by using
* AbilityContext.requestPermissionsFromUser(java.lang.String[],int). This parameter cannot be null.
* @param grantResults Indicates the granting results of the corresponding permissions requested using
* AbilityContext.requestPermissionsFromUser(java.lang.String[],int). The value 0 indicates that a
* permission is granted, and the value -1 indicates not.
*
*/
virtual void OnRequestPermissionsFromUserResult(
int requestCode, const std::vector<std::string> &permissions, const std::vector<int> &grantResults);
/**
* @brief Called when this ability is about to leave the foreground and enter the background due to a user
* operation, for example, when the user touches the Home key.
*
*/
virtual void OnLeaveForeground();
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
virtual std::string GetType(const Uri &uri);
/**
* @brief Inserts a data record into the database. This method should be implemented by a Data ability.
*
* @param uri Indicates the position where the data is to insert.
* @param value Indicates the data to insert.
*
* @return Returns the index of the newly inserted data record.
*/
virtual int Insert(const Uri &uri, const ValuesBucket &value);
/**
* @brief Called when the system configuration is updated.
*
* @param configuration Indicates the updated configuration information.
*/
virtual void OnConfigurationUpdated(const Configuration &configuration);
/**
* @brief Called when the system configuration is updated.
*
* @param level Indicates the memory trim level, which shows the current memory usage status.
*
*/
virtual void OnMemoryLevel(int level);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
virtual int OpenRawFile(const Uri &uri, const std::string &mode);
/**
* @brief Updates one or more data records in the database. This method should be implemented by a Data ability.
*
* @param uri Indicates the database table storing the data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. If this parameter is null, all data records will be updated by
* default.
*
* @return Returns the number of data records updated.
*/
virtual int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates);
/**
* @brief get application witch the ability belong
*
* @return Returns the application ptr
*/
std::shared_ptr<OHOSApplication> GetApplication();
/**
* @brief Obtains the class name in this ability name, without the prefixed bundle name.
*
* @return Returns the class name of this ability.
*/
std::string GetAbilityName();
/**
* @brief OChecks whether the current ability is being destroyed.
* An ability is being destroyed if you called terminateAbility() on it or someone else requested to destroy it.
*
* @return Returns true if the current ability is being destroyed; returns false otherwise.
*/
bool IsTerminating();
/**
* @brief Called when startAbilityForResult(ohos.aafwk.content.Want,int) is called to start an ability and the
* result is returned. This method is called only on Page abilities. You can start a new ability to perform some
* calculations and use setResult (int,ohos.aafwk.content.Want) to return the calculation result. Then the system
* calls back the current method to use the returned data to execute its own logic.
*
* @param requestCode Indicates the request code returned after the ability is started. You can define the request
* code to identify the results returned by abilities. The value ranges from 0 to 65535.
* @param resultCode Indicates the result code returned after the ability is started. You can define the result code
* to identify an error.
* @param resultData Indicates the data returned after the ability is started. You can define the data returned. The
* value can be null.
*
*/
virtual void OnAbilityResult(int requestCode, int resultCode, const Want &resultData);
/**
* @brief Called back when the Back key is pressed.
* The default implementation destroys the ability. You can override this method.
*
*/
virtual void OnBackPressed() override;
/**
* @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch an
* ability that has been at the top of the ability stack.
*
* @param want Indicates the new Want containing information about the ability.
*/
virtual void OnNewWant(const Want &want);
/**
* @brief Restores data and states of an ability when it is restored by the system. This method should be
* implemented by a Page ability. This method is called if an ability was destroyed at a certain time due to
* resource reclaim or was unexpectedly destroyed and the onSaveAbilityState(ohos.utils.PacMap) method was called to
* save its user data and states. Generally, this method is called after the onStart(ohos.aafwk.content.Want)
* method.
*
* @param inState Indicates the PacMap object used for storing data and states. This parameter can not be null.
*
*/
virtual void OnRestoreAbilityState(const PacMap &inState);
/**
* @brief Saves temporary data and states of this ability. This method should be implemented by a Page ability.
* This method is called when the system determines that the ability may be destroyed in an unexpected situation,
* for example, when the screen orientation changes or the user touches the Home key. Generally, this method is used
* only to save temporary states.
*
* @param outState Indicates the PacMap object used for storing user data and states. This parameter cannot be
* null.
*
*/
virtual void OnSaveAbilityState(PacMap &outState);
/**
* @brief Called every time a key, touch, or trackball event is dispatched to this ability.
* You can override this callback method if you want to know that the user has interacted with
* the device in a certain way while this ability is running. This method, together with onLeaveForeground(),
* is designed to help abilities intelligently manage status bar notifications. Specifically, they help
* abilities determine when to cancel a notification.
*
*/
virtual void OnEventDispatch();
/**
* @brief Called when this ability gains or loses window focus.
* The focus state refers to the global state, which is independent of the ability lifecycle states.
* Although the lifecycle state change of an ability may lead to a focus change (for example, onStop()
* may cause the ability to lose window focus), there is no particular sequence between this callback
* and other lifecycle callbacks such as onBackground().
* Generally, the ability in the foreground will have window focus. The ability will lose focus when
* another dialog box or pop-up window is displayed. The ability will also lose focus when a system-level
* window (such as the status bar or a system alarm) is displayed.
*
* @param hasFocus Specifies whether this ability has focus.
*/
virtual void OnWindowFocusChanged(bool hasFocus);
/**
* @brief Sets the want object that can be obtained by calling getWant().
*
* @param Want information of other ability
*/
void SetWant(const AAFwk::Want &want);
/**
@brief Obtains the Want object that starts this ability.
*
@return Returns the Want object that starts this ability.
*/
std::shared_ptr<AAFwk::Want> GetWant();
/**
* @brief Sets the result code and data to be returned by this Page ability to the caller.
* When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to
* receive the result set in the current method. This method can be called only after the ability has been
* initialized.
*
* @param resultCode Indicates the result code returned after the ability is destroyed. You can define the result
* code to identify an error.
* @param resultData Indicates the data returned after the ability is destroyed. You can define the data returned.
* This parameter can be null.
*/
virtual void SetResult(int resultCode, /*const AAFwk::Want& resultData*/ const Want &resultData) final;
/**
* @brief Sets the type of audio whose volume will be adjusted by the volume button.
*
* @param volumeType Indicates the AudioManager.AudioVolumeType to set.
*/
virtual void SetVolumeTypeAdjustedByKey(int volumeType);
/**
* @brief Called back when Service is started.
* This method can be called only by Service. You can use the StartAbility(ohos.aafwk.content.Want) method to start
* Service. Then the system calls back the current method to use the transferred want parameter to execute its own
* logic.
*
* @param want Indicates the want of Service to start.
* @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented by
* 1 every time the ability is started. For example, if the ability has been started for six times, the value of
* startId is 6.
*/
virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId);
/**
* @brief dump ability info
*
* @param extra dump ability info
*/
virtual void Dump(const std::string &extra);
/**
* @brief Keeps this Service ability in the background and displays a notification bar.
* To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission from the system.
* The ohos.permission.KEEP_BACKGROUND_RUNNING permission is of the normal level.
* This method can be called only by Service abilities after the onStart(ohos.aafwk.content.Want) method is called.
*
* @param id Identifies the notification bar information.
* @param notificationRequest Indicates the NotificationRequest instance containing information for displaying a
* notification bar.
*/
virtual void KeepBackgroundRunning(int id, const NotificationRequest &notificationRequest) final;
/**
* @brief Cancels background running of this ability to free up system memory.
* This method can be called only by Service abilities when the onStop() method is called.
*
*/
virtual void CancelBackgroundRunning() final;
/**
* @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
* across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if the
* context has changed. If you implement URI normalization for a Data ability, you must also implement
* denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
* any method that is called on the Data ability must require normalization verification and denormalization. The
* default implementation of this method returns null, indicating that this Data ability does not support URI
* normalization.
*
* @param uri Indicates the Uri object to normalize.
*
* @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
*/
virtual const std::shared_ptr<Uri> NormalizeUri(const Uri &uri);
/**
* @brief Deletes one or more data records. This method should be implemented by a Data ability.
*
* @param uri Indicates the database table storing the data to delete.
* @param predicates Indicates filter criteria. If this parameter is null, all data records will be deleted by
* default.
*
* @return Returns the number of data records deleted.
*/
virtual int Delete(const Uri &uri, const DataAbilityPredicates &predicates);
/**
* @brief Obtains the MIME type of files. This method should be implemented by a Data ability.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME type of the files to obtain. This parameter cannot be set to null.
* 1. * / *: Obtains all types supported by a Data ability.
* 2. image/ *: Obtains files whose main type is image of any subtype.
* 3. * /jpg: Obtains files whose subtype is JPG of any main type.
*
* @return Returns the MIME type of the matched files; returns null if there is no type that matches the Data
* ability.
*/
virtual std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file. This method should be implemented by a Data ability.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the FileDescriptor object of the file descriptor.
*/
virtual int OpenFile(const Uri &uri, const std::string &mode);
/**
* @brief Queries one or more data records in the database. This method should be implemented by a Data ability.
*
* @param uri Indicates the database table storing the data to query.
* @param columns Indicates the columns to be queried, in array, for example, {"name","age"}. You should define the
* processing logic when this parameter is null.
* @param predicates Indicates filter criteria. If this parameter is null, all data records will be queried by
* default.
*
* @return Returns the queried data.
*/
virtual std::shared_ptr<ResultSet> Query(
const Uri &uri, const std::vector<std::string> &columns, const DataAbilityPredicates &predicates);
/**
* @brief Sets the main route for this ability.
*
* The main route, also called main entry, refers to the default <b>AbilitySlice</b> to present for this ability.
* This function should be called only on Feature Abilities. If this function is not called in the
* {@link OnStart(const Want &want)} function for a Feature Ability, the Feature Ability will fail to start.
*
* @param entry Indicates the main entry, which is the class name of the <b>AbilitySlice</b> instance to start.
*
* @return Returns the result of SetMainRoute
*/
virtual void SetMainRoute(const std::string &entry) final;
/**
* @brief Migrates this ability to another device on the same distributed network in a reversible way that allows
* this ability to be migrated back to the local device through reverseContinueAbility(). If there are multiple
* candidate devices, a pop-up will be displayed for users to choose the desired one. The ability to migrate and its
* ability slices must implement the IAbilityContinuation interface. Otherwise, an exception is thrown, indicating
* that the ability does not support migration.
*
*/
virtual void ContinueAbilityReversibly() final;
/**
* @brief Migrates this ability to the given device on the same distributed network in a reversible way that allows
* this ability to be migrated back to the local device through reverseContinueAbility(). The ability to migrate and
* its ability slices must implement the IAbilityContinuation interface. Otherwise, an exception is thrown,
* indicating that the ability does not support migration.
*
* @param deviceId Indicates the ID of the target device where this ability will be migrated to. If this parameter
* is null, this method has the same effect as ContinueAbilityReversibly().
*
*/
virtual void ContinueAbilityReversibly(const std::string &deviceId) final;
/**
* @brief Obtains the ID of the source device from which this ability is migrated.
*
* @return Returns the source device ID.
*/
virtual std::string GetOriginalDeviceId() final;
/**
* @brief Obtains the migration state of this ability.
* @return Returns the migration state.
*/
virtual std::shared_ptr<ContinuationState> GetContinuationState() final;
/**
* @brief Migrates this ability from another device on the same distributed network back to the local device.
* @return Returns true if the migration request is successful; returns false otherwise.
*/
virtual bool ReverseContinueAbility() final;
/**
* @brief Obtains the singleton AbilityPackage object to which this ability belongs.
*
* @return Returns the singleton AbilityPackage object to which this ability belongs.
*/
virtual std::shared_ptr<AbilityPackage> GetAbilityPackage();
/**
* @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
* The default implementation of this method returns the original URI passed to it.
*
* @param uri uri Indicates the Uri object to denormalize.
*
* @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed
* to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found
* in the current environment.
*/
virtual std::shared_ptr<Uri> DenormalizeUri(const Uri &uri);
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
virtual bool Reload(const Uri &uri, const PacMap &extras);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
virtual int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values);
/**
* @brief Obtains the type of audio whose volume is adjusted by the volume button.
*
* @return Returns the AudioManager.AudioVolumeType.
*/
int GetVolumeTypeAdjustedByKey();
/**
* @brief Obtains the lifecycle state of this ability.
*
* @return Returns the lifecycle state of this ability.
*/
virtual AbilityLifecycleExecutor::LifecycleState GetState() final;
/**
* @brief A Page or Service ability uses this method to start a specific ability. The system locates the target
* ability from installed abilities based on the value of the intent parameter and then starts it. You can specify
* the ability to start using the intent parameter.
*
* @param intent Indicates the ability to start.
*/
using AbilityContext::StartAbility;
virtual void StartAbility(const Want &want) final;
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template.
*
* @param want Indicates the want containing information about the ability to connect
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure
*/
bool ConnectAbility(const Want &want, const sptr<AAFwk::IAbilityConnection> &conn) override;
/**
* @brief Disconnects the current ability from an ability
*
* @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
* is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
*/
void DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn) override;
/**
* @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template.
* The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE
* template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE
* template. The current ability itself can be destroyed by calling the terminateAbility() method.
*
* @param want Indicates the Want containing information about the ability to destroy.
*
* @return Returns true if the ability is destroyed successfully; returns false otherwise.
*/
bool StopAbility(const AAFwk::Want &want) override;
/**
* @brief Posts a scheduled Runnable task to a new non-UI thread.
* The task posted via this method will be executed in a new thread, which allows you to perform certain
* time-consuming operations. To use this method, you must also override the supportHighPerformanceUI() method.
* Additionally, the usage of this method must comply with the following constraints: 1、This method can only be
* used to initialize the component tree in parallel mode. 2、The task can only be processed during system cold
* start. 3、If the parallel loading mechanism is used, the component tree-related operations to be performed in
* onActive() and onStop() of the ability slice must also be added to the parallel thread. 4、You must run
* setUIContent(ohos.agp.components.ComponentContainer) to unlock the UI thread and wait until the component tree is
* ready. 5、Other time-consuming operations, such as I/O and network processing, cannot be added to the parallel
* task queue.
*
* @param task Indicates the Runnable task to post.
*
* @param delayTime Indicates the number of milliseconds after which the task will be executed.
*
* @return -
*/
void PostTask(std::function<void()> task, long delayTime);
private:
std::shared_ptr<AbilityInfo> abilityInfo_ = nullptr;
std::shared_ptr<Context> context_;
std::shared_ptr<AbilityHandler> handler_;
std::shared_ptr<LifeCycle> lifecycle_ = nullptr;
std::shared_ptr<AbilityLifecycleExecutor> abilityLifecycleExecutor_ = nullptr;
std::shared_ptr<OHOSApplication> application_;
std::vector<std::string> types_;
std::shared_ptr<AbilityWindow> abilityWindow_ = nullptr;
std::shared_ptr<AAFwk::Want> setWant_;
bool bWindowFocus_ = false;
static const std::string SYSTEM_UI;
static const std::string STATUS_BAR;
static const std::string NAVIGATION_BAR;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_H
+497
View File
@@ -0,0 +1,497 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTEXT_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTEXT_H
#include "context_container.h"
#include "data_ability_helper.h"
namespace OHOS {
namespace AppExecFwk {
class AbilityContext : public ContextContainer {
public:
AbilityContext() = default;
virtual ~AbilityContext() = default;
/**
* Attaches a Context object to the current ability.
* Generally, this method is called after Ability is loaded to provide the application context for the current
* ability.
*
* @param base Indicates a Context object.
*/
void AttachBaseContext(const std::shared_ptr<Context> &base);
/**
* @brief Obtains the absolute path to the application-specific cache directory
* on the primary external or shared storage device.
*
* @return Returns the absolute path to the application-specific cache directory on the external or
* shared storage device; returns null if the external or shared storage device is temporarily unavailable.
*/
std::string GetExternalCacheDir() override;
/**
* @brief Obtains the absolute path to the directory for storing files for the application on the
* primary external or shared storage device.
*
* @param type Indicates the type of the file directory to return
*
* @return Returns the absolute path to the application file directory on the external or shared storage
* device; returns null if the external or shared storage device is temporarily unavailable.
*/
std::string GetExternalFilesDir(std::string &type) override;
/**
* @brief Obtains the directory for storing files for the application on the device's internal storage.
*
* @return Returns the application file directory.
*/
std::string GetFilesDir() override;
/**
* @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage.
* The returned path maybe changed if the application is moved to an adopted storage device.
*
* @return The path of the directory holding application files that will not be automatically backed up to remote
* storage.
*/
std::string GetNoBackupFilesDir() override;
/**
* @brief Remove permissions for all users who have access to specific permissions
*
* @param permission Indicates the permission to unauth. This parameter cannot be null.
* @param uri Indicates the URI to unauth. This parameter cannot be null.
* @param uid Indicates the UID of the unauth to check.
*
*/
void UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) override;
/**
* @brief Obtains the distributed file path.
* If the distributed file path does not exist, the system creates one and returns the created path. This method is
* applicable only to the context of an ability rather than that of an application.
*
* @return Returns the distributed file.
*/
std::string GetDistributedDir() override;
/**
* @brief Sets the pattern of this Context based on the specified pattern ID.
*
* @param patternId Indicates the resource ID of the pattern to set.
*/
void SetPattern(int patternId) override;
/**
* @brief Obtains the Context object of this ability.
*
* @return Returns the Context object of this ability.
*/
std::shared_ptr<Context> GetAbilityPackageContext() override;
/**
* @brief Obtains the name of the current process.
*
* @return Returns the current process name.
*/
std::string GetProcessName() override;
/**
* @brief InitResourceManager
*
* @param bundleInfo BundleInfo
*/
void InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr<ContextDeal> &deal);
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method
* to start a specific ability. The system locates the target ability from installed abilities based on the value
* of the want parameter and then starts it. You can specify the ability to start using the want parameter.
*
* @param want Indicates the Want containing information about the target ability to start.
*
* @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE
* template is started. You can define the request code to identify the results returned by abilities. The value
* ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE
* template.
*
*/
using ContextContainer::StartAbility;
void StartAbility(const AAFwk::Want &Want, int requestCode) override;
/**
* @brief Starts a new ability with special ability start setting.
*
* @param want Indicates the Want containing information about the target ability to start.
* @param requestCode Indicates the request code returned after the ability is started. You can define the request
* code to identify the results returned by abilities. The value ranges from 0 to 65535.
* @param abilityStartSetting Indicates the special start setting used in starting ability.
*
*/
void StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) override;
/**
* @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult
* (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode
* passed.
*
* @param requestCode Indicates the request code passed for starting the ability.
*
*/
void TerminateAbility(int requestCode) override;
/**
* @brief Destroys the current ability.
*
*/
void TerminateAbility() override;
/**
* @brief Obtains the bundle name of the ability that called the current ability.
* You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will
* send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int,
* ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned.
*
* @return Returns the bundle name of the calling ability; returns null if no calling ability is available.
*/
std::string GetCallingBundle() override;
/**
* @brief Obtains the ohos.bundle.ElementName object of the current ability.
*
* @return Returns the ohos.bundle.ElementName object of the current ability.
*/
std::shared_ptr<ElementName> GetElementName();
/**
* @brief Obtains the ElementName of the ability that called the current ability.
*
* @return Returns the ElementName of the calling ability; returns null if no calling ability is available.
*/
std::shared_ptr<ElementName> GetCallingAbility();
/**
* @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template.
*
* @param want Indicates the want containing information about the ability to connect
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure
*/
bool ConnectAbility(const Want &want, const sptr<AAFwk::IAbilityConnection> &conn) override;
/**
* @brief Disconnects the current ability from an ability
*
* @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
* is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
*/
void DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn) override;
/**
* @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template.
* The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE
* template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE
* template. The current ability itself can be destroyed by calling the terminateAbility() method.
*
* @param want Indicates the Want containing information about the ability to destroy.
*
* @return Returns true if the ability is destroyed successfully; returns false otherwise.
*/
virtual bool StopAbility(const AAFwk::Want &want) override;
/**
* @brief Obtains information about the current application. The returned application information includes basic
* information such as the application name and application permissions.
*
* @return Returns the ApplicationInfo for the current application.
*/
std::shared_ptr<ApplicationInfo> GetApplicationInfo() const override;
/**
* @brief Obtains the application-specific cache directory on the device's internal storage. The system
* automatically deletes files from the cache directory if disk space is required elsewhere on the device.
* Older files are always deleted first.
*
* @return Returns the application-specific cache directory.
*/
std::string GetCacheDir() override;
/**
* @brief Obtains the application-specific code-cache directory on the device's internal storage.
* The system will delete any files stored in this location both when your specific application is upgraded,
* and when the entire platform is upgraded.
*
* @return Returns the application-specific code-cache directory.
*/
std::string GetCodeCacheDir() override;
/**
* @brief Obtains the local database path.
* If the local database path does not exist, the system creates one and returns the created path.
*
* @return Returns the local database file.
*/
std::string GetDatabaseDir() override;
/**
* @brief Obtains the absolute path where all private data files of this application are stored.
*
* @return Returns the absolute path storing all private data files of this application.
*/
std::string GetDataDir() override;
/**
* @brief Obtains the directory for storing custom data files of the application.
* You can use the returned File object to create and access files in this directory. The files
* can be accessible only by the current application.
*
* @param name Indicates the name of the directory to retrieve. This directory is created as part
* of your application data.
* @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE.
*
* @return Returns a File object for the requested directory.
*/
std::string GetDir(const std::string &name, int mode) override;
/**
* @brief Obtains an IBundleMgr instance.
* You can use this instance to obtain information about the application bundle.
*
* @return Returns an IBundleMgr instance.
*/
sptr<IBundleMgr> GetBundleManager() const override;
/**
* @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
* source code, and configuration files of a module.
*
* @return Returns the path of the package file.
*/
std::string GetBundleCodePath() override;
/**
* @brief Obtains the bundle name of the current ability.
*
* @return Returns the bundle name of the current ability.
*/
std::string GetBundleName() override;
/**
* @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability.
*
* @return Returns the path of the HAP containing this ability.
*/
std::string GetBundleResourcePath() override;
/**
* @brief Obtains the Context object of the application.
*
* @return Returns the Context object of the application.
*/
std::shared_ptr<Context> GetApplicationContext() const override;
/**
* @brief Obtains the Context object of the application.
*
* @return Returns the Context object of the application.
*/
std::shared_ptr<Context> GetContext() override;
/**
* @brief Obtains an ability manager.
* The ability manager provides information about running processes and memory usage of an application.
*
* @return Returns an IAbilityManager instance.
*/
sptr<AAFwk::IAbilityManager> GetAbilityManager() override;
/**
* Called when getting the ProcessInfo
*
* @return ProcessInfo
*/
std::shared_ptr<ProcessInfo> GetProcessInfo() const override;
/**
* @brief Obtains the type of this application.
*
* @return Returns system if this application is a system application;
* returns normal if it is released in official AppGallery;
* returns other if it is released by a third-party vendor;
* returns an empty string if the query fails.
*/
std::string GetAppType() override;
/**
* @brief Obtains information about the current ability.
* The returned information includes the class name, bundle name, and other information about the current ability.
*
* @return Returns the AbilityInfo object for the current ability.
*/
const std::shared_ptr<AbilityInfo> GetAbilityInfo() override;
/**
* @brief Obtains the HapModuleInfo object of the application.
*
* @return Returns the HapModuleInfo object of the application.
*/
std::shared_ptr<HapModuleInfo> GetHapModuleInfo() override;
/**
* @brief Creates a Context object for an application with the given bundle name.
*
* @param bundleName Indicates the bundle name of the application.
*
* @param flag Indicates the flag for creating a Context object. It can be 0, any of
* the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY,
* CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction
* on creating contexts for applications.
*
* @return Returns a Context object created for the specified application.
*/
std::shared_ptr<Context> CreateBundleContext(std::string bundleName, int flag);
/**
* @brief Obtains a resource manager.
*
* @return Returns a ResourceManager object.
*/
std::shared_ptr<Global::Resource::ResourceManager> GetResourceManager() const override;
/**
* @brief Checks whether the current process has the given permission.
* You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only
* if the current process does not have the specific permission.
*
* @param permission Indicates the permission to check. This parameter cannot be null.
*
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
virtual int VerifySelfPermission(const std::string &permission) override;
/**
* @brief Checks whether the calling process for inter-process communication has the given permission.
* The calling process is not the current process.
*
* @param permission Indicates the permission to check. This parameter cannot be null.
*
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
virtual int VerifyCallingPermission(const std::string &permission) override;
/**
* @brief Confirms with the permission management module to check whether a request prompt is required for granting
* a certain permission. You need to call the current method to check whether a prompt is required before calling
* requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required,
* permission request will not be initiated.
*
* @param requestCode Indicates the permission to be queried. This parameter cannot be null.
*
* @return Returns true if the current application does not have the permission and the user does not turn off
* further requests; returns false if the current application already has the permission, the permission is rejected
* by the system, or the permission is denied by the user and the user has turned off further requests.
*/
virtual bool CanRequestPermission(const std::string &permission) override;
/**
* @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has
* permission
*
* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
virtual int VerifyCallingOrSelfPermission(const std::string &permission) override;
/**
* @brief Query whether the application of the specified PID and UID has been granted a certain permission
*
* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
* @param pid Process id
* @param uid
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
virtual int VerifyPermission(const std::string &permission, int pid, int uid) override;
/**
* @brief Requests certain permissions from the system.
* This method is called for permission request. This is an asynchronous method. When it is executed,
* the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back.
*
* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
* @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int,
* String[], int[]) callback method. This code cannot be a negative number.
*/
virtual void RequestPermissionsFromUser(std::vector<std::string> &permissions, int requestCode) override;
/*
* @brief Deletes the specified private file associated with the application.
*
* @param fileName Indicates the name of the file to delete. The file name cannot contain path separators.
*
* @return Returns true if the file is deleted successfully; returns false otherwise.
*/
bool DeleteFile(const std::string &fileName) override;
/**
* @brief Set deviceId/bundleName/abilityName of the calling ability
*
* @param deviceId deviceId of the calling ability
*
* @param deviceId bundleName of the calling ability
*
* @param deviceId abilityName of the calling ability
*/
void SetCallingContext(const std::string &deviceId, const std::string &bundleName, const std::string &abilityName);
/**
* @brief Obtains information about the caller of this ability.
*
* @return Returns the caller information.
*/
Uri GetCaller() override;
friend DataAbilityHelper;
private:
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
AppExecFwk::AbilityType GetAbilityInfoType();
protected:
sptr<IRemoteObject> GetToken() override;
sptr<IRemoteObject> token_;
AAFwk::Want resultWant_;
int resultCode_ = -1;
std::string callingDeviceId_;
std::string callingBundleName_;
std::string callingAbilityName_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTEXT_H
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_EVENT_INTERFACE_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_EVENT_INTERFACE_H
namespace OHOS {
namespace AppExecFwk {
class IAbilityEvent {
public:
IAbilityEvent() = default;
virtual ~IAbilityEvent() = default;
/**
* @brief Called back when the Back key is pressed.
*
*/
virtual void OnBackPressed() = 0;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_EVENT_INTERFACE_H
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_ABILITY_HANDLER_H
#define FOUNDATION_APPEXECFWK_ABILITY_HANDLER_H
#include "ability_thread.h"
#include "event_handler.h"
#include "refbase.h"
namespace OHOS {
namespace AppExecFwk {
class AbilityThread;
class AbilityHandler : public EventHandler {
public:
AbilityHandler(const std::shared_ptr<EventRunner> &runner, const sptr<AbilityThread> &server);
~AbilityHandler() = default;
/**
* Process the event. Developers should override this method.
*
* @param event The event should be processed.
*/
void ProcessEvent(const InnerEvent::Pointer &event) override;
private:
sptr<AbilityThread> server_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_ABILITY_HANDLER_H
@@ -0,0 +1,357 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_IMPL_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_IMPL_H
#include "ability.h"
#include "ability_state.h"
#include "iability_lifecycle_callback.h"
#include "context.h"
#include "application_impl.h"
#include "ability_local_record.h"
#include "ability_handler.h"
#include "ability_manager_client.h"
#include "ability_manager_interface.h"
#include "touch_event.h"
#include "key_event.h"
#include "dummy_component_container.h"
#include "dummy_values_bucket.h"
#include "dummy_data_ability_predicates.h"
#include "dummy_result_set.h"
#include "key_event.h"
namespace OHOS {
namespace AppExecFwk {
class Ability;
class AbilityHandler;
class ApplicationImpl;
class AbilityLocalRecord;
class AbilityLifecycleCallbacks;
class OHOSApplication;
class AbilityImpl : public std::enable_shared_from_this<AbilityImpl> {
public:
AbilityImpl() = default;
virtual ~AbilityImpl() = default;
virtual void Init(std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &record,
std::shared_ptr<Ability> &ability, std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token,
std::shared_ptr<ContextDeal> &contextDeal);
/**
* @brief Connect the ability. and Calling information back to Ability.
*
* @param want The Want object to connect to.
*
*/
sptr<IRemoteObject> ConnectAbility(const Want &want);
/**
* @brief Disconnects the connected object.
*
* @param want The Want object to disconnect to.
*/
void DisconnectAbility(const Want &want);
/**
* @brief Command the ability. and Calling information back to Ability.
*
* @param want The Want object to command to.
*
* * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
*
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented
* by 1 every time the ability is started. For example, if the ability has been started for six times, the value
* of startId is 6.
*/
void CommandAbility(const Want &want, bool restart, int startId);
/**
* @brief Gets the current Ability status.
*
*/
int GetCurrentState();
/**
* @brief Save data and states of an ability when it is restored by the system. and Calling information back to
* Ability. This method should be implemented by a Page ability.
* @param instate The Want object to connect to.
*
*/
void DispatchSaveAbilityState(PacMap &outState);
/**
* @brief Restores data and states of an ability when it is restored by the system. and Calling information back
* to Ability. This method should be implemented by a Page ability.
* @param instate The Want object to connect to.
*
*/
void DispatchRestoreAbilityState(const PacMap &inState);
// Page Service Ability has different AbilityTransaction
virtual void HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState);
/**
* @brief Execution the KeyDown callback of the ability
* @param keyCode Indicates the code of the key pressed.
* @param keyEvent Indicates the key-down event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
virtual bool DoKeyDown(int keyCode, const KeyEvent &keyEvent);
/**
* @brief Execution the KeyUp callback of the ability
* @param keyCode Indicates the code of the key released.
* @param keyEvent Indicates the key-up event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
virtual bool DoKeyUp(int keyCode, const KeyEvent &keyEvent);
/**
* @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
* does nothing and returns false.
* @param touchEvent Indicates information about the touch event.
*
* @return Returns true if the event is handled; returns false otherwise.
*
*/
virtual bool DoTouchEvent(const TouchEvent &touchEvent);
/**
* @brief Send the result code and data to be returned by this Page ability to the caller.
* When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want)
* method to receive the result set in the current method. This method can be called only after the ability has
* been initialized.
*
* @param requestCode Indicates the request code.
* @param resultCode Indicates the result code returned after the ability is destroyed. You can define the
* result code to identify an error.
* @param resultData Indicates the data returned after the ability is destroyed. You can define the data
* returned. This parameter can be null.
*/
void SendResult(int requestCode, int resultCode, /*const AAFwk::Want& resultData*/ const Want &resultData);
/**
* @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch
* an ability that has been at the top of the ability stack.
*
* @param want Indicates the new Want containing information about the ability.
*/
void NewWant(const Want &want);
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
virtual std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
virtual int OpenFile(const Uri &uri, const std::string &mode);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
virtual int OpenRawFile(const Uri &uri, const std::string &mode);
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
virtual int Insert(const Uri &uri, const ValuesBucket &value);
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is
* null.
*
* @return Returns the number of data records updated.
*/
virtual int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is
* null.
*
* @return Returns the number of data records deleted.
*/
virtual int Delete(const Uri &uri, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is
* null.
*
* @return Returns the query result.
*/
virtual std::shared_ptr<ResultSet> Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates);
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should
* be implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
virtual std::string GetType(const Uri &uri);
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call.
* This parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be
* transferred across processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for
* the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
virtual bool Reload(const Uri &uri, const PacMap &extras);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
virtual int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values);
/**
* @brief Set deviceId/bundleName/abilityName of the calling ability
*
* @param deviceId deviceId of the calling ability
*
* @param deviceId bundleName of the calling ability
*
* @param deviceId abilityName of the calling ability
*/
void SetCallingContext(const std::string &deviceId, const std::string &bundleName, const std::string &abilityName);
protected:
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
* @param want The Want object to switch the life cycle.
*/
void Start(const Want &want);
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INITIAL. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void Stop();
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_ACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void Active();
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void Inactive();
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
* @param want The Want object to switch the life cycle.
*/
void Foreground(const Want &want);
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the
* application that it belongs to of the lifecycle status.
*
*/
void Background();
/**
* @brief SerUriString
*/
void SerUriString(const std::string &uri);
int lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL;
sptr<IRemoteObject> token_;
std::shared_ptr<Ability> ability_;
private:
typedef enum {
START,
INACTIVE,
ACTIVE,
BACKGROUND,
FOREGROUND,
STOP,
} Action;
std::shared_ptr<AbilityLifecycleCallbacks> abilityLifecycleCallbacks_;
std::shared_ptr<ApplicationImpl> applactionImpl_;
std::shared_ptr<ContextDeal> contextDeal_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_IMPL_H
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_IMPL_FACTORY_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_IMPL_FACTORY_H
#include "ability_impl.h"
#include "singleton.h"
namespace OHOS {
namespace AppExecFwk {
class AbilityImplFactory {
DECLARE_DELAYED_SINGLETON(AbilityImplFactory)
public:
/**
* @brief Create impl object based on abilitytype
*
* @param type AbilityType:PAGE/SERVICE/PROVIDER
*
* @return AbilityImpl object
*/
std::shared_ptr<AbilityImpl> MakeAbilityImplObject(const std::shared_ptr<AbilityInfo> &info);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_IMPL_FACTORY_H
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_H
#include <vector>
#include <string>
#include <list>
#include <refbase.h>
#include <memory>
#include "want.h"
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class ILifecycleObserver;
class LifeCycle {
public:
LifeCycle() = default;
virtual ~LifeCycle() = default;
enum Event { ON_ACTIVE, ON_BACKGROUND, ON_FOREGROUND, ON_INACTIVE, ON_START, ON_STOP, UNDEFINED };
/**
* @brief Obtains the current lifecycle event.
* Lifecycle events drive lifecycle state changes. Therefore, you are able to know the lifecycle state
* once you obtain the lifecycle event. For example, if the ON_ACTIVE event is received, the ability or
* ability slice is in the ACTIVE state; if the ON_FOREGROUND event is received, the ability or ability
* slice is changing from the BACKGROUND state to INACTIVE.
*
* @return Returns the current lifecycle event.
*/
LifeCycle::Event GetLifecycleState();
/**
* @brief Adds a lifecycle observer.
* The observer will be notified of lifecycle changes.
*
* @param observer Indicates the lifecycle observer, either LifecycleObserver or LifecycleStateObserver.
* The value cannot be null.
*
*/
void AddObserver(const std::shared_ptr<ILifecycleObserver> &observer);
/**
* @brief While Ability's lifecycle changes, dispatch lifecycle event.
*
* @param event Lifecycle state.
* @param want Indicates the Want containing information about the target ability to change lifecycle state.
*/
void DispatchLifecycle(const LifeCycle::Event &event, const Want &want);
/**
* @brief While Ability's lifecycle changes, dispatch lifecycle event.
*
* @param event Lifecycle state.
* @param want Indicates the Want containing information about the target ability to change lifecycle state.
*/
void DispatchLifecycle(const LifeCycle::Event &event);
/**
* @brief Removes a lifecycle observer.
* You are advised to call this method if you no longer need to listen to lifecycle changes. This reduces the
* performance loss caused by observing lifecycle changes.
*
* @param observer Indicates the lifecycle observer, either LifecycleObserver or LifecycleStateObserver.
* The value cannot be null.
*/
void RemoveObserver(const std::shared_ptr<ILifecycleObserver> &observer);
private:
LifeCycle::Event state_ = UNDEFINED;
std::list<std::shared_ptr<ILifecycleObserver>> callbacks_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_H
@@ -0,0 +1,87 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_CALLBACK_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_CALLBACK_H
#include "pac_map.h"
namespace OHOS {
namespace AppExecFwk {
class Ability;
class AbilityLifecycleCallbacks {
public:
AbilityLifecycleCallbacks() = default;
virtual ~AbilityLifecycleCallbacks() = default;
/**
*
* Will be called when the given ability calls Ability->onStart
*
* @param Ability Indicates the ability object that calls the onStart() method.
*/
virtual void OnAbilityStart(const std::shared_ptr<Ability> &ability) = 0;
/**
*
* Will be called when the given ability calls Ability->onInactive
*
* @param Ability Indicates the Ability object that calls the onInactive() method.
*/
virtual void OnAbilityInactive(const std::shared_ptr<Ability> &ability) = 0;
/**
*
* Will be called when the given ability calls Ability->onBackground
*
* @param Ability Indicates the Ability object that calls the onBackground() method.
*/
virtual void OnAbilityBackground(const std::shared_ptr<Ability> &ability) = 0;
/**
*
* Will be called when the given ability calls Ability->onForeground
*
* @param Ability Indicates the Ability object that calls the onForeground() method.
*/
virtual void OnAbilityForeground(const std::shared_ptr<Ability> &ability) = 0;
/**
*
* Will be called when the given ability calls Ability->onActive
*
* @param Ability Indicates the Ability object that calls the onActive() method.
*/
virtual void OnAbilityActive(const std::shared_ptr<Ability> &ability) = 0;
/**
*
* Will be called when the given ability calls Ability->onStop
*
* @param Ability Indicates the Ability object that calls the onStop() method.
*/
virtual void OnAbilityStop(const std::shared_ptr<Ability> &ability) = 0;
/**
*
* Will be Called when an ability calls Ability#onSaveAbilityState(PacMap).
*
* @param outState Indicates the PacMap object passed to the onSaveAbilityState() callback.
*/
virtual void OnAbilitySaveState(const PacMap &outState) = 0;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_CALLBACK_H
@@ -0,0 +1,54 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_EXECUTOR_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_EXECUTOR_H
namespace OHOS {
namespace AppExecFwk {
class AbilityLifecycleExecutor {
public:
AbilityLifecycleExecutor() = default;
virtual ~AbilityLifecycleExecutor() = default;
enum LifecycleState {
ACTIVE,
BACKGROUND,
INACTIVE,
INITIAL,
UNINITIALIZED,
};
/**
* @brief While Ability's lifecycle changes, dispatch lifecycle state.
*
* @param state Lifecycle state.
*/
void DispatchLifecycleState(const AbilityLifecycleExecutor::LifecycleState &state);
/**
* @brief Obtains the int value of the ability lifecycle state represented by the
* AbilityLifecycleExecutor.LifecycleState enum constant.
*
* @return return Returns the int value of the ability lifecycle state represented
* by the AbilityLifecycleExecutor.LifecycleState enum constant.
*/
int GetState();
private:
AbilityLifecycleExecutor::LifecycleState state_ = UNINITIALIZED;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_EXECUTOR_H
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_INTERFACE_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_INTERFACE_H
#include "ability_lifecycle.h"
namespace OHOS {
namespace AppExecFwk {
class ILifeCycle {
public:
ILifeCycle() = default;
virtual ~ILifeCycle() = default;
/**
* @brief Obtains the Lifecycle object of an Ability
*
* @return Returns the Lifecycle object.
*/
virtual std::shared_ptr<LifeCycle> GetLifecycle() = 0;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_LIFECYCLE_INTERFACE_H
@@ -0,0 +1,100 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_LIFECYCLE_OBSERVER_INTERFACE_H
#define FOUNDATION_APPEXECFWK_OHOS_LIFECYCLE_OBSERVER_INTERFACE_H
#include "ability_lifecycle_observer_interface.h"
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class LifecycleObserver : public ILifecycleObserver {
public:
LifecycleObserver() = default;
virtual ~LifecycleObserver() = default;
/**
* @brief Called back in response to an ON_ACTIVE event.
* When an ON_ACTIVE event is received, the ability or ability slice is in the foreground and is interactive.
*/
virtual void OnActive();
/**
* @brief Called back in response to an ON_BACKGROUND event.
* When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to
* suspend the threads related to this ability or ability slice and clear resources for more system memory.
*
*/
virtual void OnBackground();
/**
* @brief Called back in response to an ON_FOREGROUND event, where information for the
* ability or ability slice to go back to the ACTIVE state is carried in the want parameter.
* When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use
* this method to implement re-initialization or adjust the UI display by using the want parameter.
*
* @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state.
*/
virtual void OnForeground(const Want &want);
/**
* @brief Called back in response to an ON_INACTIVE event.
* When an ON_INACTIVE event is received, the ability or ability slice is in the INACTIVE state. INACTIVE is an
* intermediate state before the state changes to ACTIVE or BACKGROUND. In this state, the UI may be visible but is
* not interactive. You are advised not to use this method to invoke complex service logic.
*
*/
virtual void OnInactive();
/**
* @brief Called back in response to an ON_START event, where the startup information
* is carried in the want parameter.
* This method initializes an Ability or AbilitySlice and is called back only once during the entire lifecycle.
* You are advised to implement some initialization logic using this method, for example, you can initialize a
* timer or define some global objects.
*
* @param want Indicates the startup information.
*/
virtual void OnStart(const Want &want);
/**
* @brief Called back in response to an ON_STOP event.
* This method is called back when the lifecycle of the ability or ability slice is destroyed. You can reclaim
* resources using this method.
*
*/
virtual void OnStop();
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
* @param want Indicates the state change information.
*/
virtual void OnStateChanged(Lifecycle::Event event, const Want &want);
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
*/
virtual void OnStateChanged(LifeCycle::Event event);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_LIFECYCLE_OBSERVER_INTERFACE_H
@@ -0,0 +1,101 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_LIFECYCLE_OBSERVER_INTERFACE_H
#define FOUNDATION_APPEXECFWK_OHOS_LIFECYCLE_OBSERVER_INTERFACE_H
#include "want.h"
#include "ability_lifecycle.h"
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class ILifecycleObserver {
public:
ILifecycleObserver() = default;
virtual ~ILifecycleObserver() = default;
/**
* @brief Called back in response to an ON_ACTIVE event.
* When an ON_ACTIVE event is received, the ability or ability slice is in the foreground and is interactive.
*/
virtual void OnActive() = 0;
/**
* @brief Called back in response to an ON_BACKGROUND event.
* When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to
* suspend the threads related to this ability or ability slice and clear resources for more system memory.
*
*/
virtual void OnBackground() = 0;
/**
* @brief Called back in response to an ON_FOREGROUND event, where information for the
* ability or ability slice to go back to the ACTIVE state is carried in the want parameter.
* When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use
* this method to implement re-initialization or adjust the UI display by using the want parameter.
*
* @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state.
*/
virtual void OnForeground(const Want &want) = 0;
/**
* @brief Called back in response to an ON_INACTIVE event.
* When an ON_INACTIVE event is received, the ability or ability slice is in the INACTIVE state. INACTIVE is an
* intermediate state before the state changes to ACTIVE or BACKGROUND. In this state, the UI may be visible but is
* not interactive. You are advised not to use this method to invoke complex service logic.
*
*/
virtual void OnInactive() = 0;
/**
* @brief Called back in response to an ON_START event, where the startup information
* is carried in the want parameter.
* This method initializes an Ability or AbilitySlice and is called back only once during the entire lifecycle.
* You are advised to implement some initialization logic using this method, for example, you can initialize a
* timer or define some global objects.
*
* @param want Indicates the startup information.
*/
virtual void OnStart(const Want &want) = 0;
/**
* @brief Called back in response to an ON_STOP event.
* This method is called back when the lifecycle of the ability or ability slice is destroyed. You can reclaim
* resources using this method.
*
*/
virtual void OnStop() = 0;
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
* @param want Indicates the state change information.
*/
virtual void OnStateChanged(LifeCycle::Event event, const Want &want) = 0;
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
*/
virtual void OnStateChanged(LifeCycle::Event event) = 0;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_LIFECYCLE_OBSERVER_INTERFACE_H
@@ -0,0 +1,112 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_LOADER_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_LOADER_H
#include "ability.h"
#include "ohos_application.h"
#include <functional>
#include <string>
#include <unordered_map>
namespace OHOS {
namespace AppExecFwk {
using CreateAblity = std::function<Ability *(void)>;
#ifdef ABILITY_WINDOW_SUPPORT
using CreateSlice = std::function<AbilitySlice *(void)>;
#endif
/**
* @brief Declares functions for registering the class names of {@link Ability} and {@link AbilitySlice} with the
* ability management framework.
*
* After creating your own {@link Ability} and {@link AbilitySlice} child classes, you should register their class
* names with the ability management framework so that the application can start <b>Ability</b> instances created in
* the background.
*
* @since 1
* @version 1
*/
class AbilityLoader {
public:
static AbilityLoader &GetInstance();
~AbilityLoader() = default;
/**
* @brief Register Ability Info
*
* @param abilityName ability classname
* @param createFunc Constructor address
*/
void RegisterAbility(const std::string &abilityName, const CreateAblity &createFunc);
/**
* @brief Get Ability address
*
* @param abilityName ability classname
*
* @return return Ability address
*/
Ability *GetAbilityByName(const std::string &abilityName);
#ifdef ABILITY_WINDOW_SUPPORT
void RegisterAbilitySlice(const std::string &sliceName, const CreateSlice &createFunc);
AbilitySlice *GetAbilitySliceByName(const std::string &sliceName);
#endif
private:
AbilityLoader() = default;
AbilityLoader(const AbilityLoader &) = delete;
AbilityLoader &operator=(const AbilityLoader &) = delete;
AbilityLoader(AbilityLoader &&) = delete;
AbilityLoader &operator=(AbilityLoader &&) = delete;
std::unordered_map<std::string, CreateAblity> abilities_;
};
/**
* @brief Registers the class name of an {@link Ability} child class.
*
* After implementing your own {@link Ability} class, you should call this function so that the ability management
* framework can create <b>Ability</b> instances when loading your <b>Ability</b> class.
*
* @param className Indicates the {@link Ability} class name to register.
*/
#define REGISTER_AA(className) \
__attribute__((constructor)) void RegisterAA##className() \
{ \
AbilityLoader::GetInstance().RegisterAbility( \
#className, []() -> Ability * { return new (std::nothrow) className; }); \
}
/**
* @brief Registers the class name of an {@link AbilitySlice} child class.
*
* After implementing your own {@link AbilitySlice} class, you should call this function so that the ability
* management framework can create <b>AbilitySlice</b> instances when loading your <b>AbilitySlice</b> class.
*
* @param className Indicates the {@link AbilitySlice} class name to register.
*/
#ifdef ABILITY_WINDOW_SUPPORT
#define REGISTER_AS(className) \
__attribute((constructor)) void RegisterAS##className() \
{ \
AbilityLoader::GetInstance().RegisterAbilitySlice( \
#className, []() -> AbilitySlice * { return new (std::nothrow) className; });
}
#endif
} // namespace OHOS
} // OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_LOADER_H
@@ -0,0 +1,124 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_ABILITY_ITEM_H
#define FOUNDATION_APPEXECFWK_ABILITY_ITEM_H
#include <string>
#include "iremote_object.h"
#include "event_runner.h"
#include "ability_info.h"
#include "application_info.h"
#include "refbase.h"
namespace OHOS {
namespace AppExecFwk {
class AbilityThread;
class AbilityImpl;
class AbilityLocalRecord {
public:
/**
*
* default constructor
*
*/
AbilityLocalRecord(const std::shared_ptr<AbilityInfo> &info, const sptr<IRemoteObject> &token);
/**
*
* @default Destructor
*
*/
virtual ~AbilityLocalRecord();
/**
* @description: Get an AbilityInfo in an ability.
*
* @return Returns a pointer to abilityinfo.
*/
const std::shared_ptr<AbilityInfo> &GetAbilityInfo();
/**
* @description: Get an EventHandler in an ability.
*
* @return Returns a pointer to EventHandler
*/
const std::shared_ptr<EventHandler> &GetEventHandler();
/**
* @description: Set an EventHandler in an ability.
* @param handler EventHandler object
* @return None.
*/
void SetEventHandler(const std::shared_ptr<EventHandler> &handler);
/**
* @description: Get an EventRunner in an ability.
*
* @return Returns a pointer to EventRunner
*/
const std::shared_ptr<EventRunner> &GetEventRunner();
/**
* @description: Set an EventRunner in an ability.
* @param runner EventHandler object
* @return None.
*/
void SetEventRunner(const std::shared_ptr<EventRunner> &runner);
/**
* @description: Gets the identity of the ability
* @return return the identity of the ability.
*/
const sptr<IRemoteObject> &GetToken();
/**
* @description: Get an AbilityImpl in an ability.
*
* @return Returns AbilityImpl pointer
*/
const std::shared_ptr<AbilityImpl> &GetAbilityImpl();
/**
* @description: Set an AbilityImpl in an ability.
* @param abilityImpl AbilityImpl object
* @return None.
*/
void SetAbilityImpl(const std::shared_ptr<AbilityImpl> &abilityImpl);
/**
* @description: Obtains the information based on ability thread.
* @return return AbilityThread Pointer
*/
const sptr<AbilityThread> &GetAbilityThread();
/**
* @description: Set an AbilityThread in an ability.
* @param abilityThread AbilityThread object
* @return None.
*/
void SetAbilityThread(const sptr<AbilityThread> &abilityThread);
private:
std::shared_ptr<AbilityInfo> abilityInfo_;
sptr<IRemoteObject> token_;
std::shared_ptr<EventRunner> runner_;
std::shared_ptr<EventHandler> handler_;
std::shared_ptr<AbilityImpl> abilityImpl_; // store abilityImpl
sptr<AbilityThread> abilityThread_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_ABILITY_ITEM_H
+50
View File
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_PROCESS_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_PROCESS_H
#include <mutex>
#include "feature_ability.h"
#include "napi_context.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @class AbilityProcess
* Provides the feature ability function.
*/
class AbilityProcess {
public:
AbilityProcess();
virtual ~AbilityProcess();
static std::shared_ptr<AbilityProcess> GetInstance();
void StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callbackInfo);
void OnAbilityResult(Ability *ability, int requestCode, int resultCode, const Want &resultData);
void RequestPermissionsFromUser(Ability *ability, CallAbilityPermissionParam &param, CallbackInfo callbackInfo);
void OnRequestPermissionsFromUserResult(Ability *ability, int requestCode,
const std::vector<std::string> &permissions, const std::vector<int> &grantResults);
private:
static std::mutex mutex_;
static std::shared_ptr<AbilityProcess> instance_;
static std::map<Ability *, std::map<int, CallbackInfo>> abilityResultMap_;
static std::map<Ability *, std::map<int, CallbackInfo>> abilityRequestPermissionsForUserMap_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_PROCESS_H
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2021 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.
*/
/**
* @addtogroup AbilityKit
* @{
*
* @brief Provides ability-related functions, including ability lifecycle callbacks and functions for connecting to
* or disconnecting from AAs.
*
* Abilities are classified into Feature Abilities (FAs) and Atomic Abilities (AAs). FAs support the Page template,
* and AAs support the Service template. An ability using the Page template is called Page ability for short and that
* using the Service template is called Service ability.
*
* @since 1
* @version 1
*/
/**
* @file ability_state.h
*
* @brief Declares ability-related functions, including ability lifecycle callbacks and functions for connecting to
* or disconnecting from AAs.
* As the fundamental unit of OpenHarmony, abilities are classified into Feature Abilities (FAs) and Atomic
* Abilities (AAs). FAs support the Page template, and AAs support the Service template. An ability using the Page
* template is called Page ability for short and that using the Service template is called Service ability.
*
* @since 1
* @version 1
*/
#ifndef OHOS_ABILITY_STATE_H
#define OHOS_ABILITY_STATE_H
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */
/**
* @brief Enumerates all lifecycle states that an ability will go through over the course of its lifetime.
*
* @since 1
* @version 1
*/
typedef enum {
/**
* Initial state: An ability is in this state after it is initialized or stopped.
*/
STATE_INITIAL,
/**
* Inactive state: An ability is in this state when it is switched to the foreground but is not interactive.
*/
STATE_INACTIVE,
/**
* Active state: An ability is in this state when it is switched to the foreground and is interactive.
*/
STATE_ACTIVE,
/**
* Background state: An ability is in this state after it returns to the background.
*/
STATE_BACKGROUND,
STATE_SUSPENDED,
STATE_INACTIVATING,
STATE_ACTIVATING,
STATE_MOVING_BACKGROUND,
STATE_TERMINATING,
} State;
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif // OHOS_ABILITY_STATE_H
@@ -0,0 +1,334 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_ABILITY_THREAD_H
#define FOUNDATION_APPEXECFWK_ABILITY_THREAD_H
#include "want.h"
#include "ability_manager_client.h"
#include "ability_manager_interface.h"
#include "ability_impl.h"
#include "ability.h"
#include "ability_local_record.h"
#include "context.h"
#include "ohos_application.h"
#include "ability_scheduler_stub.h"
#include "pac_map.h"
#include "ohos/aafwk/base/ipc_singleton.h"
#include "dummy_values_bucket.h"
#include "dummy_data_ability_predicates.h"
#include "dummy_result_set.h"
namespace OHOS {
namespace AppExecFwk {
using AbilitySchedulerStub = OHOS::AAFwk::AbilitySchedulerStub;
using LifeCycleStateInfo = OHOS::AAFwk::LifeCycleStateInfo;
class AbilityImpl;
class Ability;
class AbilityHandler;
class AbilityLocalRecord;
class ApplicationImpl;
class OHOSApplication;
class AbilityHandler;
class AbilityThread : public AbilitySchedulerStub {
public:
/**
* @brief Default constructor used to create a AbilityThread instance.
*/
AbilityThread();
~AbilityThread();
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
* @param mainRunner The runner which main_thread holds.
*/
static void AbilityThreadMain(std::shared_ptr<OHOSApplication> &application,
const std::shared_ptr<AbilityLocalRecord> &abilityRecord, const std::shared_ptr<EventRunner> &mainRunner);
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
*/
static void AbilityThreadMain(
std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &abilityRecord);
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
* @param mainRunner The runner which main_thread holds.
*/
void Attach(std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &abilityRecord,
const std::shared_ptr<EventRunner> &mainRunner);
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
*/
void Attach(
std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &abilityRecord);
/**
* @description: Provide operating system AbilityTransaction information to the observer
* @param want Indicates the structure containing Transaction information about the ability.
* @param lifeCycleStateInfo Indicates the lifecycle state.
*/
void ScheduleAbilityTransaction(const Want &want, const LifeCycleStateInfo &targetState);
/**
* @description: Provide operating system ConnectAbility information to the observer
* @param want Indicates the structure containing connect information about the ability.
*/
void ScheduleConnectAbility(const Want &want);
/**
* @description: Provide operating system ConnectAbility information to the observer
* @return None
*/
void ScheduleDisconnectAbility(const Want &want);
/**
* @description: Provide operating system CommandAbility information to the observer
*
* @param want The Want object to command to.
*
* * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
*
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented by
* 1 every time the ability is started. For example, if the ability has been started for six times, the value of
* startId is 6.
*/
void ScheduleCommandAbility(const Want &want, bool restart, int startId);
/**
* @description: Provide operating system SaveabilityState information to the observer
* @param state Indicates save ability state used to dispatch.
*/
void ScheduleSaveAbilityState(PacMap &state);
/**
* @description: Provide operating system RestoreAbilityState information to the observer
* @param state Indicates resotre ability state used to dispatchRestoreAbilityState.
*/
void ScheduleRestoreAbilityState(const PacMap &state);
/**
* @brief Send the result code and data to be returned by this Page ability to the caller.
* When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to
* receive the result set in the current method. This method can be called only after the ability has been
* initialized.
*
* @param requestCode Indicates the request code for send.
* @param resultCode Indicates the result code returned after the ability is destroyed. You can define the result
* code to identify an error.
* @param want Indicates the data returned after the ability is destroyed. You can define the data returned. This
* parameter can be null.
*/
void SendResult(int requestCode, int resultCode, const Want &resultData);
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int OpenFile(const Uri &uri, const std::string &mode);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int OpenRawFile(const Uri &uri, const std::string &mode);
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int Insert(const Uri &uri, const ValuesBucket &value);
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int Delete(const Uri &uri, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates);
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string GetType(const Uri &uri);
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool Reload(const Uri &uri, const PacMap &extras);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values);
private:
/**
* @description: Create the abilityname.
*
* @param abilityRecord Indicates the abilityRecord.
*
* @return Returns the abilityname.
*
*/
std::string CreateAbilityName(const std::shared_ptr<AbilityLocalRecord> &abilityRecord);
/**
* @description: Create and init contextDeal.
*
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
* @param abilityObject Indicates the abilityObject.
*
* @return Returns the contextDeal.
*
*/
std::shared_ptr<ContextDeal> CreateAndInitContextDeal(std::shared_ptr<OHOSApplication> &application,
const std::shared_ptr<AbilityLocalRecord> &abilityRecord, const std::shared_ptr<Context> &abilityObject);
/**
* @description: Handle the life cycle of Ability.
* @param want Indicates the structure containing lifecycle information about the ability.
* @param lifeCycleStateInfo Indicates the lifeCycleStateInfo.
*/
void HandleAbilityTransaction(const Want &want, const LifeCycleStateInfo &lifeCycleStateInfo);
/**
* @description: Handle the current connection of Ability.
* @param want Indicates the structure containing connection information about the ability.
*/
void HandleConnectAbility(const Want &want);
/**
* @description: Handle the current disconnection of Ability.
*/
void HandleDisconnectAbility(const Want &want);
/**
* @brief Handle the current commadn of Ability.
*
* @param want The Want object to command to.
*
* * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
*
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented by
* 1 every time the ability is started. For example, if the ability has been started for six times, the value of
* startId is 6.
*/
void HandleCommandAbility(const Want &want, bool restart, int startId);
/**
* @description: Handle the SaveAbility state.
* @param state Indicates save ability state used to dispatchSaveAbilityState.
*/
void HandleSaveAbilityState(PacMap &state);
/**
* @description: Handle the restoreAbility state.
* @param state Indicates save ability state used to dispatchRestoreAbilityState.
*/
void HandleRestoreAbilityState(const PacMap &state);
std::shared_ptr<AbilityImpl> abilityImpl_ = nullptr;
sptr<IRemoteObject> token_;
std::shared_ptr<Ability> currentAbility_ = nullptr;
std::shared_ptr<AbilityHandler> abilityHandler_ = nullptr;
std::shared_ptr<EventRunner> runner_ = nullptr;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_ABILITY_THREAD_H
@@ -0,0 +1,126 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef OHOS_ABILITY_WINDOW_H
#define OHOS_ABILITY_WINDOW_H
#define WMS_COMPILE
#ifdef WMS_COMPILE
#include "window_manager.h"
#endif // WMS_COMPILE
#include <map>
#include "nocopyable.h"
namespace OHOS {
namespace AppExecFwk {
class IAbilityEvent;
class Ability;
class AbilityHandler;
class AbilityWindow : public NoCopyable {
public:
AbilityWindow();
virtual ~AbilityWindow();
#ifdef WMS_COMPILE
/**
* @brief Init the AbilityWindow object.
*
* @param handler The EventHandler of the Ability the AbilityWindow belong.
*/
void Init(std::shared_ptr<AbilityHandler> &handler, std::shared_ptr<Ability> ability);
/**
* @brief Sets the window config for the host ability to create window.
*
* @param config Indicates window config.
*/
bool SetWindowConfig(const WindowConfig &config);
/**
* @brief Called when the KeyEvent sent.
*
* @param KeyEvent the key event.
*
* @return Returns true if the listener has processed the event; returns false otherwise.
*
*/
bool OnKeyEvent(KeyEvent event);
/**
* @brief Called back when the Back key is pressed.
*
* @param ability The ability receive the event.
*
* @return Returns true if the listener has processed the event; returns false otherwise.
*
*/
bool OnBackPressed(std::shared_ptr<IAbilityEvent> &ability);
#endif // WMS_COMPILE
/**
* @brief Called when this ability is started.
*
*/
void OnPostAbilityStart();
/**
* @brief Called when this ability is activated.
*
*/
void OnPostAbilityActive();
/**
* @brief Called when this ability is inactivated.
*
*/
void OnPostAbilityInactive();
/**
* @brief Called when this ability is background.
*
*/
void OnPostAbilityBackground();
/**
* @brief Called when this ability is foreground.
*
*/
void OnPostAbilityForeground();
/**
* @brief Called when this ability is stopped.
*
*/
void OnPostAbilityStop();
/**
* @brief Get the window belong to the ability.
*
* @return Returns a Window object pointer.
*/
#ifdef WMS_COMPILE
const std::unique_ptr<Window> &GetWindow();
#endif // WMS_COMPILE
private:
#ifdef WMS_COMPILE
std::shared_ptr<AbilityHandler> handler_ = nullptr;
std::weak_ptr<IAbilityEvent> ability_;
std::unique_ptr<Window> window_;
#endif // WMS_COMPILE
bool isWindowAttached = false;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // OHOS_ABILITY_WINDOW_H
@@ -0,0 +1,202 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_HELPER_H
#define FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_HELPER_H
#include "context.h"
#include "dummy_values_bucket.h"
#include "dummy_data_ability_predicates.h"
#include "dummy_result_set.h"
#include "uri.h"
using Uri = OHOS::Uri;
namespace OHOS {
namespace AppExecFwk {
using string = std::string;
class PacMap;
class DataAbilityHelper final : public std::enable_shared_from_this<DataAbilityHelper> {
public:
~DataAbilityHelper() = default;
/**
* @brief Creates a DataAbilityHelper instance without specifying the Uri based on the given Context.
*
* @param context Indicates the Context object on OHOS.
*
* @return Returns the created DataAbilityHelper instance where Uri is not specified.
*/
static std::shared_ptr<DataAbilityHelper> Creator(const std::shared_ptr<Context> &context);
/**
* @brief Creates a DataAbilityHelper instance with the Uri specified based on the given Context.
*
* @param context Indicates the Context object on OHOS.
* @param uri Indicates the database table or disk file to operate.
*
* @return Returns the created DataAbilityHelper instance with a specified Uri.
*/
static std::shared_ptr<DataAbilityHelper> Creator(
const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri);
/**
* @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
* between the ability using the Data template (Data ability for short) and the associated client process in
* a DataAbilityHelper instance.
*
* @param context Indicates the Context object on OHOS.
* @param uri Indicates the database table or disk file to operate.
* @param tryBind Specifies whether the exit of the corresponding Data ability process causes the exit of the
* client process.
*
* @return Returns the created DataAbilityHelper instance.
*/
static std::shared_ptr<DataAbilityHelper> Creator(
const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri, const bool tryBind);
/**
* @brief Releases the client resource of the Data ability.
* You should call this method to releases client resource after the data operations are complete.
*
* @return Returns true if the resource is successfully released; returns false otherwise.
*/
bool Release();
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> GetFileTypes(Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int OpenFile(Uri &uri, const std::string &mode);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int OpenRawFile(Uri &uri, const std::string &mode);
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int Insert(Uri &uri, const ValuesBucket &value);
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int Update(Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int Delete(Uri &uri, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> Query(
Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates);
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string GetType(Uri &uri);
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool Reload(Uri &uri, const PacMap &extras);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int BatchInsert(Uri &uri, const std::vector<ValuesBucket> &values);
private:
DataAbilityHelper(const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri,
const sptr<AAFwk::IAbilityScheduler> &dataAbilityProxy, bool tryBind = false);
DataAbilityHelper(const std::shared_ptr<Context> &context);
sptr<IRemoteObject> token_;
std::weak_ptr<Context> context_;
std::shared_ptr<Uri> uri_ = nullptr;
bool tryBind_ = false;
sptr<AAFwk::IAbilityScheduler> dataAbilityProxy_ = nullptr;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_HELPER_H
@@ -0,0 +1,160 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_IMPL_H
#define FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_IMPL_H
#include "ability_impl.h"
namespace OHOS {
namespace AppExecFwk {
class DataAbilityImpl final : public AbilityImpl {
public:
/**
* @brief Constructor.
*
*/
DataAbilityImpl() = default;
/**
* @brief Destructor.
*
*/
~DataAbilityImpl() = default;
/**
* @brief Handling the life cycle switching of PageAbility.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
*/
void HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState);
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int OpenFile(const Uri &uri, const std::string &mode);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int OpenRawFile(const Uri &uri, const std::string &mode);
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int Insert(const Uri &uri, const ValuesBucket &value);
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int Delete(const Uri &uri, const DataAbilityPredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates);
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string GetType(const Uri &uri);
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool Reload(const Uri &uri, const PacMap &extras);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_IMPL_H
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef DATA_URI_UTIL_H
#define DATA_URI_UTIL_H
#include <cstring>
#include "uri.h"
using string = std::string;
using Uri = OHOS::Uri;
namespace OHOS {
namespace AppExecFwk {
class DataUriUtils final {
public:
/**
* @brief Default constructor of DataUriUtils class
* @return None
*/
DataUriUtils();
/**
* @brief Default deconstructor of DataUriUtils class
* @return None
*/
~DataUriUtils();
/**
* @brief Attaches the given ID to the end of the path component of the given URI.
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @param id
* @return Uri( scheme://authority/path1/path2/path3/updateIDNumber....)
*/
static Uri AttachId(const Uri &dataUri, long id);
/**
* @brief Obtains the ID attached to the end of the path component of the given URI.
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @return long ID
*/
static long GetId(const Uri &dataUri);
/**
* @brief Deletes the ID from the end of the path component of the given URI.
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @return long ID
*/
static Uri DeleteId(const Uri &dataUri);
/**
* @brief Updates the ID in the specified dataUri
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @param id indiates Update attached to the end of the path component of the given URI
* @return Uri return is the URI after path is updated
*/
static Uri UpdateId(const Uri &dataUri, long id);
/**
* @brief Does the end path of the path component of the given URI have an ID attached to it?
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @return bool
*/
static bool IsAttachedId(const Uri &dataUri);
private:
/**
* @brief Determine whether the string content is a numeric string
* @param str indicates stirng.
* @return bool
*/
static bool IsNumber(const string &str);
/**
* @brief Determine whether the string content is a numeric string
* @param dataUri indicates Uri object
* @return Uri return is the URI after path is updated
*/
static Uri UriUpateLastPath(const Uri &dataUri, const string &updateLastPath);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITYPACKAGE_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITYPACKAGE_H
namespace OHOS {
namespace AppExecFwk {
class AbilityPackage {
public:
AbilityPackage() = default;
~AbilityPackage() = default;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITYPACKAGE_H
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_DUMMY_COMPONENT_CONTAINER_H
#define FOUNDATION_APPEXECFWK_OHOS_DUMMY_COMPONENT_CONTAINER_H
namespace OHOS {
namespace AppExecFwk {
class ComponentContainer {
public:
ComponentContainer() = default;
~ComponentContainer() = default;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_DUMMY_COMPONENT_CONTAINER_H
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_CONTINUATIONTATE_H
#define FOUNDATION_APPEXECFWK_OHOS_CONTINUATIONTATE_H
namespace OHOS {
namespace AppExecFwk {
class ContinuationState {
public:
ContinuationState() = default;
~ContinuationState() = default;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_CONTINUATIONTATE_H
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_DATAABILITYPREDICATES_H
#define FOUNDATION_APPEXECFWK_OHOS_DATAABILITYPREDICATES_H
#include <string>
#include <unistd.h>
#include "nocopyable.h"
#include "parcel.h"
namespace OHOS {
namespace AppExecFwk {
class DataAbilityPredicates : public Parcelable {
public:
DataAbilityPredicates() = default;
DataAbilityPredicates(const std::string &testInf);
~DataAbilityPredicates() = default;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static DataAbilityPredicates *Unmarshalling(Parcel &parcel);
private:
std::string testInf_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_DATAABILITYPREDICATES_H
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_FILEDESCRIPTOR_H
#define FOUNDATION_APPEXECFWK_OHOS_FILEDESCRIPTOR_H
namespace OHOS {
namespace AppExecFwk {
class FileDescriptor {
public:
FileDescriptor() = default;
~FileDescriptor() = default;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_FILEDESCRIPTOR_H
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_NOTIFICATIONREQUEST_H
#define FOUNDATION_APPEXECFWK_OHOS_NOTIFICATIONREQUEST_H
namespace OHOS {
namespace AppExecFwk {
class NotificationRequest {
public:
NotificationRequest() = default;
~NotificationRequest() = default;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_NOTIFICATIONREQUEST_H
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_RAWFILEDESCRIPTOR_H
#define FOUNDATION_APPEXECFWK_OHOS_RAWFILEDESCRIPTOR_H
namespace OHOS {
namespace AppExecFwk {
class RawFileDescriptor {
public:
RawFileDescriptor() = default;
~RawFileDescriptor() = default;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_RAWFILEDESCRIPTOR_H
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_RESULTSET_H
#define FOUNDATION_APPEXECFWK_OHOS_RESULTSET_H
#include <string>
#include <unistd.h>
#include "nocopyable.h"
#include "parcel.h"
namespace OHOS {
namespace AppExecFwk {
class ResultSet : public Parcelable {
public:
ResultSet() = default;
ResultSet(const std::string &testInf);
~ResultSet() = default;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static ResultSet *Unmarshalling(Parcel &parcel);
std::string testInf_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_RESULTSET_H
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_VALUESBUCKER_H
#define FOUNDATION_APPEXECFWK_OHOS_VALUESBUCKER_H
#include <string>
#include <unistd.h>
#include "nocopyable.h"
#include "parcel.h"
namespace OHOS {
namespace AppExecFwk {
class ValuesBucket : public Parcelable {
public:
ValuesBucket() = default;
ValuesBucket(const std::string &testInf);
~ValuesBucket() = default;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static ValuesBucket *Unmarshalling(Parcel &parcel);
private:
std::string testInf_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_VALUESBUCKER_H
@@ -0,0 +1,73 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_IABILITY_LIFECYCLE_CALLBACK_H
#define FOUNDATION_APPEXECFWK_OHOS_IABILITY_LIFECYCLE_CALLBACK_H
namespace OHOS {
namespace AppExecFwk {
class IAbilityLifecycleCallback {
public:
/**
*
* Will be called when Ability start
*
* @param want Want for AbilitySliceManager
*/
virtual void OnAbilityStart(const Want &want) = 0;
/**
*
* Will be called when Ability stop
*/
virtual void OnAbilityStop() = 0;
/**
*
* Will be called when Ability active
*/
virtual void OnAbilityActive() = 0;
/**
*
* Will be called when Ability inactive
*/
virtual void OnAbilityInactive() = 0;
/**
*
* Will be called when Ability foreground
*
* @param want Want for AbilitySliceManager
*/
virtual void OnAbilityForeground(const Want &want) = 0;
/**
*
* Will be called when Ability to background
*/
virtual void OnAbilityBackground() = 0;
/**
* Will be called to receive result from other ability
*
* @param requestCode request code of ability result
* @param want ability result from other ability
*/
virtual void OnAbilityResult(int requestCode, const Want &want) = 0;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_IABILITY_LIFECYCLE_CALLBACK_H
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef OHOS_AAFWK_IPCSINGLETON_H
#define OHOS_AAFWK_IPCSINGLETON_H
#include "nocopyable.h"
#include <mutex>
#include <memory>
namespace OHOS {
#define DECLARE_DELAYED_IPCSINGLETON(MyClass) \
public: \
~MyClass(); \
\
private: \
friend DelayedIPCSingleton<MyClass>; \
MyClass();
template <typename T>
class DelayedIPCSingleton : public NoCopyable {
public:
static sptr<T> GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> lock(mutex_);
if (instance_ == nullptr) {
sptr<T> temp(new T);
instance_ = temp;
}
}
return instance_;
};
static void DestroyInstance();
private:
static sptr<T> instance_;
static std::mutex mutex_;
};
template <typename T>
sptr<T> DelayedIPCSingleton<T>::instance_ = nullptr;
template <typename T>
std::mutex DelayedIPCSingleton<T>::mutex_;
template <typename T>
void DelayedIPCSingleton<T>::DestroyInstance()
{
std::lock_guard<std::mutex> lock(mutex_);
if (instance_ != nullptr) {
instance_.reset();
instance_ = nullptr;
}
}
} // namespace OHOS
#endif // OHOS_AAFWK_IPCSINGLETON_H
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_PAGE_ABILITY_IMPL_H
#define FOUNDATION_APPEXECFWK_OHOS_PAGE_ABILITY_IMPL_H
#include "ability_impl.h"
namespace OHOS {
namespace AppExecFwk {
class Ability;
class AbilityHandler;
class AbilityLocalRecord;
class AbilityImpl;
class PageAbilityImpl final : public AbilityImpl {
public:
/**
* @brief Constructor.
*
*/
PageAbilityImpl() = default;
/**
* @brief Destructor.
*
*/
~PageAbilityImpl() = default;
/**
* @brief Handling the life cycle switching of PageAbility.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
*/
void HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState);
/**
* @brief Handling the life cycle switching of PageAbility in switch.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
* @return return true if the lifecycle transaction successfully, otherwise return false.
*
*/
bool AbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState);
/**
* @brief Execution the KeyDown callback of the ability
* @param keyCode Indicates the code of the key pressed.
* @param keyEvent Indicates the key-down event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
bool DoKeyDown(int keyCode, const KeyEvent &keyEvent);
/**
* @brief Execution the KeyUp callback of the ability
* @param keyCode Indicates the code of the key released.
* @param keyEvent Indicates the key-up event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
bool DoKeyUp(int keyCode, const KeyEvent &keyEvent);
/**
* @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
* does nothing and returns false.
* @param touchEvent Indicates information about the touch event.
*
* @return Returns true if the event is handled; returns false otherwise.
*
*/
bool DoTouchEvent(const TouchEvent &touchEvent);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_PAGE_ABILITY_IMPL_H
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_SERVICE_ABILITY_IMPL_H
#define FOUNDATION_APPEXECFWK_OHOS_SERVICE_ABILITY_IMPL_H
#include "ability_impl.h"
namespace OHOS {
namespace AppExecFwk {
class Ability;
class AbilityHandler;
class AbilityLocalRecord;
class AbilityImpl;
class ServiceAbilityImpl final : public AbilityImpl {
public:
/**
* @brief Constructor.
*
*/
ServiceAbilityImpl() = default;
/**
* @brief Destructor.
*
*/
~ServiceAbilityImpl() = default;
/**
* @brief Handling the life cycle switching of PageAbility.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
*/
void HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState);
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_SERVICE_ABILITY_IMPL_H
File diff suppressed because it is too large Load Diff
+830
View File
@@ -0,0 +1,830 @@
/*
* Copyright (c) 2021 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 "ability_context.h"
#include "ability_manager_client.h"
#include "app_log_wrapper.h"
#include "resource_manager.h"
#include "bundle_constants.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method
* to start a specific ability. The system locates the target ability from installed abilities based on the value
* of the want parameter and then starts it. You can specify the ability to start using the want parameter.
*
* @param want Indicates the Want containing information about the target ability to start.
*
* @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE
* template is started. You can define the request code to identify the results returned by abilities. The value
* ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE
* template.
*
*/
void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode)
{
APP_LOGI("AbilityContext::StartAbility called");
AppExecFwk::AbilityType type = GetAbilityInfoType();
if (type != AppExecFwk::AbilityType::PAGE && type != AppExecFwk::AbilityType::SERVICE) {
APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type);
return;
}
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode);
if (err != ERR_OK) {
APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err);
}
}
/**
* @brief Starts a new ability with special ability start setting.
*
* @param want Indicates the Want containing information about the target ability to start.
* @param requestCode Indicates the request code returned after the ability is started. You can define the request code
* to identify the results returned by abilities. The value ranges from 0 to 65535.
* @param abilityStartSetting Indicates the special start setting used in starting ability.
*
*/
void AbilityContext::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting)
{
AppExecFwk::AbilityType type = GetAbilityInfoType();
if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) {
APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type);
return;
}
}
/**
* @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult
* (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode passed.
*
* @param requestCode Indicates the request code passed for starting the ability.
*
*/
void AbilityContext::TerminateAbility(int requestCode)
{
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, requestCode);
if (err != ERR_OK) {
APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err);
}
}
/**
* @brief Destroys the current ability.
*
*/
void AbilityContext::TerminateAbility()
{
std::shared_ptr<AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
APP_LOGE("AbilityContext::TerminateAbility info == nullptr");
return;
}
ErrCode err = ERR_OK;
switch (info->type) {
case AppExecFwk::AbilityType::PAGE:
err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, resultCode_, &resultWant_);
break;
case AppExecFwk::AbilityType::SERVICE:
err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr);
break;
default:
APP_LOGE("AbilityContext::TerminateAbility info type error is %{public}d", info->type);
break;
}
if (err != ERR_OK) {
APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err);
}
} // namespace AppExecFwk
/**
* @brief Obtains the bundle name of the ability that called the current ability.
* You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will
* send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int,
* ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned.
*
* @return Returns the bundle name of the calling ability; returns null if no calling ability is available.
*/
std::string AbilityContext::GetCallingBundle()
{
return callingBundleName_;
}
/**
* @brief Obtains the ohos.bundle.ElementName object of the current ability.
*
* @return Returns the ohos.bundle.ElementName object of the current ability.
*/
std::shared_ptr<ElementName> AbilityContext::GetElementName()
{
std::shared_ptr<AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
APP_LOGE("AbilityContext::GetElementName info == nullptr");
return nullptr;
}
std::shared_ptr<ElementName> elementName = std::make_shared<ElementName>();
if (elementName == nullptr) {
APP_LOGE("AbilityContext::GetElementName elementName == nullptr");
return nullptr;
}
elementName->SetAbilityName(info->name);
elementName->SetBundleName(info->bundleName);
elementName->SetDeviceID(info->deviceId);
return elementName;
}
/**
* @brief Obtains the ElementName of the ability that called the current ability.
*
* @return Returns the ElementName of the calling ability; returns null if no calling ability is available.
*/
std::shared_ptr<ElementName> AbilityContext::GetCallingAbility()
{
std::shared_ptr<ElementName> elementName = std::make_shared<ElementName>();
if (elementName == nullptr) {
APP_LOGE("AbilityContext::GetElementName elementName == nullptr");
return nullptr;
}
elementName->SetAbilityName(callingAbilityName_);
elementName->SetBundleName(callingBundleName_);
elementName->SetDeviceID(callingDeviceId_);
return elementName;
}
/**
* @brief Connects the current ability to an ability
*
* @param want Indicates the want containing information about the ability to connect
*
* @param conn Indicates the callback object when the target ability is connected.
*
* @return True means success and false means failure
*/
bool AbilityContext::ConnectAbility(const Want &want, const sptr<AAFwk::IAbilityConnection> &conn)
{
APP_LOGD("AbilityContext::ConnectAbility called");
AppExecFwk::AbilityType type = GetAbilityInfoType();
if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) {
APP_LOGE("AbilityContext::ConnectAbility AbilityType = %{public}d", type);
return false;
}
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_);
bool value = ((ret == ERR_OK) ? true : false);
if (!value) {
APP_LOGE("AbilityContext::ConnectAbility ErrorCode = %{public}d", ret);
}
return value;
}
/**
*
* @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection
* is set up. The IAbilityConnection object uniquely identifies a connection between two abilities.
*/
void AbilityContext::DisconnectAbility(const sptr<AAFwk::IAbilityConnection> &conn)
{
APP_LOGD("AbilityContext::DisconnectAbility called");
AppExecFwk::AbilityType type = GetAbilityInfoType();
if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) {
APP_LOGE("AbilityContext::DisconnectAbility AbilityType = %{public}d", type);
return;
}
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn);
if (ret != ERR_OK) {
APP_LOGE("AbilityContext::DisconnectAbility error");
}
}
/**
* @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template.
* The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE
* template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE
* template. The current ability itself can be destroyed by calling the terminateAbility() method.
*
* @param want Indicates the Want containing information about the ability to destroy.
*
* @return Returns true if the ability is destroyed successfully; returns false otherwise.
*/
bool AbilityContext::StopAbility(const AAFwk::Want &want)
{
AppExecFwk::AbilityType type = GetAbilityInfoType();
if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) {
APP_LOGE("AbilityContext::StopAbility AbilityType = %{public}d", type);
return false;
}
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StopServiceAbility(want);
if (err != ERR_OK) {
APP_LOGE("AbilityContext::StopAbility is failed %{public}d", err);
return false;
}
return true;
}
sptr<IRemoteObject> AbilityContext::GetToken()
{
return token_;
}
/**
* @brief Obtains information about the current application. The returned application information includes basic
* information such as the application name and application permissions.
*
* @return Returns the ApplicationInfo for the current application.
*/
std::shared_ptr<ApplicationInfo> AbilityContext::GetApplicationInfo() const
{
return ContextContainer::GetApplicationInfo();
}
/**
* @brief Obtains the application-specific cache directory on the device's internal storage. The system
* automatically deletes files from the cache directory if disk space is required elsewhere on the device.
* Older files are always deleted first.
*
* @return Returns the application-specific cache directory.
*/
std::string AbilityContext::GetCacheDir()
{
return ContextContainer::GetCacheDir();
}
/**
* @brief Obtains the application-specific code-cache directory on the device's internal storage.
* The system will delete any files stored in this location both when your specific application is upgraded,
* and when the entire platform is upgraded.
*
* @return Returns the application-specific code-cache directory.
*/
std::string AbilityContext::GetCodeCacheDir()
{
return ContextContainer::GetCodeCacheDir();
}
/**
* @brief Obtains the local database path.
* If the local database path does not exist, the system creates one and returns the created path.
*
* @return Returns the local database file.
*/
std::string AbilityContext::GetDatabaseDir()
{
return ContextContainer::GetDatabaseDir();
}
/**
* @brief Obtains the absolute path where all private data files of this application are stored.
*
* @return Returns the absolute path storing all private data files of this application.
*/
std::string AbilityContext::GetDataDir()
{
return ContextContainer::GetDataDir();
}
/**
* @brief Obtains the directory for storing custom data files of the application.
* You can use the returned File object to create and access files in this directory. The files
* can be accessible only by the current application.
*
* @param name Indicates the name of the directory to retrieve. This directory is created as part
* of your application data.
* @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE.
*
* @return Returns a File object for the requested directory.
*/
std::string AbilityContext::GetDir(const std::string &name, int mode)
{
return ContextContainer::GetDir(name, mode);
}
/**
* @brief Obtains an IBundleMgr instance.
* You can use this instance to obtain information about the application bundle.
*
* @return Returns an IBundleMgr instance.
*/
sptr<IBundleMgr> AbilityContext::GetBundleManager() const
{
return ContextContainer::GetBundleManager();
}
/**
* @brief Obtains the path of the package containing the current ability. The returned path contains the resources,
* source code, and configuration files of a module.
*
* @return Returns the path of the package file.
*/
std::string AbilityContext::GetBundleCodePath()
{
return ContextContainer::GetBundleCodePath();
}
/**
* @brief Obtains the bundle name of the current ability.
*
* @return Returns the bundle name of the current ability.
*/
std::string AbilityContext::GetBundleName()
{
return ContextContainer::GetBundleName();
}
/**
* @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability.
*
* @return Returns the path of the HAP containing this ability.
*/
std::string AbilityContext::GetBundleResourcePath()
{
return ContextContainer::GetBundleResourcePath();
}
/**
* @brief Obtains the Context object of the application.
*
* @return Returns the Context object of the application.
*/
std::shared_ptr<Context> AbilityContext::GetApplicationContext() const
{
return ContextContainer::GetApplicationContext();
}
/**
* @brief Obtains the Context object of the application.
*
* @return Returns the Context object of the application.
*/
std::shared_ptr<Context> AbilityContext::GetContext()
{
return ContextContainer::GetContext();
}
/**
* @brief Obtains an ability manager.
* The ability manager provides information about running processes and memory usage of an application.
*
* @return Returns an IAbilityManager instance.
*/
sptr<AAFwk::IAbilityManager> AbilityContext::GetAbilityManager()
{
return ContextContainer::GetAbilityManager();
}
/**
* Called when getting the ProcessInfo
*
* @return ProcessInfo
*/
std::shared_ptr<ProcessInfo> AbilityContext::GetProcessInfo() const
{
return ContextContainer::GetProcessInfo();
}
/**
* @brief Obtains the type of this application.
*
* @return Returns system if this application is a system application;
* returns normal if it is released in official AppGallery;
* returns other if it is released by a third-party vendor;
* returns an empty string if the query fails.
*/
std::string AbilityContext::GetAppType()
{
return ContextContainer::GetAppType();
}
/**
* @brief Obtains information about the current ability.
* The returned information includes the class name, bundle name, and other information about the current ability.
*
* @return Returns the AbilityInfo object for the current ability.
*/
const std::shared_ptr<AbilityInfo> AbilityContext::GetAbilityInfo()
{
return ContextContainer::GetAbilityInfo();
}
/**
* @brief Obtains the HapModuleInfo object of the application.
*
* @return Returns the HapModuleInfo object of the application.
*/
std::shared_ptr<HapModuleInfo> AbilityContext::GetHapModuleInfo()
{
return ContextContainer::GetHapModuleInfo();
}
/**
* @brief Get Current Ability Type
*
* @return Current Ability Type
*/
AppExecFwk::AbilityType AbilityContext::GetAbilityInfoType()
{
std::shared_ptr<AbilityInfo> info = GetAbilityInfo();
if (info == nullptr) {
APP_LOGE("AbilityContext::GetAbilityInfoType info == nullptr");
return AppExecFwk::AbilityType::UNKNOWN;
}
return info->type;
}
/**
* @brief Creates a Context object for an application with the given bundle name.
*
* @param bundleName Indicates the bundle name of the application.
*
* @param flag Indicates the flag for creating a Context object. It can be 0, any of
* the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY,
* CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction
* on creating contexts for applications.
*
* @return Returns a Context object created for the specified application.
*/
std::shared_ptr<Context> AbilityContext::CreateBundleContext(std::string bundleName, int flag)
{
return ContextContainer::CreateBundleContext(bundleName, flag);
}
/**
* @brief Obtains a resource manager.
*
* @return Returns a ResourceManager object.
*/
std::shared_ptr<Global::Resource::ResourceManager> AbilityContext::GetResourceManager() const
{
std::shared_ptr<Context> appcontext = GetApplicationContext();
if (appcontext == nullptr) {
APP_LOGE("AbilityContext::GetResourceManager appcontext is nullptr");
return nullptr;
}
std::shared_ptr<Global::Resource::ResourceManager> resourceManager = appcontext->GetResourceManager();
if (resourceManager == nullptr) {
APP_LOGE("AbilityContext::GetResourceManager resourceManager is nullptr");
return nullptr;
}
return resourceManager;
}
/**
* @brief Checks whether the current process has the given permission.
* You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only
* if the current process does not have the specific permission.
*
* @param permission Indicates the permission to check. This parameter cannot be null.
*
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
int AbilityContext::VerifySelfPermission(const std::string &permission)
{
if (permission.empty()) {
APP_LOGE("VerifySelfPermission permission invalid");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
std::string bundle_name = GetBundleName();
if (bundle_name.empty()) {
APP_LOGE("VerifySelfPermission failed to get bundle name error");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
sptr<IBundleMgr> ptr = GetBundleManager();
if (ptr == nullptr) {
APP_LOGE("VerifySelfPermission failed to get bundle manager service");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
return ptr->CheckPermission(bundle_name, permission);
}
/**
* @brief Checks whether the calling process for inter-process communication has the given permission.
* The calling process is not the current process.
*
* @param permission Indicates the permission to check. This parameter cannot be null.
*
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
int AbilityContext::VerifyCallingPermission(const std::string &permission)
{
if (permission.empty()) {
APP_LOGE("VerifyCallingPermission permission invalid");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
std::string bundle_name = GetCallingBundle();
if (bundle_name.empty()) {
APP_LOGE("VerifyCallingPermission failed to get bundle name by uid");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
sptr<IBundleMgr> ptr = GetBundleManager();
if (ptr == nullptr) {
APP_LOGE("VerifyCallingPermission failed to get bundle manager service");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
return ptr->CheckPermission(bundle_name, permission);
}
/**
* @brief Confirms with the permission management module to check whether a request prompt is required for granting a
* certain permission. You need to call the current method to check whether a prompt is required before calling
* requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, permission
* request will not be initiated.
*
* @param requestCode Indicates the permission to be queried. This parameter cannot be null.
*
* @return Returns true if the current application does not have the permission and the user does not turn off further
* requests; returns false if the current application already has the permission, the permission is rejected by the
* system, or the permission is denied by the user and the user has turned off further requests.
*/
bool AbilityContext::CanRequestPermission(const std::string &permission)
{
if (permission.empty()) {
APP_LOGE("CanRequestPermission permission invalid");
return true;
}
std::string bundle_name = GetBundleName();
if (bundle_name.empty()) {
APP_LOGE("CanRequestPermission failed to get bundle name error");
return true;
}
sptr<IBundleMgr> ptr = GetBundleManager();
if (ptr == nullptr) {
APP_LOGE("CanRequestPermission failed to get bundle manager service");
return true;
}
return ptr->CanRequestPermission(bundle_name, permission, 0);
}
/**
* @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has
* permission
*
* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission)
{
return VerifySelfPermission(permission);
}
/**
* @brief Query whether the application of the specified PID and UID has been granted a certain permission
*
* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
* @param pid Process id
* @param uid
* @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission;
* returns -1 (IBundleManager.PERMISSION_DENIED) otherwise.
*/
int AbilityContext::VerifyPermission(const std::string &permission, int pid, int uid)
{
if (permission.empty()) {
APP_LOGE("VerifyPermission permission invalid");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
sptr<IBundleMgr> ptr = GetBundleManager();
if (ptr == nullptr) {
APP_LOGE("VerifyPermission failed to get bundle manager service");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
std::string bundle_name;
if (!ptr->GetBundleNameForUid(uid, bundle_name)) {
APP_LOGE("VerifyPermission failed to get bundle name by uid");
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
return ptr->CheckPermission(bundle_name, permission);
}
/**
* @brief Requests certain permissions from the system.
* This method is called for permission request. This is an asynchronous method. When it is executed,
* the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back.
*
* @param permissions Indicates the list of permissions to be requested. This parameter cannot be null.
* @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int,
* String[], int[]) callback method. This code cannot be a negative number.
*/
void AbilityContext::RequestPermissionsFromUser(std::vector<std::string> &permissions, int requestCode)
{
if (permissions.size() == 0) {
APP_LOGE("AbilityContext::RequestPermissionsFromUser permissions is empty");
return;
}
if (requestCode < 0) {
APP_LOGE("AbilityContext::RequestPermissionsFromUser requestCode should be >= 0");
return;
}
AAFwk::Want want;
want.SetElementName("com.ohos.systemui", "com.ohos.systemdialog.MainAbility");
want.SetParam(OHOS_PERMISSIONS_REQUEST_KEY, permissions);
want.SetParam(OHOS_PERMISSIONS_REQUEST_USER_ID_KEY, 0);
want.SetParam(OHOS_PERMISSIONS_REQUEST_BUNDLE_NAME_KEY, GetBundleName());
StartAbility(want, requestCode);
}
/* @brief Deletes the specified private file associated with the application.
*
* @param fileName Indicates the name of the file to delete. The file name cannot contain path separators.
*
* @return Returns true if the file is deleted successfully; returns false otherwise.
*/
bool AbilityContext::DeleteFile(const std::string &fileName)
{
return ContextContainer::DeleteFile(fileName);
}
/**
* @brief Set deviceId/bundleName/abilityName of the calling ability
*
* @param deviceId deviceId of the calling ability
*
* @param deviceId bundleName of the calling ability
*
* @param deviceId abilityName of the calling ability
*/
void AbilityContext::SetCallingContext(
const std::string &deviceId, const std::string &bundleName, const std::string &abilityName)
{
callingDeviceId_ = deviceId;
callingBundleName_ = bundleName;
callingAbilityName_ = abilityName;
}
/**
* @brief Obtains information about the caller of this ability.
*
* @return Returns the caller information.
*/
Uri AbilityContext::GetCaller()
{
return ContextContainer::GetCaller();
}
/**
* Attaches a Context object to the current ability.
* Generally, this method is called after Ability is loaded to provide the application context for the current
* ability.
*
* @param base Indicates a Context object.
*/
void AbilityContext::AttachBaseContext(const std::shared_ptr<Context> &base)
{
ContextContainer::AttachBaseContext(base);
}
/**
* @brief Obtains the absolute path to the application-specific cache directory
* on the primary external or shared storage device.
*
* @return Returns the absolute path to the application-specific cache directory on the external or
* shared storage device; returns null if the external or shared storage device is temporarily unavailable.
*/
std::string AbilityContext::GetExternalCacheDir()
{
return ContextContainer::GetExternalCacheDir();
}
/**
* @brief Obtains the absolute path to the directory for storing files for the application on the
* primary external or shared storage device.
*
* @param type Indicates the type of the file directory to return
*
* @return Returns the absolute path to the application file directory on the external or shared storage
* device; returns null if the external or shared storage device is temporarily unavailable.
*/
std::string AbilityContext::GetExternalFilesDir(std::string &type)
{
return ContextContainer::GetExternalFilesDir(type);
}
/**
* @brief Obtains the directory for storing files for the application on the device's internal storage.
*
* @return Returns the application file directory.
*/
std::string AbilityContext::GetFilesDir()
{
return ContextContainer::GetFilesDir();
}
/**
* @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage.
* The returned path maybe changed if the application is moved to an adopted storage device.
*
* @return The path of the directory holding application files that will not be automatically backed up to remote
* storage.
*/
std::string AbilityContext::GetNoBackupFilesDir()
{
return ContextContainer::GetNoBackupFilesDir();
}
/**
* @brief Remove permissions for all users who have access to specific permissions
*
* @param permission Indicates the permission to unauth. This parameter cannot be null.
* @param uri Indicates the URI to unauth. This parameter cannot be null.
* @param uid Indicates the UID of the unauth to check.
*
*/
void AbilityContext::UnauthUriPermission(const std::string &permission, const Uri &uri, int uid)
{
ContextContainer::UnauthUriPermission(permission, uri, uid);
}
/**
* @brief Obtains the distributed file path.
* If the distributed file path does not exist, the system creates one and returns the created path. This method is
* applicable only to the context of an ability rather than that of an application.
*
* @return Returns the distributed file.
*/
std::string AbilityContext::GetDistributedDir()
{
return ContextContainer::GetDistributedDir();
}
/**
* @brief Sets the pattern of this Context based on the specified pattern ID.
*
* @param patternId Indicates the resource ID of the pattern to set.
*/
void AbilityContext::SetPattern(int patternId)
{
ContextContainer::SetPattern(patternId);
}
/**
* @brief Obtains the Context object of this ability.
*
* @return Returns the Context object of this ability.
*/
std::shared_ptr<Context> AbilityContext::GetAbilityPackageContext()
{
return ContextContainer::GetAbilityPackageContext();
}
/**
* @brief Obtains the name of the current process.
*
* @return Returns the current process name.
*/
std::string AbilityContext::GetProcessName()
{
return ContextContainer::GetProcessName();
}
/**
* @brief InitResourceManager
*
* @param bundleInfo BundleInfo
*/
void AbilityContext::InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr<ContextDeal> &deal)
{
ContextContainer::InitResourceManager(bundleInfo, deal);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2021 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 "ability_handler.h"
namespace OHOS {
namespace AppExecFwk {
AbilityHandler::AbilityHandler(const std::shared_ptr<EventRunner> &runner, const sptr<AbilityThread> &server)
: EventHandler(runner), server_(server)
{}
/**
* Process the event. Developers should override this method.
*
* @param event The event should be processed.
*/
void AbilityHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer &event)
{}
} // namespace AppExecFwk
} // namespace OHOS
+534
View File
@@ -0,0 +1,534 @@
/*
* Copyright (c) 2021 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 "ability_impl.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
void AbilityImpl::Init(std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &record,
std::shared_ptr<Ability> &ability, std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token,
std::shared_ptr<ContextDeal> &contextDeal)
{
APP_LOGI("AbilityImpl::init begin");
if ((token == nullptr) || (application == nullptr) || (handler == nullptr) || (record == nullptr) ||
ability == nullptr || contextDeal == nullptr) {
APP_LOGE("AbilityImpl::init failed, token is nullptr, application is nullptr, handler is nullptr, record is "
"nullptr, ability is nullptr, contextDeal is nullptr");
return;
}
token_ = record->GetToken();
record->SetAbilityImpl(shared_from_this());
ability_ = ability;
ability_->Init(record->GetAbilityInfo(), application, handler, token);
lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL;
abilityLifecycleCallbacks_ = application;
contextDeal_ = contextDeal;
APP_LOGI("AbilityImpl::init end");
}
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
* @param want The Want object to switch the life cycle.
*/
void AbilityImpl::Start(const Want &want)
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::Start ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGI("AbilityImpl::Start");
ability_->OnStart(want);
if (ability_->GetAbilityInfo()->type == AbilityType::DATA) {
lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE;
} else {
lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE;
}
abilityLifecycleCallbacks_->OnAbilityStart(ability_);
}
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INITIAL. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void AbilityImpl::Stop()
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::Stop ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGD("AbilityImpl::Stop");
ability_->OnStop();
lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL;
abilityLifecycleCallbacks_->OnAbilityStop(ability_);
}
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_ACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void AbilityImpl::Active()
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::Active ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGD("AbilityImpl::Active");
ability_->OnActive();
lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE;
abilityLifecycleCallbacks_->OnAbilityActive(ability_);
}
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void AbilityImpl::Inactive()
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::Inactive ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGD("AbilityImpl::Inactive");
ability_->OnInactive();
lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE;
abilityLifecycleCallbacks_->OnAbilityInactive(ability_);
}
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application
* that it belongs to of the lifecycle status.
*
* @param want The Want object to switch the life cycle.
*/
void AbilityImpl::Foreground(const Want &want)
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::Foreground ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGD("AbilityImpl::Foreground");
ability_->OnForeground(want);
lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE;
abilityLifecycleCallbacks_->OnAbilityForeground(ability_);
}
/**
* @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the application
* that it belongs to of the lifecycle status.
*
*/
void AbilityImpl::Background()
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::Background ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGD("AbilityImpl::Background");
ability_->OnLeaveForeground();
ability_->OnBackground();
lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND;
abilityLifecycleCallbacks_->OnAbilityBackground(ability_);
}
/**
* @brief Save data and states of an ability when it is restored by the system. and Calling information back to Ability.
* This method should be implemented by a Page ability.
* @param instate The Want object to connect to.
*
*/
void AbilityImpl::DispatchSaveAbilityState(PacMap &outState)
{
if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) {
APP_LOGE("AbilityImpl::DispatchSaveAbilityState ability_ or abilityLifecycleCallbacks_ is nullptr");
return;
}
APP_LOGD("AbilityImpl::DispatchSaveAbilityState");
ability_->OnSaveAbilityState(outState);
abilityLifecycleCallbacks_->OnAbilitySaveState(outState);
}
/**
* @brief Restores data and states of an ability when it is restored by the system. and Calling information back to
* Ability. This method should be implemented by a Page ability.
* @param instate The Want object to connect to.
*
*/
void AbilityImpl::DispatchRestoreAbilityState(const PacMap &inState)
{
if (ability_ == nullptr) {
APP_LOGE("AbilityImpl::DispatchRestoreAbilityState ability_ is nullptr");
return;
}
APP_LOGD("AbilityImpl:: DispatchRestoreAbilityState");
ability_->OnRestoreAbilityState(inState);
}
void AbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{}
/**
* @brief Connect the ability. and Calling information back to Ability.
*
* @param want The Want object to connect to.
*
*/
sptr<IRemoteObject> AbilityImpl::ConnectAbility(const Want &want)
{
if (ability_ == nullptr) {
APP_LOGE("AbilityImpl::ConnectAbility ability_ is nullptr");
return nullptr;
}
APP_LOGD("AbilityImpl:: ConnectAbility");
sptr<IRemoteObject> object = ability_->OnConnect(want);
lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE;
abilityLifecycleCallbacks_->OnAbilityActive(ability_);
return object;
}
/**
* @brief Disconnects the connected object.
*
* @param want The Want object to disconnect to.
*/
void AbilityImpl::DisconnectAbility(const Want &want)
{
if (ability_ == nullptr) {
APP_LOGE("AbilityImpl::DisconnectAbility ability_ is nullptr");
return;
}
ability_->OnDisconnect(want);
}
/**
* @brief Command the ability. and Calling information back to Ability.
*
* @param want The Want object to command to.
*
* * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
*
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented by 1
* every time the ability is started. For example, if the ability has been started for six times, the value of startId
* is 6.
*/
void AbilityImpl::CommandAbility(const Want &want, bool restart, int startId)
{
if (ability_ == nullptr) {
APP_LOGE("AbilityImpl::CommandAbility ability_ is nullptr");
return;
}
APP_LOGD("AbilityImpl:: CommandAbility");
ability_->OnCommand(want, restart, startId);
lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE;
abilityLifecycleCallbacks_->OnAbilityActive(ability_);
}
/**
* @brief Gets the current Ability status.
*
*/
int AbilityImpl::GetCurrentState()
{
return lifecycleState_;
}
/**
* @brief Execution the KeyDown callback of the ability
* @param keyCode Indicates the code of the key pressed.
* @param keyEvent Indicates the key-down event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
bool AbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent)
{
APP_LOGD("AbilityImpl::DoKeyDown called");
return false;
}
/**
* @brief Execution the KeyUp callback of the ability
* @param keyCode Indicates the code of the key released.
* @param keyEvent Indicates the key-up event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
bool AbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent)
{
APP_LOGD("AbilityImpl::DoKeyUp called");
return false;
}
/**
* @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
* does nothing and returns false.
* @param touchEvent Indicates information about the touch event.
*
* @return Returns true if the event is handled; returns false otherwise.
*
*/
bool AbilityImpl::DoTouchEvent(const TouchEvent &touchEvent)
{
APP_LOGD("AbilityImpl::DoTouchEvent called");
return false;
}
/**
* @brief Send the result code and data to be returned by this Page ability to the caller.
* When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to
* receive the result set in the current method. This method can be called only after the ability has been initialized.
*
* @param requestCode Indicates the request code.
* @param resultCode Indicates the result code returned after the ability is destroyed. You can define the result code
* to identify an error.
* @param resultData Indicates the data returned after the ability is destroyed. You can define the data returned. This
* parameter can be null.
*/
void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &resultData)
{
if (ability_ == nullptr) {
APP_LOGE("AbilityImpl::SendResult ability_ is nullptr");
return;
}
if (resultData.HasParameter(OHOS_PERMISSIONS_REQUEST_RESULT_KEY) &&
resultData.HasParameter(OHOS_PERMISSIONS_REQUEST_KEY)) {
std::vector<int> grant_result = resultData.GetIntArrayParam(OHOS_PERMISSIONS_REQUEST_RESULT_KEY);
std::vector<std::string> permissions = resultData.GetStringArrayParam(OHOS_PERMISSIONS_REQUEST_KEY);
if (permissions.size() > 0 && permissions.size() == grant_result.size()) {
ability_->OnRequestPermissionsFromUserResult(requestCode, permissions, grant_result);
} else {
APP_LOGE("AbilityImpl::SendResult Grand failed, data error!");
}
} else {
ability_->OnAbilityResult(requestCode, resultCode, resultData);
}
}
/**
* @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch
* an ability that has been at the top of the ability stack.
*
* @param want Indicates the new Want containing information about the ability.
*/
void AbilityImpl::NewWant(const Want &want)
{
if (ability_ == nullptr) {
APP_LOGE("AbilityImpl::NewWant ability_ is nullptr");
return;
}
ability_->SetWant(want);
ability_->OnNewWant(want);
}
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> AbilityImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
std::vector<std::string> types;
return types;
}
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int AbilityImpl::OpenFile(const Uri &uri, const std::string &mode)
{
return -1;
}
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int AbilityImpl::OpenRawFile(const Uri &uri, const std::string &mode)
{
return -1;
}
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int AbilityImpl::Insert(const Uri &uri, const ValuesBucket &value)
{
return -1;
}
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int AbilityImpl::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
return -1;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int AbilityImpl::Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
return -1;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> AbilityImpl::Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
return nullptr;
}
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string AbilityImpl::GetType(const Uri &uri)
{
return "";
}
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool AbilityImpl::Reload(const Uri &uri, const PacMap &extras)
{
return false;
}
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int AbilityImpl::BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values)
{
return -1;
}
/**
* @brief SerUriString
*/
void AbilityImpl::SerUriString(const std::string &uri)
{
if (contextDeal_ == nullptr) {
APP_LOGE("AbilityImpl::SerUriString contextDeal_ is nullptr");
return;
}
contextDeal_->SerUriString(uri);
}
/**
* @brief Set deviceId/bundleName/abilityName of the calling ability
*
* @param deviceId deviceId of the calling ability
*
* @param deviceId bundleName of the calling ability
*
* @param deviceId abilityName of the calling ability
*/
void AbilityImpl::SetCallingContext(
const std::string &deviceId, const std::string &bundleName, const std::string &abilityName)
{
if (ability_ != nullptr) {
ability_->SetCallingContext(deviceId, bundleName, abilityName);
}
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,75 @@
/*
* Copyright (c) 2021 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 "ability_impl_factory.h"
#include "app_log_wrapper.h"
#include "data_ability_impl.h"
#include "page_ability_impl.h"
#include "service_ability_impl.h"
namespace OHOS {
namespace AppExecFwk {
/**
*
* default constructor
*
*/
AbilityImplFactory::AbilityImplFactory()
{}
/**
*
* default Destructor
*
*/
AbilityImplFactory::~AbilityImplFactory()
{}
/**
* @brief Create impl object based on abilitytype
*
* @param type AbilityType:PAGE/SERVICE/PROVIDER
*
* @return AbilityImpl object
*/
std::shared_ptr<AbilityImpl> AbilityImplFactory::MakeAbilityImplObject(const std::shared_ptr<AbilityInfo> &info)
{
if (info == nullptr) {
APP_LOGE("AbilityImplFactory::MakeAbilityImplObject is error nullptr == info ");
return nullptr;
}
std::shared_ptr<AbilityImpl> abilityImpl = nullptr;
APP_LOGI("AbilityImplFactory::MakeAbilityImplObject type:%{public}d", info->type);
switch (info->type) {
case AppExecFwk::AbilityType::PAGE:
abilityImpl = std::make_shared<PageAbilityImpl>();
break;
case AppExecFwk::AbilityType::SERVICE:
abilityImpl = std::make_shared<ServiceAbilityImpl>();
break;
case AppExecFwk::AbilityType::DATA:
abilityImpl = std::make_shared<DataAbilityImpl>();
break;
default:
APP_LOGE("AbilityImplFactory::MakeAbilityImplObject is error");
break;
}
return abilityImpl;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,170 @@
/*
* Copyright (c) 2021 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 "ability_lifecycle_observer_interface.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @brief Obtains the current lifecycle event.
* Lifecycle events drive lifecycle state changes. Therefore, you are able to know the lifecycle state
* once you obtain the lifecycle event. For example, if the ON_ACTIVE event is received, the ability or
* ability slice is in the ACTIVE state; if the ON_FOREGROUND event is received, the ability or ability
* slice is changing from the BACKGROUND state to INACTIVE.
*
* @return Returns the current lifecycle event.
*/
LifeCycle::Event LifeCycle::GetLifecycleState()
{
APP_LOGI("LifeCycle::GetLifecycleState: called");
return state_;
}
/**
* @brief Adds a lifecycle observer.
* The observer will be notified of lifecycle changes.
*
* @param observer Indicates the lifecycle observer, either LifecycleObserver or LifecycleStateObserver.
* The value cannot be null.
*
*/
void LifeCycle::AddObserver(const std::shared_ptr<ILifecycleObserver> &observer)
{
APP_LOGI("LifeCycle::AddObserver: called");
if (observer == nullptr) {
APP_LOGI("LifeCycle::AddObserver: observer is null");
return;
}
callbacks_.emplace_back(observer);
}
/**
* @brief While Ability's lifecycle changes, dispatch lifecycle event.
*
* @param event Lifecycle state.
* @param want Indicates the Want containing information about the target ability to change lifecycle state.
*/
void LifeCycle::DispatchLifecycle(const LifeCycle::Event &event, const Want &want)
{
APP_LOGI("LifeCycle::DispatchLifecycle: called");
if ((event != LifeCycle::Event::ON_FOREGROUND) && (event != LifeCycle::Event::ON_START)) {
APP_LOGE("event value error: event is %{public}d", event);
return;
}
state_ = event;
if (callbacks_.size() != 0) {
for (auto &callback : callbacks_) {
switch (event) {
case ON_FOREGROUND: {
if (callback != nullptr) {
callback->OnForeground(want);
}
break;
}
case ON_START: {
if (callback != nullptr) {
callback->OnStart(want);
}
break;
}
default:
break;
}
if (callback != nullptr) {
callback->OnStateChanged(event, want);
}
}
}
}
/**
* @brief While Ability's lifecycle changes, dispatch lifecycle event.
*
* @param event Lifecycle state.
*/
void LifeCycle::DispatchLifecycle(const LifeCycle::Event &event)
{
APP_LOGI("LifeCycle::DispatchLifecycle: called");
if ((event != LifeCycle::Event::ON_ACTIVE) && (event != LifeCycle::Event::ON_BACKGROUND) &&
(event != LifeCycle::Event::ON_INACTIVE) && (event != LifeCycle::Event::ON_STOP)) {
APP_LOGE("event value error: event is %{public}d", event);
return;
}
state_ = event;
if (callbacks_.size() != 0) {
for (auto &callback : callbacks_) {
switch (event) {
case ON_ACTIVE: {
if (callback != nullptr) {
callback->OnActive();
}
break;
}
case ON_BACKGROUND: {
if (callback != nullptr) {
callback->OnBackground();
}
break;
}
case ON_INACTIVE: {
if (callback != nullptr) {
callback->OnInactive();
}
break;
}
case ON_STOP: {
if (callback != nullptr) {
callback->OnStop();
}
break;
}
default:
break;
}
if (callback != nullptr) {
callback->OnStateChanged(event);
}
}
}
}
/**
* @brief Removes a lifecycle observer.
* You are advised to call this method if you no longer need to listen to lifecycle changes. This reduces the
* performance loss caused by observing lifecycle changes.
*
* @param observer Indicates the lifecycle observer, either LifecycleObserver or LifecycleStateObserver.
* The value cannot be null.
*/
void LifeCycle::RemoveObserver(const std::shared_ptr<ILifecycleObserver> &observer)
{
APP_LOGI("LifeCycle::RemoveObserver: called");
if (observer == nullptr) {
APP_LOGI("LifeCycle::RemoveObserver: observer is null");
return;
}
callbacks_.remove(observer);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 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 "ability_lifecycle_executor.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @brief While Ability's lifecycle changes, dispatch lifecycle state.
*
* @param state Lifecycle state.
*/
void AbilityLifecycleExecutor::DispatchLifecycleState(const AbilityLifecycleExecutor::LifecycleState &state)
{
state_ = state;
}
/**
* @brief Obtains the int value of the ability lifecycle state represented by the
* AbilityLifecycleExecutor.LifecycleState enum constant.
*
* @return return Returns the int value of the ability lifecycle state represented
* by the AbilityLifecycleExecutor.LifecycleState enum constant.
*/
int AbilityLifecycleExecutor::GetState()
{
return state_;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2021 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 "ability_lifecycle_observer.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @brief Called back in response to an ON_ACTIVE event.
* When an ON_ACTIVE event is received, the ability or ability slice is in the foreground and is interactive.
*/
void LifecycleObserver::OnActive()
{}
/**
* @brief Called back in response to an ON_BACKGROUND event.
* When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to
* suspend the threads related to this ability or ability slice and clear resources for more system memory.
*
*/
void LifecycleObserver::OnBackground()
{}
/**
* @brief Called back in response to an ON_FOREGROUND event, where information for the
* ability or ability slice to go back to the ACTIVE state is carried in the want parameter.
* When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use
* this method to implement re-initialization or adjust the UI display by using the want parameter.
*
* @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state.
*/
void LifecycleObserver::OnForeground(const Want &want)
{}
/**
* @brief Called back in response to an ON_INACTIVE event.
* When an ON_INACTIVE event is received, the ability or ability slice is in the INACTIVE state. INACTIVE is an
* intermediate state before the state changes to ACTIVE or BACKGROUND. In this state, the UI may be visible but is
* not interactive. You are advised not to use this method to invoke complex service logic.
*
*/
void LifecycleObserver::OnInactive()
{}
/**
* @brief Called back in response to an ON_START event, where the startup information
* is carried in the want parameter.
* This method initializes an Ability or AbilitySlice and is called back only once during the entire lifecycle.
* You are advised to implement some initialization logic using this method, for example, you can initialize a
* timer or define some global objects.
*
* @param want Indicates the startup information.
*/
void LifecycleObserver::OnStart(const Want &want)
{}
/**
* @brief Called back in response to an ON_STOP event.
* This method is called back when the lifecycle of the ability or ability slice is destroyed. You can reclaim
* resources using this method.
*
*/
void LifecycleObserver::OnStop()
{}
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
* @param want Indicates the state change information.
*/
void LifecycleObserver::OnStateChanged(Lifecycle::Event event, const Want &want)
{}
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
*/
virtual void LifecycleObserver::OnStateChanged(LifeCycle::Event event)
{}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,76 @@
/*
* Copyright (c) 2021 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 "ability_loader.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
AbilityLoader &AbilityLoader::GetInstance()
{
static AbilityLoader abilityLoader;
return abilityLoader;
}
/**
* @brief Register Ability Info
*
* @param abilityName ability classname
* @param createFunc Constructor address
*/
void AbilityLoader::RegisterAbility(const std::string &abilityName, const CreateAblity &createFunc)
{
abilities_.emplace(abilityName, createFunc);
APP_LOGD("AbilityLoader::RegisterAbility:%{public}s", abilityName.c_str());
}
/**
* @brief Get Ability address
*
* @param abilityName ability classname
*
* @return return Ability address
*/
Ability *AbilityLoader::GetAbilityByName(const std::string &abilityName)
{
auto it = abilities_.find(abilityName);
if (it != abilities_.end()) {
return it->second();
} else {
APP_LOGE("AbilityLoader::GetAbilityByName failed:%{public}s", abilityName.c_str());
}
return nullptr;
}
#ifdef ABILITY_WINDOW_SUPPORT
void AbilityLoader::RegisterAbilitySlice(const std::string &sliceName, const CreateSlice &createFunc)
{
slices_.emplace(sliceName, createFunc);
HILOG_INFO(HILOG_MODULE_APP, "RegisterAbilitySlice %s", sliceName.c_str());
}
AbilitySlice *AbilityLoader::GetAbilitySliceByName(const std::string &sliceName)
{
auto it = slices_.find(sliceName);
if (it != slices_.end()) {
return it->second();
} else {
HILOG_ERROR(HILOG_MODULE_APP, "GetAbilitySliceByName failed: %s", sliceName.c_str());
return nullptr;
}
}
#endif
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,136 @@
/*
* Copyright (c) 2021 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 "ability_local_record.h"
#include "ability_impl.h"
namespace OHOS {
namespace AppExecFwk {
/**
*
* default constructor
*
*/
AbilityLocalRecord::AbilityLocalRecord(const std::shared_ptr<AbilityInfo> &info, const sptr<IRemoteObject> &token)
: abilityInfo_(info), token_(token)
{}
/**
*
* @default Destructor
*
*/
AbilityLocalRecord::~AbilityLocalRecord()
{}
/**
* @description: Get an AbilityInfo in an ability.
*
* @return Returns a pointer to abilityinfo
*/
const std::shared_ptr<AbilityInfo> &AbilityLocalRecord::GetAbilityInfo()
{
return abilityInfo_;
}
/**
* @description: Get an EventHandler in an ability.
*
* @return Returns a pointer to EventHandler
*/
const std::shared_ptr<EventHandler> &AbilityLocalRecord::GetEventHandler()
{
return handler_;
}
/**
* @description: Set an EventHandler in an ability.
* @param handler EventHandler object
* @return None.
*/
void AbilityLocalRecord::SetEventHandler(const std::shared_ptr<EventHandler> &handler)
{
handler_ = handler;
}
/**
* @description: Get an EventRunner in an ability.
*
* @return Returns a pointer to EventRunner
*/
const std::shared_ptr<EventRunner> &AbilityLocalRecord::GetEventRunner()
{
return runner_;
}
/**
* @description: Set an EventRunner in an ability.
* @param runner EventHandler object
* @return None.
*/
void AbilityLocalRecord::SetEventRunner(const std::shared_ptr<EventRunner> &runner)
{
runner_ = runner;
}
/**
* @description: Gets the identity of the ability
* @return return the identity of the ability.
*/
const sptr<IRemoteObject> &AbilityLocalRecord::GetToken()
{
return token_;
}
/**
* @description: Get an AbilityImpl in an ability.
*
* @return Returns AbilityImpl pointer
*/
const std::shared_ptr<AbilityImpl> &AbilityLocalRecord::GetAbilityImpl()
{
return abilityImpl_;
}
/**
* @description: Set an AbilityImpl in an ability.
* @param abilityImpl AbilityImpl object
* @return None.
*/
void AbilityLocalRecord::SetAbilityImpl(const std::shared_ptr<AbilityImpl> &abilityImpl)
{
abilityImpl_ = abilityImpl;
}
/**
* @description: Obtains the information based on ability thread.
* @return return AbilityThread Pointer
*/
const sptr<AbilityThread> &AbilityLocalRecord::GetAbilityThread()
{
return abilityThread_;
}
/**
* @description: Set an AbilityThread in an ability.
* @param abilityThread AbilityThread object
* @return None.
*/
void AbilityLocalRecord::SetAbilityThread(const sptr<AbilityThread> &abilityThread)
{
abilityThread_ = abilityThread;
}
} // namespace AppExecFwk
} // namespace OHOS
+169
View File
@@ -0,0 +1,169 @@
/*
* Copyright (c) 2021 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 "ability_process.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
std::shared_ptr<AbilityProcess> AbilityProcess::instance_ = nullptr;
std::map<Ability *, std::map<int, CallbackInfo>> AbilityProcess::abilityResultMap_;
std::map<Ability *, std::map<int, CallbackInfo>> AbilityProcess::abilityRequestPermissionsForUserMap_;
std::mutex AbilityProcess::mutex_;
std::shared_ptr<AbilityProcess> AbilityProcess::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mutex_);
if (instance_ == nullptr) {
instance_ = std::make_shared<AbilityProcess>();
}
}
return instance_;
}
AbilityProcess::AbilityProcess()
{}
AbilityProcess::~AbilityProcess()
{}
void AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, CallbackInfo callback)
{
APP_LOGI("AbilityProcess::StartAbility called");
if (ability == nullptr) {
APP_LOGE("AbilityProcess::StartAbility ability is nullptr");
return;
}
if (param.forResultOption == true) {
if (param.setting == nullptr) {
ability->StartAbilityForResult(param.want, param.requestCode);
} else {
ability->StartAbilityForResult(param.want, param.requestCode, *(param.setting.get()));
}
std::lock_guard<std::mutex> lock_l(mutex_);
std::map<int, CallbackInfo> map;
auto it = abilityResultMap_.find(ability);
if (it == abilityResultMap_.end()) {
APP_LOGI("AbilityProcess::StartAbility ability: %{public}p is not in the abilityResultMap_", ability);
} else {
APP_LOGI("AbilityProcess::StartAbility ability: %{public}p is in the abilityResultMap_", ability);
map = it->second;
}
map[param.requestCode] = callback;
abilityResultMap_[ability] = map;
} else {
if (param.setting == nullptr) {
ability->StartAbility(param.want);
} else {
ability->StartAbility(param.want, *(param.setting.get()));
}
}
}
void AbilityProcess::OnAbilityResult(Ability *ability, int requestCode, int resultCode, const Want &resultData)
{
APP_LOGI("AbilityProcess::OnAbilityResult called");
std::lock_guard<std::mutex> lock_l(mutex_);
auto it = abilityResultMap_.find(ability);
if (it == abilityResultMap_.end()) {
APP_LOGE("AbilityProcess::OnAbilityResult ability: %{public}p is not in the abilityResultMap", ability);
return;
}
std::map<int, CallbackInfo> map = it->second;
auto callback = map.find(requestCode);
if (callback == map.end()) {
APP_LOGE("AbilityProcess::OnAbilityResult requestCode: %{public}d is not in the map", requestCode);
return;
}
CallbackInfo callbackInfo = callback->second;
CallOnAbilityResult(requestCode, resultCode, resultData, callbackInfo);
map.erase(requestCode);
abilityResultMap_[ability] = map;
}
void AbilityProcess::RequestPermissionsFromUser(
Ability *ability, CallAbilityPermissionParam &param, CallbackInfo callbackInfo)
{
APP_LOGI("AbilityProcess::RequestPermissionsFromUser called");
if (ability == nullptr) {
APP_LOGE("AbilityProcess::RequestPermissionsFromUser ability is nullptr");
return;
}
ability->RequestPermissionsFromUser(param.permission_list, param.requestCode);
{
std::lock_guard<std::mutex> lock_l(mutex_);
std::map<int, CallbackInfo> map;
auto it = abilityRequestPermissionsForUserMap_.find(ability);
if (it == abilityRequestPermissionsForUserMap_.end()) {
APP_LOGI("AbilityProcess::RequestPermissionsFromUser ability: %{public}p is not in the "
"abilityRequestPermissionsForUserMap_",
ability);
} else {
APP_LOGI("AbilityProcess::RequestPermissionsFromUser ability: %{public}p is in the "
"abilityRequestPermissionsForUserMap_",
ability);
map = it->second;
}
map[param.requestCode] = callbackInfo;
abilityRequestPermissionsForUserMap_[ability] = map;
}
}
void AbilityProcess::OnRequestPermissionsFromUserResult(Ability *ability, int requestCode,
const std::vector<std::string> &permissions, const std::vector<int> &grantResults)
{
if (ability == nullptr) {
APP_LOGE("AbilityProcess::OnRequestPermissionsFromUserResult ability is nullptr");
return;
}
std::lock_guard<std::mutex> lock_l(mutex_);
auto it = abilityRequestPermissionsForUserMap_.find(ability);
if (it == abilityRequestPermissionsForUserMap_.end()) {
APP_LOGE("AbilityProcess::OnRequestPermissionsFromUserResult ability: %{public}p is not in the "
"abilityRequestPermissionsForUserMap_",
ability);
return;
}
std::map<int, CallbackInfo> map = it->second;
auto callback = map.find(requestCode);
if (callback == map.end()) {
APP_LOGE("AbilityProcess::OnRequestPermissionsFromUserResult requestCode: %{public}d is not in the map",
requestCode);
return;
}
CallbackInfo callbackInfo = callback->second;
CallOnRequestPermissionsFromUserResult(requestCode, permissions, grantResults, callbackInfo);
map.erase(requestCode);
abilityRequestPermissionsForUserMap_[ability] = map;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,764 @@
/*
* Copyright (c) 2021 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 "ability_thread.h"
#include <functional>
#include "ohos_application.h"
#include "ability_loader.h"
#include "ability_state.h"
#include "ability_impl_factory.h"
#include "page_ability_impl.h"
#include "application_impl.h"
#include "app_log_wrapper.h"
#include "context_deal.h"
namespace OHOS {
namespace AppExecFwk {
using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient;
constexpr static char ACE_ABILITY_NAME[] = "AceAbility";
/**
* @brief Default constructor used to create a AbilityThread instance.
*/
AbilityThread::AbilityThread()
: abilityImpl_(nullptr), token_(nullptr), currentAbility_(nullptr), abilityHandler_(nullptr), runner_(nullptr)
{}
AbilityThread::~AbilityThread()
{
DelayedSingleton<AbilityImplFactory>::DestroyInstance();
}
/**
* @description: Attach The ability thread to the main process.
*
* @param abilityRecord Indicates the abilityRecord.
*
* @return Returns the abilityName.
*
*/
std::string AbilityThread::CreateAbilityName(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
{
std::string abilityName;
APP_LOGI("AbilityThread::CreateAbilityName called");
if (abilityRecord == nullptr) {
APP_LOGE("AbilityThread::CreateAbilityName failed,abilityRecord is nullptr");
return abilityName;
}
std::shared_ptr<AbilityInfo> abilityInfo = abilityRecord->GetAbilityInfo();
if (abilityInfo == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,abilityInfo is nullptr");
return abilityName;
}
bool isAceAbility = false;
APP_LOGI("AbilityThread::ability attach the ability type is %{public}d", abilityInfo->type);
APP_LOGI("AbilityThread::ability attach the ability is Native %{public}d", abilityInfo->isNativeAbility);
if ((abilityInfo->type == AbilityType::PAGE) && (abilityInfo->isNativeAbility == false)) {
APP_LOGI("AbilityThread::ability attach the ability is Ace");
isAceAbility = true;
}
abilityName = isAceAbility ? ACE_ABILITY_NAME : abilityInfo->name;
return abilityName;
}
/**
* @description: Create and init contextDeal.
*
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
* @param abilityObject Indicates the abilityObject.
*
* @return Returns the contextDeal.
*
*/
std::shared_ptr<ContextDeal> AbilityThread::CreateAndInitContextDeal(std::shared_ptr<OHOSApplication> &application,
const std::shared_ptr<AbilityLocalRecord> &abilityRecord, const std::shared_ptr<Context> &abilityObject)
{
std::shared_ptr<ContextDeal> contextDeal = nullptr;
APP_LOGI("AbilityThread::CreateAndInitContextDeal called");
if ((application == nullptr) || (abilityRecord == nullptr) || (abilityObject == nullptr)) {
APP_LOGE("AbilityThread::ability attach failed,context or record or abilityObject is nullptr");
return contextDeal;
}
contextDeal = std::make_shared<ContextDeal>();
if (contextDeal == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,contextDeal is nullptr");
return contextDeal;
}
contextDeal->SetAbilityInfo(abilityRecord->GetAbilityInfo());
contextDeal->SetApplicationInfo(application->GetApplicationInfo());
contextDeal->SetProcessInfo(application->GetProcessInfo());
std::shared_ptr<Context> tmpContext = application->GetApplicationContext();
contextDeal->SetApplicationContext(tmpContext);
contextDeal->SetBundleCodePath(abilityRecord->GetAbilityInfo()->codePath);
contextDeal->SetContext(abilityObject);
return contextDeal;
}
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
* @param mainRunner The runner which main_thread holds.
*/
void AbilityThread::Attach(std::shared_ptr<OHOSApplication> &application,
const std::shared_ptr<AbilityLocalRecord> &abilityRecord, const std::shared_ptr<EventRunner> &mainRunner)
{
APP_LOGI("AbilityThread:: attach begin");
if ((application == nullptr) || (abilityRecord == nullptr) || (mainRunner == nullptr)) {
APP_LOGE("AbilityThread::ability attach failed,context or record is nullptr");
return;
}
// 1.new AbilityHandler
std::string abilityName = CreateAbilityName(abilityRecord);
abilityHandler_ = std::make_shared<AbilityHandler>(mainRunner, this);
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,abilityHandler_ is nullptr");
return;
}
// 2.new ability
auto ability = AbilityLoader::GetInstance().GetAbilityByName(abilityName);
if (ability == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,load ability failed");
return;
}
APP_LOGI("AbilityThread::new ability success.");
std::shared_ptr<Context> abilityObject(ability);
currentAbility_.reset(ability);
token_ = abilityRecord->GetToken();
abilityRecord->SetEventHandler(abilityHandler_);
abilityRecord->SetEventRunner(mainRunner);
abilityRecord->SetAbilityThread(this);
std::shared_ptr<ContextDeal> contextDeal = CreateAndInitContextDeal(application, abilityRecord, abilityObject);
ability->AttachBaseContext(contextDeal);
// 3.new abilityImpl
abilityImpl_ =
DelayedSingleton<AbilityImplFactory>::GetInstance()->MakeAbilityImplObject(abilityRecord->GetAbilityInfo());
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::ability abilityImpl_ == nullptr");
return;
}
abilityImpl_->Init(application, abilityRecord, currentAbility_, abilityHandler_, token_, contextDeal);
// 4. ability attach : ipc
ErrCode err = AbilityManagerClient::GetInstance()->AttachAbilityThread(this, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread:: attach success faile err = %{public}d", err);
return;
}
APP_LOGI("AbilityThread:: attach success");
}
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
*/
void AbilityThread::Attach(
std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
{
APP_LOGI("AbilityThread:: attach begin");
if ((application == nullptr) || (abilityRecord == nullptr)) {
APP_LOGE("AbilityThread::ability attach failed,context or record is nullptr");
return;
}
// 1.new AbilityHandler
std::string abilityName = CreateAbilityName(abilityRecord);
runner_ = EventRunner::Create(abilityName);
if (runner_ == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,create runner failed");
return;
}
abilityHandler_ = std::make_shared<AbilityHandler>(runner_, this);
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,abilityHandler_ is nullptr");
return;
}
// 2.new ability
auto ability = AbilityLoader::GetInstance().GetAbilityByName(abilityName);
if (ability == nullptr) {
APP_LOGE("AbilityThread::ability attach failed,load ability failed");
return;
}
APP_LOGI("AbilityThread::new ability success.");
std::shared_ptr<Context> abilityObject(ability);
currentAbility_.reset(ability);
token_ = abilityRecord->GetToken();
abilityRecord->SetEventHandler(abilityHandler_);
abilityRecord->SetEventRunner(runner_);
abilityRecord->SetAbilityThread(this);
std::shared_ptr<ContextDeal> contextDeal = CreateAndInitContextDeal(application, abilityRecord, abilityObject);
ability->AttachBaseContext(contextDeal);
// 3.new abilityImpl
abilityImpl_ =
DelayedSingleton<AbilityImplFactory>::GetInstance()->MakeAbilityImplObject(abilityRecord->GetAbilityInfo());
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::ability abilityImpl_ == nullptr");
return;
}
abilityImpl_->Init(application, abilityRecord, currentAbility_, abilityHandler_, token_, contextDeal);
// 4. ability attach : ipc
ErrCode err = AbilityManagerClient::GetInstance()->AttachAbilityThread(this, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread:: attach success faile err = %{public}d", err);
return;
}
APP_LOGI("AbilityThread:: attach success");
}
/**
* @description: Handle the life cycle of Ability.
* @param want Indicates the structure containing lifecycle information about the ability.
* @param lifeCycleStateInfo Indicates the lifeCycleStateInfo.
*/
void AbilityThread::HandleAbilityTransaction(const Want &want, const LifeCycleStateInfo &lifeCycleStateInfo)
{
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::HandleAbilityTransaction abilityImpl_ == nullptr");
return;
}
abilityImpl_->SetCallingContext(lifeCycleStateInfo.caller.deviceId,
lifeCycleStateInfo.caller.bundleName,
lifeCycleStateInfo.caller.abilityName);
abilityImpl_->HandleAbilityTransaction(want, lifeCycleStateInfo);
}
/**
* @description: Handle the current connection of Ability.
* @param want Indicates the structure containing connection information about the ability.
*/
void AbilityThread::HandleConnectAbility(const Want &want)
{
APP_LOGI("AbilityThread::HandleConnectAbility called");
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::HandleConnectAbility abilityImpl_ == nullptr");
return;
}
sptr<IRemoteObject> service = abilityImpl_->ConnectAbility(want);
ErrCode err = AbilityManagerClient::GetInstance()->ScheduleConnectAbilityDone(token_, service);
if (err != ERR_OK) {
APP_LOGE("AbilityThread:: HandleConnectAbility faile err = %{public}d", err);
}
}
/**
* @description: Handle the current disconnection of Ability.
*/
void AbilityThread::HandleDisconnectAbility(const Want &want)
{
APP_LOGI("AbilityThread::HandleDisconnectAbility called");
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::HandleDisconnectAbility abilityImpl_ == nullptr");
return;
}
abilityImpl_->DisconnectAbility(want);
ErrCode err = AbilityManagerClient::GetInstance()->ScheduleDisconnectAbilityDone(token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread:: HandleDisconnectAbility faile err = %{public}d", err);
}
}
/**
* @brief Handle the current commadn of Ability.
*
* @param want The Want object to command to.
*
* * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
*
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented by 1
* every time the ability is started. For example, if the ability has been started for six times, the value of startId
* is 6.
*/
void AbilityThread::HandleCommandAbility(const Want &want, bool restart, int startId)
{
APP_LOGI("AbilityThread::HandleCommandAbility called");
abilityImpl_->CommandAbility(want, restart, startId);
ErrCode err = AbilityManagerClient::GetInstance()->ScheduleCommandAbilityDone(token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread:: HandleCommandAbility faile err = %{public}d", err);
}
}
/**
* @description: Handle the SaveAbility state.
* @param state Indicates save ability state used to dispatchSaveAbilityState.
*/
void AbilityThread::HandleSaveAbilityState(PacMap &state)
{
APP_LOGI("AbilityThread::HandleSaveAbilityState called");
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::HandleSaveAbilityState abilityImpl_ == nullptr");
return;
}
abilityImpl_->DispatchSaveAbilityState(state);
}
/**
* @description: Handle the restoreAbility state.
* @param state Indicates save ability state used to dispatchRestoreAbilityState.
*/
void AbilityThread::HandleRestoreAbilityState(const PacMap &state)
{
APP_LOGI("AbilityThread::HandleRestoreAbilityState called");
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::HandleRestoreAbilityState abilityImpl_ == nullptr");
return;
}
abilityImpl_->DispatchRestoreAbilityState(state);
}
/**
* @description: Provide operating system SaveabilityState information to the observer
* @param state Indicates save ability state used to dispatch.
*/
void AbilityThread::ScheduleSaveAbilityState(PacMap &state)
{
APP_LOGI("AbilityThread::ScheduleSaveAbilityState called");
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleSaveAbilityState abilityImpl_ == nullptr");
return;
}
auto task = [abilityThread = this, &state]() { abilityThread->HandleSaveAbilityState(state); };
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleSaveAbilityState abilityHandler_ == nullptr");
return;
}
bool ret = abilityHandler_->PostTask(task);
if (!ret) {
APP_LOGE("AbilityThread::ScheduleSaveAbilityState PostTask error");
}
}
/**
* @description: Provide operating system RestoreAbilityState information to the observer
* @param state Indicates resotre ability state used to dispatchRestoreAbilityState.
*/
void AbilityThread::ScheduleRestoreAbilityState(const PacMap &state)
{
APP_LOGI("AbilityThread::ScheduleRestoreAbilityState called");
if (abilityImpl_ == nullptr) {
APP_LOGE("ScheduleRestoreAbilityState::failed");
return;
}
auto task = [abilityThread = this, state]() { abilityThread->HandleRestoreAbilityState(state); };
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleRestoreAbilityState abilityHandler_ == nullptr");
return;
}
bool ret = abilityHandler_->PostTask(task);
if (!ret) {
APP_LOGE("AbilityThread::ScheduleRestoreAbilityState PostTask error");
}
}
/**
* @description: Provide operating system AbilityTransaction information to the observer
* @param want Indicates the structure containing Transaction information about the ability.
* @param lifeCycleStateInfo Indicates the lifecycle state.
*/
void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycleStateInfo &lifeCycleStateInfo)
{
APP_LOGI("ScheduleAbilityTransaction::enter, targeState = %{public}d, isNewWant = %{public}d",
lifeCycleStateInfo.state,
lifeCycleStateInfo.isNewWant);
if ((token_ == nullptr) || abilityImpl_ == nullptr) {
APP_LOGE("ScheduleAbilityTransaction::failed");
return;
}
auto task = [abilityThread = this, want, lifeCycleStateInfo]() {
abilityThread->HandleAbilityTransaction(want, lifeCycleStateInfo);
};
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleAbilityTransaction abilityHandler_ == nullptr");
return;
}
bool ret = abilityHandler_->PostTask(task);
if (!ret) {
APP_LOGE("AbilityThread::ScheduleAbilityTransaction PostTask error");
}
}
/**
* @description: Provide operating system ConnectAbility information to the observer
* @param want Indicates the structure containing connect information about the ability.
*/
void AbilityThread::ScheduleConnectAbility(const Want &want)
{
APP_LOGI("AbilityThread::ScheduleConnectAbility called");
auto task = [abilityThread = this, want]() { abilityThread->HandleConnectAbility(want); };
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleConnectAbility abilityHandler_ == nullptr");
return;
}
bool ret = abilityHandler_->PostTask(task);
if (!ret) {
APP_LOGE("AbilityThread::ScheduleConnectAbility PostTask error");
}
}
/**
* @description: Provide operating system ConnectAbility information to the observer
* @return None
*/
void AbilityThread::ScheduleDisconnectAbility(const Want &want)
{
APP_LOGI("AbilityThread::ScheduleDisconnectAbility called");
auto task = [abilityThread = this, want]() { abilityThread->HandleDisconnectAbility(want); };
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleDisconnectAbility abilityHandler_ == nullptr");
return;
}
bool ret = abilityHandler_->PostTask(task);
if (!ret) {
APP_LOGE("AbilityThread::ScheduleDisconnectAbility PostTask error");
}
}
/**
* @description: Provide operating system CommandAbility information to the observer
*
* @param want The Want object to command to.
*
* * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being
* destroyed, and the value false indicates a normal startup.
*
* @param startId Indicates the number of times the Service ability has been started. The startId is incremented by 1
* every time the ability is started. For example, if the ability has been started for six times, the value of startId
* is 6.
*/
void AbilityThread::ScheduleCommandAbility(const Want &want, bool restart, int startId)
{
APP_LOGI("AbilityThread::ScheduleCommandAbility called");
auto task = [abilityThread = this, want, restart, startId]() {
abilityThread->HandleCommandAbility(want, restart, startId);
};
if (abilityHandler_ == nullptr) {
APP_LOGE("AbilityThread::ScheduleCommandAbility abilityHandler_ == nullptr");
return;
}
bool ret = abilityHandler_->PostTask(task);
if (!ret) {
APP_LOGE("AbilityThread::ScheduleCommandAbility PostTask error");
}
}
/**
* @brief Send the result code and data to be returned by this Page ability to the caller.
* When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to
* receive the result set in the current method. This method can be called only after the ability has been initialized.
*
* @param requestCode Indicates the request code for send.
* @param resultCode Indicates the result code returned after the ability is destroyed. You can define the result code
* to identify an error.
* @param want Indicates the data returned after the ability is destroyed. You can define the data returned. This
* parameter can be null.
*/
void AbilityThread::SendResult(int requestCode, int resultCode, const Want &want)
{
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::SendResult abilityImpl_ == nullptr");
return;
}
if (requestCode != -1) {
abilityImpl_->SendResult(requestCode, resultCode, want);
}
}
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> AbilityThread::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
std::vector<std::string> types;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::GetFileTypes abilityImpl_ is nullptr");
return types;
}
types = abilityImpl_->GetFileTypes(uri, mimeTypeFilter);
return types;
}
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int AbilityThread::OpenFile(const Uri &uri, const std::string &mode)
{
int fd = -1;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::OpenFile abilityImpl_ is nullptr");
return fd;
}
fd = abilityImpl_->OpenFile(uri, mode);
return fd;
}
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int AbilityThread::OpenRawFile(const Uri &uri, const std::string &mode)
{
int fd = -1;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::OpenRawFile abilityImpl_ is nullptr");
return fd;
}
fd = abilityImpl_->OpenRawFile(uri, mode);
return fd;
}
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int AbilityThread::Insert(const Uri &uri, const ValuesBucket &value)
{
int index = -1;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::Insert abilityImpl_ is nullptr");
return index;
}
index = abilityImpl_->Insert(uri, value);
return index;
}
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int AbilityThread::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
int index = -1;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::Update abilityImpl_ is nullptr");
return index;
}
index = abilityImpl_->Update(uri, value, predicates);
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int AbilityThread::Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
int index = -1;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::Delete abilityImpl_ is nullptr");
return index;
}
index = abilityImpl_->Delete(uri, predicates);
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> AbilityThread::Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
std::shared_ptr<ResultSet> resultSet = nullptr;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::Query abilityImpl_ is nullptr");
return resultSet;
}
resultSet = abilityImpl_->Query(uri, columns, predicates);
return resultSet;
}
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string AbilityThread::GetType(const Uri &uri)
{
std::string type;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::GetType abilityImpl_ is nullptr");
return type;
}
type = abilityImpl_->GetType(uri);
return type;
}
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool AbilityThread::Reload(const Uri &uri, const PacMap &extras)
{
bool ret = false;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::Reload abilityImpl_ is nullptr");
return ret;
}
ret = abilityImpl_->Reload(uri, extras);
return ret;
}
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int AbilityThread::BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values)
{
int ret = -1;
if (abilityImpl_ == nullptr) {
APP_LOGE("AbilityThread::BatchInsert abilityImpl_ is nullptr");
return ret;
}
ret = abilityImpl_->BatchInsert(uri, values);
return ret;
}
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
* @param mainRunner The runner which main_thread holds.
*/
void AbilityThread::AbilityThreadMain(std::shared_ptr<OHOSApplication> &application,
const std::shared_ptr<AbilityLocalRecord> &abilityRecord, const std::shared_ptr<EventRunner> &mainRunner)
{
APP_LOGI("AbilityThread::AbilityThreadMain::begin");
sptr<AbilityThread> thread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
if (thread == nullptr) {
APP_LOGE("AbilityThread::AbilityThreadMain failed,thread is nullptr");
return;
}
thread->Attach(application, abilityRecord, mainRunner);
}
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
* @param abilityRecord Indicates the abilityRecord.
*/
void AbilityThread::AbilityThreadMain(
std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
{
APP_LOGI("AbilityThread::AbilityThreadMain::begin");
sptr<AbilityThread> thread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
if (thread == nullptr) {
APP_LOGE("AbilityThread::AbilityThreadMain failed,thread is nullptr");
return;
}
thread->Attach(application, abilityRecord);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,274 @@
/*
* Copyright (c) 2021 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 "ability_window.h"
#include "ability.h"
#include "ability_handler.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
AbilityWindow::AbilityWindow()
{}
AbilityWindow::~AbilityWindow()
{}
#ifdef WMS_COMPILE
/**
* @brief Init the AbilityWindow object.
*
* @param handler The EventHandler of the Ability the AbilityWindow belong.
*/
void AbilityWindow::Init(std::shared_ptr<AbilityHandler> &handler, std::shared_ptr<Ability> ability)
{
APP_LOGI("AbilityWindow::Init called.");
handler_ = handler;
ability_ = std::weak_ptr<IAbilityEvent>(ability);
}
/**
* @brief Sets the window config for the host ability to create window.
*
* @param config Indicates window config.
*/
bool AbilityWindow::SetWindowConfig(const WindowConfig &config)
{
APP_LOGI("AbilityWindow::SetWindowConfig called.");
APP_LOGI("config format = %{public}d, width = %{public}d, height = %{public}d.",
config.format,
config.width,
config.height);
APP_LOGI("config pos_x = %{public}d, pos_y = %{public}d, stride = %{public}d, type = %{public}d.",
config.pos_x,
config.pos_y,
config.stride,
config.type);
window_ = (WindowManager::GetInstance()->CreateWindow(const_cast<WindowConfig *>(&config)));
if (window_.get() == nullptr) {
APP_LOGE("AbilityWindow::SetWindowConfig the window is nullptr.");
return false;
}
auto callback = [abilityWindow = this](KeyEvent event) -> bool { return abilityWindow->OnKeyEvent(event); };
window_->RegistOnKeyCb(callback);
isWindowAttached = true;
APP_LOGI("AbilityWindow::SetWindowConfig end.");
return true;
}
/**
* @brief Called when the KeyEvent sent.
*
* @param KeyEvent the key event.
*
* @return Returns true if the listener has processed the event; returns false otherwise.
*
*/
bool AbilityWindow::OnKeyEvent(KeyEvent event)
{
APP_LOGI("AbilityWindow::OnKeyEvent called.");
bool ret = false;
std::shared_ptr<IAbilityEvent> ability = nullptr;
ability = ability_.lock();
if (ability == nullptr) {
APP_LOGE("AbilityWindow::OnKeyEvent ability is nullptr.");
return ret;
}
switch (event.GetKeyCode()) {
case KeyEvent::CODE_BACK:
APP_LOGI("AbilityWindow::OnKeyEvent Back key pressed.");
ret = OnBackPressed(ability);
break;
default:
APP_LOGI("AbilityWindow::OnKeyEvent the key event is %{public}d.", event.GetKeyCode());
break;
}
return ret;
}
/**
* @brief Called back when the Back key is pressed.
*
* @param ability The ability receive the event.
*
* @return Returns true if the listener has processed the event; returns false otherwise.
*
*/
bool AbilityWindow::OnBackPressed(std::shared_ptr<IAbilityEvent> &ability)
{
APP_LOGI("AbilityWindow::OnBackPressed called.");
if (handler_ == nullptr) {
APP_LOGE("AbilityWindow::OnBackPressed handler_ is nullptr.");
return false;
}
auto task = [abilityRun = ability]() { abilityRun->OnBackPressed(); };
handler_->PostTask(task);
return true;
}
#endif // WMS_COMPILE
/**
* @brief Called when this ability is started.
*
*/
void AbilityWindow::OnPostAbilityStart()
{
APP_LOGI("AbilityWindow::OnPostAbilityStart called.");
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::OnPostAbilityStart window not attached.");
return;
}
#ifdef WMS_COMPILE
if (window_ != nullptr) {
APP_LOGI("AbilityWindow::widow::Hide called.");
window_->Hide();
}
#endif // WMS_COMPILE
APP_LOGI("AbilityWindow::OnPostAbilityStart end.");
}
/**
* @brief Called when this ability is activated.
*
*/
void AbilityWindow::OnPostAbilityActive()
{
APP_LOGI("AbilityWindow::OnPostAbilityActive called.");
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::OnPostAbilityActive window not attached.");
return;
}
#ifdef WMS_COMPILE
if (window_ != nullptr) {
APP_LOGI("AbilityWindow::widow::SwitchTop called.");
window_->SwitchTop();
APP_LOGI("AbilityWindow::widow::Show called.");
window_->Show();
}
#endif // WMS_COMPILE
APP_LOGI("AbilityWindow::OnPostAbilityActive end.");
}
/**
* @brief Called when this ability is inactivated.
*
*/
void AbilityWindow::OnPostAbilityInactive()
{
APP_LOGI("AbilityWindow::OnPostAbilityInactive called.");
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::OnPostAbilityInactive window not attached.");
return;
}
#ifdef WMS_COMPILE
if (window_ != nullptr) {
APP_LOGI("AbilityWindow::widow::Hide called.");
window_->Hide();
}
#endif // WMS_COMPILE
APP_LOGI("AbilityWindow::OnPostAbilityInactive end.");
}
/**
* @brief Called when this ability is background.
*
*/
void AbilityWindow::OnPostAbilityBackground()
{
APP_LOGI("AbilityWindow::OnPostAbilityBackground called.");
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::OnPostAbilityBackground window not attached.");
return;
}
#ifdef WMS_COMPILE
if (window_ != nullptr) {
APP_LOGI("AbilityWindow::widow::Hide called.");
window_->Hide();
}
#endif // WMS_COMPILE
APP_LOGI("AbilityWindow::OnPostAbilityBackground end.");
}
/**
* @brief Called when this ability is foreground.
*
*/
void AbilityWindow::OnPostAbilityForeground()
{
APP_LOGI("AbilityWindow::OnPostAbilityForeground called.");
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::OnPostAbilityForeground window not attached.");
return;
}
#ifdef WMS_COMPILE
if (window_ != nullptr) {
APP_LOGI("AbilityWindow::widow::Show called.");
window_->Show();
}
#endif // WMS_COMPILE
APP_LOGI("AbilityWindow::OnPostAbilityForeground end.");
}
/**
* @brief Called when this ability is stopped.
*
*/
void AbilityWindow::OnPostAbilityStop()
{
APP_LOGI("AbilityWindow::OnPostAbilityStop called.");
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::OnPostAbilityStop window not attached.");
return;
}
#ifdef WMS_COMPILE
if (window_ != nullptr) {
int32_t windowID = window_->GetWindowID();
APP_LOGI("AbilityWindow::widow::DestroyWindow called windowID=%{public}d.", windowID);
WindowManager::GetInstance()->DestroyWindow(windowID);
}
#endif // WMS_COMPILE
isWindowAttached = false;
APP_LOGI("AbilityWindow::OnPostAbilityStop end.");
}
#ifdef WMS_COMPILE
/**
* @brief Get the window belong to the ability.
*
* @return Returns a Window object pointer.
*/
const std::unique_ptr<Window> &AbilityWindow::GetWindow()
{
if (!isWindowAttached) {
APP_LOGE("AbilityWindow::GetWindow window not attached.");
}
if (window_.get() == nullptr) {
APP_LOGE("AbilityWindow::GetWindow the window is nullptr.");
}
return window_;
}
#endif // WMS_COMPILE
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,512 @@
/*
* Copyright (c) 2021 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 "data_ability_helper.h"
#include "ability_thread.h"
#include "ability_scheduler_interface.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
std::string SchemeOhos = "dataability";
using IAbilityScheduler = OHOS::AAFwk::IAbilityScheduler;
using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient;
DataAbilityHelper::DataAbilityHelper(const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri,
const sptr<IAbilityScheduler> &dataAbilityProxy, bool tryBind)
{
token_ = context->GetToken();
context_ = std::weak_ptr<Context>(context);
uri_ = uri;
tryBind_ = tryBind;
dataAbilityProxy_ = dataAbilityProxy;
}
DataAbilityHelper::DataAbilityHelper(const std::shared_ptr<Context> &context)
{
token_ = context->GetToken();
context_ = std::weak_ptr<Context>(context);
}
/**
* @brief Creates a DataAbilityHelper instance without specifying the Uri based on the given Context.
*
* @param context Indicates the Context object on OHOS.
*
* @return Returns the created DataAbilityHelper instance where Uri is not specified.
*/
std::shared_ptr<DataAbilityHelper> DataAbilityHelper::Creator(const std::shared_ptr<Context> &context)
{
if (context == nullptr) {
APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, context == nullptr");
return nullptr;
}
DataAbilityHelper *ptrDataAbilityHelper = new (std::nothrow) DataAbilityHelper(context);
if (ptrDataAbilityHelper == nullptr) {
APP_LOGE("DataAbilityHelper::Creator (context) failed, create DataAbilityHelper failed");
return nullptr;
}
return std::shared_ptr<DataAbilityHelper>(ptrDataAbilityHelper);
}
/**
* @brief Creates a DataAbilityHelper instance with the Uri specified based on the given Context.
*
* @param context Indicates the Context object on OHOS.
* @param uri Indicates the database table or disk file to operate.
*
* @return Returns the created DataAbilityHelper instance with a specified Uri.
*/
std::shared_ptr<DataAbilityHelper> DataAbilityHelper::Creator(
const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri)
{
return DataAbilityHelper::Creator(context, uri, false);
}
/**
* @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
* between the ability using the Data template (Data ability for short) and the associated client process in
* a DataAbilityHelper instance.
*
* @param context Indicates the Context object on OHOS.
* @param uri Indicates the database table or disk file to operate.
* @param tryBind Specifies whether the exit of the corresponding Data ability process causes the exit of the
* client process.
*
* @return Returns the created DataAbilityHelper instance.
*/
std::shared_ptr<DataAbilityHelper> DataAbilityHelper::Creator(
const std::shared_ptr<Context> &context, const std::shared_ptr<Uri> &uri, const bool tryBind)
{
if (context == nullptr) {
APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, context == nullptr");
return nullptr;
}
if (uri == nullptr) {
APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, uri == nullptr");
return nullptr;
}
if (uri->GetScheme() != SchemeOhos) {
APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, the Scheme is not dataability, Scheme: "
"%{public}s",
uri->GetScheme().c_str());
return nullptr;
}
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), tryBind, context->GetToken());
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::Creator failed get dataAbilityProxy");
return nullptr;
}
DataAbilityHelper *ptrDataAbilityHelper =
new (std::nothrow) DataAbilityHelper(context, uri, dataAbilityProxy, tryBind);
if (ptrDataAbilityHelper == nullptr) {
APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, create DataAbilityHelper failed");
return nullptr;
}
return std::shared_ptr<DataAbilityHelper>(ptrDataAbilityHelper);
}
/**
* @brief Releases the client resource of the Data ability.
* You should call this method to releases client resource after the data operations are complete.
*
* @return Returns true if the resource is successfully released; returns false otherwise.
*/
bool DataAbilityHelper::Release()
{
if (uri_ == nullptr) {
APP_LOGE("DataAbilityHelper::Release failed, uri_ is nullptr");
return false;
}
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_);
if (err != ERR_OK) {
APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err);
return false;
}
return true;
}
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> DataAbilityHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter)
{
std::vector<std::string> matchedMIMEs;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::GetFileTypes failed dataAbility == nullptr");
return matchedMIMEs;
}
matchedMIMEs = dataAbilityProxy->GetFileTypes(uri, mimeTypeFilter);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
matchedMIMEs = dataAbilityProxy_->GetFileTypes(uri, mimeTypeFilter);
}
}
return matchedMIMEs;
}
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int DataAbilityHelper::OpenFile(Uri &uri, const std::string &mode)
{
int fd = -1;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::OpenFile failed dataAbility == nullptr");
return fd;
}
fd = dataAbilityProxy->OpenFile(uri, mode);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::OpenFile failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
fd = dataAbilityProxy_->OpenFile(uri, mode);
}
}
return fd;
}
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int DataAbilityHelper::OpenRawFile(Uri &uri, const std::string &mode)
{
int fd = -1;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<AAFwk::IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::OpenRawFile failed dataAbility == nullptr");
return fd;
}
fd = dataAbilityProxy->OpenRawFile(uri, mode);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::OpenRawFile failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
fd = dataAbilityProxy_->OpenRawFile(uri, mode);
}
}
return fd;
}
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int DataAbilityHelper::Insert(Uri &uri, const ValuesBucket &value)
{
int index = -1;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::Insert failed dataAbility == nullptr");
return index;
}
index = dataAbilityProxy->Insert(uri, value);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::Insert failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
index = dataAbilityProxy_->Insert(uri, value);
}
}
return index;
}
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int DataAbilityHelper::Update(Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
int index = -1;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::Insert failed dataAbility == nullptr");
return index;
}
index = dataAbilityProxy->Update(uri, value, predicates);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::Insert failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
index = dataAbilityProxy_->Update(uri, value, predicates);
}
}
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int DataAbilityHelper::Delete(Uri &uri, const DataAbilityPredicates &predicates)
{
int index = -1;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::Delete failed dataAbility == nullptr");
return index;
}
index = dataAbilityProxy->Delete(uri, predicates);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::Delete failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
index = dataAbilityProxy_->Delete(uri, predicates);
}
}
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> DataAbilityHelper::Query(
Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
std::shared_ptr<ResultSet> resultset = nullptr;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::Query failed dataAbility == nullptr");
return resultset;
}
resultset = dataAbilityProxy->Query(uri, columns, predicates);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::Query failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
resultset = dataAbilityProxy_->Query(uri, columns, predicates);
}
}
return resultset;
}
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string DataAbilityHelper::GetType(Uri &uri)
{
std::string type;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::GetType failed dataAbility == nullptr");
return type;
}
type = dataAbilityProxy->GetType(uri);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::GetType failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
type = dataAbilityProxy_->GetType(uri);
}
}
return type;
}
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool DataAbilityHelper::Reload(Uri &uri, const PacMap &extras)
{
bool ret = false;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<AAFwk::IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::Reload failed dataAbility == nullptr");
return ret;
}
ret = dataAbilityProxy->Reload(uri, extras);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::Reload failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
ret = dataAbilityProxy_->Reload(uri, extras);
}
}
return ret;
}
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int DataAbilityHelper::BatchInsert(Uri &uri, const std::vector<ValuesBucket> &values)
{
int ret = -1;
if ((uri_ == nullptr) || (!uri_->Equals(uri))) {
if (uri.GetScheme() == SchemeOhos) {
sptr<AAFwk::IAbilityScheduler> dataAbilityProxy =
AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_);
if (dataAbilityProxy == nullptr) {
APP_LOGE("DataAbilityHelper::BatchInsert failed dataAbility == nullptr");
return ret;
}
ret = dataAbilityProxy->BatchInsert(uri, values);
int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_);
if (err != ERR_OK) {
APP_LOGE("AbilityThread::BatchInsert failed to ReleaseDataAbility err = %{public}d", err);
}
}
} else {
if (dataAbilityProxy_ != nullptr) {
ret = dataAbilityProxy_->BatchInsert(uri, values);
}
}
return ret;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,270 @@
/*
* Copyright (c) 2021 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 "data_ability_impl.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient;
/**
* @brief Handling the life cycle switching of PageAbility.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
*/
void DataAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{
APP_LOGI("DataAbilityImpl::sourceState:%{public}d; targetState: %{public}d; isNewWant: %{public}d",
lifecycleState_,
targetState.state,
targetState.isNewWant);
if ((lifecycleState_ == targetState.state) && !targetState.isNewWant) {
APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState.");
return;
}
switch (targetState.state) {
case AAFwk::ABILITY_STATE_ACTIVE: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_INITIAL) {
SerUriString(targetState.caller.deviceId + "/" + targetState.caller.bundleName + "/" +
targetState.caller.abilityName);
Start(want);
} else {
return;
}
break;
}
default: {
APP_LOGE("DataAbilityImpl::HandleAbilityTransaction state is error");
return;
break;
}
}
AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, targetState.state);
}
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> DataAbilityImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
std::vector<std::string> types;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::GetFileTypes ability_ is nullptr");
return types;
}
types = ability_->GetFileTypes(uri, mimeTypeFilter);
return types;
}
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int DataAbilityImpl::OpenFile(const Uri &uri, const std::string &mode)
{
int fd = -1;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::OpenFile ability_ is nullptr");
return fd;
}
fd = ability_->OpenFile(uri, mode);
return fd;
}
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int DataAbilityImpl::OpenRawFile(const Uri &uri, const std::string &mode)
{
int fd = -1;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::OpenRawFile ability_ is nullptr");
return fd;
}
fd = ability_->OpenRawFile(uri, mode);
return fd;
}
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int DataAbilityImpl::Insert(const Uri &uri, const ValuesBucket &value)
{
int index = -1;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::Insert ability_ is nullptr");
return index;
}
index = ability_->Insert(uri, value);
return index;
}
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param value Indicates the data to update. This parameter can be null.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records updated.
*/
int DataAbilityImpl::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
int index = -1;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::Update ability_ is nullptr");
return index;
}
index = ability_->Update(uri, value, predicates);
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int DataAbilityImpl::Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
int index = -1;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::Delete ability_ is nullptr");
return index;
}
index = ability_->Delete(uri, predicates);
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the query result.
*/
std::shared_ptr<ResultSet> DataAbilityImpl::Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
std::shared_ptr<ResultSet> resultSet = nullptr;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::Query ability_ is nullptr");
return resultSet;
}
resultSet = ability_->Query(uri, columns, predicates);
return resultSet;
}
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string DataAbilityImpl::GetType(const Uri &uri)
{
std::string type;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::GetType ability_ is nullptr");
return type;
}
type = ability_->GetType(uri);
return type;
}
/**
* @brief Reloads data in the database.
*
* @param uri Indicates the position where the data is to reload. This parameter is mandatory.
* @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This
* parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across
* processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object.
*
* @return Returns true if the data is successfully reloaded; returns false otherwise.
*/
bool DataAbilityImpl::Reload(const Uri &uri, const PacMap &extras)
{
bool ret = false;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::Reload ability_ is nullptr");
return ret;
}
ret = ability_->Reload(uri, extras);
return ret;
}
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int DataAbilityImpl::BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values)
{
int ret = -1;
if (ability_ == nullptr) {
APP_LOGE("DataAbilityImpl::BatchInsert ability_ is nullptr");
return ret;
}
ret = ability_->BatchInsert(uri, values);
return ret;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,219 @@
/*
* Copyright (c) 2021 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 "data_uri_utils.h"
#include <vector>
#include <memory>
#include <regex>
#include "securec.h"
namespace OHOS {
namespace AppExecFwk {
namespace {
const string EMPTY = "";
const std::regex INTEGER_REGEX("^[0-9]+$");
const int BUFFER_LEN = 32;
const char *SEPARATOR = "/";
}; // namespace
/**
* @brief Default constructor of DataUriUtils class
* @return None
*/
DataUriUtils::DataUriUtils()
{}
/**
* @brief Default deconstructor of DataUriUtils class
* @return None
*/
DataUriUtils::~DataUriUtils()
{}
/**
* @brief Attaches the given ID to the end of the path component of the given URI.
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @param id
* @return Uri( scheme://authority/path1/path2/path3/updateIDNumber....)
*/
Uri DataUriUtils::AttachId(const Uri &dataUri, long id)
{
// 1. get Path
string path = const_cast<Uri &>(dataUri).GetPath();
if (path.empty()) {
return dataUri;
}
string uriString = dataUri.ToString();
std::vector<string> pathVector;
const_cast<Uri &>(dataUri).GetPathSegments(pathVector);
if (pathVector.empty()) {
return dataUri;
}
string lastPath = pathVector[pathVector.size() - 1];
char longBuffer[BUFFER_LEN] = {0};
int ret = sprintf_s(longBuffer, sizeof(longBuffer), "%ld", id);
if (ret == -1) {
return dataUri;
}
// new path string (lastPath+SEPARATOR+number)
string newLastPath("");
newLastPath = lastPath + string(SEPARATOR) + string(longBuffer);
// find "/+lastPath"
string tempLastPath = string(SEPARATOR) + lastPath;
auto lastPathPos = uriString.rfind(tempLastPath);
uriString.replace(lastPathPos + 1, tempLastPath.size() - 1, newLastPath.c_str());
return Uri(uriString);
}
/**
* @brief Obtains the ID attached to the end of the path component of the given URI.
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @return long ID
*/
long DataUriUtils::GetId(const Uri &dataUri)
{
// 1. get Path
string path = const_cast<Uri &>(dataUri).GetPath();
if (path.empty()) {
return -1;
}
std::vector<string> pathVector;
const_cast<Uri &>(dataUri).GetPathSegments(pathVector);
if (pathVector.empty()) {
return -1;
}
string lastPath = pathVector[pathVector.size() - 1];
if (!IsNumber(lastPath)) {
return -1;
}
return atoi(lastPath.c_str());
}
/**
* @brief Deletes the ID from the end of the path component of the given URI.
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @return long ID
*/
Uri DataUriUtils::DeleteId(const Uri &dataUri)
{
return UriUpateLastPath(dataUri, EMPTY);
}
/**
* @brief Updates the ID in the specified dataUri
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @param id indiates Update attached to the end of the path component of the given URI
* @return Uri return is the URI after path is updated
*/
Uri DataUriUtils::UpdateId(const Uri &dataUri, long id)
{
char longBuffer[BUFFER_LEN] = {0};
int ret = sprintf_s(longBuffer, sizeof(longBuffer), "%ld", id);
if (ret == -1) {
return dataUri;
}
string newLastPath("");
newLastPath = string(longBuffer);
return UriUpateLastPath(dataUri, newLastPath);
}
/**
* @brief Does the end path of the path component of the given URI have an ID attached to it?
* @param dataUri based on RFC 2396( Uniform Resource Identifier ).
* @return bool
*/
bool DataUriUtils::IsAttachedId(const Uri &dataUri)
{
// 1. get Path
string path = const_cast<Uri &>(dataUri).GetPath();
if (path.empty()) {
return false;
}
std::vector<string> pathVector;
const_cast<Uri &>(dataUri).GetPathSegments(pathVector);
if (pathVector.empty()) {
return false;
}
string lastPath = pathVector[pathVector.size() - 1];
return IsNumber(lastPath);
}
/**
* @brief Determine whether the string content is a numeric string
* @param str indicates stirng.
* @return bool
*/
bool DataUriUtils::IsNumber(const string &str)
{
return std::regex_match(str, INTEGER_REGEX);
}
/**
* @brief Determine whether the string content is a numeric string
* @param dataUri indicates Uri object
scheme://authority/path/aaa?query/#fragment
* @return Uri return is the URI after path is updated
*/
Uri DataUriUtils::UriUpateLastPath(const Uri &dataUri, const string &updateLastPath)
{
std::string strUpdateLastPath;
if (updateLastPath.size() > 0) {
strUpdateLastPath = SEPARATOR + updateLastPath;
}
// 1. get Path
string path = const_cast<Uri &>(dataUri).GetPath();
if (path.empty()) {
return dataUri;
}
std::vector<string> pathVector;
const_cast<Uri &>(dataUri).GetPathSegments(pathVector);
if (pathVector.empty()) {
return dataUri;
}
string lastPath = pathVector[pathVector.size() - 1];
if (!IsNumber(lastPath)) {
return dataUri;
}
string uriString = dataUri.ToString();
// find "/+lastPath"
int lastPathPos = uriString.rfind(string(SEPARATOR) + lastPath);
if (lastPathPos == -1) {
return dataUri;
}
// replace "/lastpath"==>""
uriString.replace(lastPathPos, lastPath.size() + 1, strUpdateLastPath);
return Uri(uriString);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 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 "dummy_data_ability_predicates.h"
#include "app_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace AppExecFwk {
DataAbilityPredicates::DataAbilityPredicates(const std::string &testInf) : testInf_(testInf)
{}
/**
* @brief read this Sequenceable object from a Parcel.
*
* @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled.
* @return Returns true if read succeeded; returns false otherwise.
*/
bool DataAbilityPredicates::ReadFromParcel(Parcel &parcel)
{
testInf_ = Str16ToStr8(parcel.ReadString16());
return true;
}
/**
* @brief Unmarshals this Sequenceable object from a Parcel.
*
* @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled.
*/
DataAbilityPredicates *DataAbilityPredicates::Unmarshalling(Parcel &parcel)
{
DataAbilityPredicates *dataAbilityPredicates = new (std::nothrow) DataAbilityPredicates();
if (dataAbilityPredicates && !dataAbilityPredicates->ReadFromParcel(parcel)) {
APP_LOGE("DataAbilityPredicates::Unmarshalling ReadFromParcel failed");
delete dataAbilityPredicates;
dataAbilityPredicates = nullptr;
}
return dataAbilityPredicates;
}
/**
* @brief Marshals this Sequenceable object into a Parcel.
*
* @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled.
*/
bool DataAbilityPredicates::Marshalling(Parcel &parcel) const
{
if (!parcel.WriteString16(Str8ToStr16(testInf_))) {
APP_LOGE("dataAbilityPredicates::Marshalling WriteString16 failed");
return false;
}
return true;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 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 "dummy_result_set.h"
#include "app_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace AppExecFwk {
ResultSet::ResultSet(const std::string &testInf) : testInf_(testInf)
{}
/**
* @brief read this Sequenceable object from a Parcel.
*
* @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled.
* @return Returns true if read succeeded; returns false otherwise.
*/
bool ResultSet::ReadFromParcel(Parcel &parcel)
{
testInf_ = Str16ToStr8(parcel.ReadString16());
return true;
}
/**
* @brief Unmarshals this Sequenceable object from a Parcel.
*
* @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled.
*/
ResultSet *ResultSet::Unmarshalling(Parcel &parcel)
{
ResultSet *resultSet = new (std::nothrow) ResultSet();
if (resultSet && !resultSet->ReadFromParcel(parcel)) {
APP_LOGE("ResultSet::Unmarshalling ReadFromParcel failed");
delete resultSet;
resultSet = nullptr;
}
return resultSet;
}
/**
* @brief Marshals this Sequenceable object into a Parcel.
*
* @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled.
*/
bool ResultSet::Marshalling(Parcel &parcel) const
{
if (!parcel.WriteString16(Str8ToStr16(testInf_))) {
APP_LOGE("ResultSet::Marshalling WriteString16 failed");
return false;
}
return true;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 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 "dummy_values_bucket.h"
#include "app_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace AppExecFwk {
ValuesBucket::ValuesBucket(const std::string &testInf) : testInf_(testInf)
{}
/**
* @brief read this Sequenceable object from a Parcel.
*
* @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled.
* @return Returns true if read succeeded; returns false otherwise.
*/
bool ValuesBucket::ReadFromParcel(Parcel &parcel)
{
testInf_ = Str16ToStr8(parcel.ReadString16());
return true;
}
/**
* @brief Unmarshals this Sequenceable object from a Parcel.
*
* @param inParcel Indicates the Parcel object into which the Sequenceable object has been marshaled.
*/
ValuesBucket *ValuesBucket::Unmarshalling(Parcel &parcel)
{
ValuesBucket *valuesBucket = new (std::nothrow) ValuesBucket();
if (valuesBucket && !valuesBucket->ReadFromParcel(parcel)) {
APP_LOGE("ValuesBucket::Unmarshalling ReadFromParcel failed");
delete valuesBucket;
valuesBucket = nullptr;
}
return valuesBucket;
}
/**
* @brief Marshals this Sequenceable object into a Parcel.
*
* @param outParcel Indicates the Parcel object to which the Sequenceable object will be marshaled.
*/
bool ValuesBucket::Marshalling(Parcel &parcel) const
{
if (!parcel.WriteString16(Str8ToStr16(testInf_))) {
APP_LOGE("valuesBucket::Marshalling WriteString16 failed");
return false;
}
return true;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,165 @@
/*
* Copyright (c) 2021 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 "page_ability_impl.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient;
/**
* @brief Handling the life cycle switching of PageAbility.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
*/
void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{
APP_LOGI("PageAbilityImpl::sourceState:%{public}d; targetState: %{public}d; isNewWant: %{public}d",
lifecycleState_,
targetState.state,
targetState.isNewWant);
if ((lifecycleState_ == targetState.state) && !targetState.isNewWant) {
APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState.");
return;
}
if (lifecycleState_ == AAFwk::ABILITY_STATE_INITIAL) {
Start(want);
}
if (lifecycleState_ == AAFwk::ABILITY_STATE_ACTIVE) {
Inactive();
}
bool ret = false;
ret = AbilityTransaction(want, targetState);
if (ret) {
AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, targetState.state);
}
}
/**
* @brief Handling the life cycle switching of PageAbility in switch.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
* @return return true if the lifecycle transaction successfully, otherwise return false.
*
*/
bool PageAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{
APP_LOGE("PageAbilityImpl::AbilityTransaction called.");
bool ret = true;
switch (targetState.state) {
case AAFwk::ABILITY_STATE_INITIAL: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_INACTIVE) {
Background();
}
Stop();
break;
}
case AAFwk::ABILITY_STATE_INACTIVE: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND) {
Foreground(want);
}
break;
}
case AAFwk::ABILITY_STATE_ACTIVE: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND) {
Foreground(want);
}
if (targetState.isNewWant) {
NewWant(want);
}
SerUriString(targetState.caller.deviceId + "/" + targetState.caller.bundleName + "/" +
targetState.caller.abilityName);
Active();
break;
}
case AAFwk::ABILITY_STATE_BACKGROUND: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_INACTIVE) {
Background();
}
break;
}
default: {
ret = false;
APP_LOGE("PageAbilityImpl::HandleAbilityTransaction state error");
break;
}
}
return ret;
}
/**
* @brief Execution the KeyDown callback of the ability
* @param keyCode Indicates the code of the key pressed.
* @param keyEvent Indicates the key-down event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
bool PageAbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent)
{
if (ability_ == nullptr) {
APP_LOGE("PageAbilityImpl::DoKeyDown ability_ == nullptr");
return false;
}
return ability_->OnKeyDown(keyCode, keyEvent);
}
/**
* @brief Execution the KeyUp callback of the ability
* @param keyCode Indicates the code of the key released.
* @param keyEvent Indicates the key-up event.
*
* @return Returns true if this event is handled and will not be passed further; returns false if this event is
* not handled and should be passed to other handlers.
*
*/
bool PageAbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent)
{
if (ability_ == nullptr) {
APP_LOGE("PageAbilityImpl::DoKeyUp ability_ == nullptr");
return false;
}
return ability_->OnKeyUp(keyCode, keyEvent);
}
/**
* @brief Called when a touch event is dispatched to this ability. The default implementation of this callback
* does nothing and returns false.
* @param touchEvent Indicates information about the touch event.
*
* @return Returns true if the event is handled; returns false otherwise.
*
*/
bool PageAbilityImpl::DoTouchEvent(const TouchEvent &touchEvent)
{
if (ability_ == nullptr) {
APP_LOGE("PageAbilityImpl::DoTouchEvent ability_ == nullptr");
return false;
}
return ability_->OnTouchEvent(touchEvent);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2021 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 "service_ability_impl.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient;
/**
* @brief Handling the life cycle switching of PageAbility.
*
* @param want Indicates the structure containing information about the ability.
* @param targetState The life cycle state to switch to.
*
*/
void ServiceAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{
APP_LOGI("ServiceAbilityImpl::sourceState:%{public}d; targetState: %{public}d; isNewWant: %{public}d",
lifecycleState_,
targetState.state,
targetState.isNewWant);
if (lifecycleState_ == targetState.state) {
APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState.");
return;
}
bool ret = true;
switch (targetState.state) {
case AAFwk::ABILITY_STATE_INITIAL: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_ACTIVE) {
Background();
Stop();
}
break;
}
case AAFwk::ABILITY_STATE_INACTIVE: {
if (lifecycleState_ == AAFwk::ABILITY_STATE_INITIAL) {
SerUriString(targetState.caller.deviceId + "/" + targetState.caller.bundleName + "/" +
targetState.caller.abilityName);
Start(want);
}
break;
}
default: {
ret = false;
APP_LOGE("ServiceAbilityImpl::HandleAbilityTransaction state is error");
break;
}
}
if (ret) {
AbilityManagerClient::GetInstance()->AbilityTransitionDone(token_, targetState.state);
}
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2021 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 "task_handler.h"
namespace OHOS {
namespace AppExecFwk {
TaskHandler::TaskHandler(const std::shared_ptr<EventRunner> &runner) : EventHandler(runner)
{}
/**
* Process the event. Developers should override this method.
*
* @param event The event should be processed.
*/
void TaskHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer &event)
{}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,77 @@
/*
* Copyright (c) 2021 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 "task_handler_client.h"
#include "app_log_wrapper.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
std::shared_ptr<TaskHandlerClient> TaskHandlerClient::instance_ = nullptr;
std::mutex TaskHandlerClient::mutex_;
std::shared_ptr<TaskHandlerClient> TaskHandlerClient::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mutex_);
if (instance_ == nullptr) {
instance_ = std::make_shared<TaskHandlerClient>();
}
}
return instance_;
}
TaskHandlerClient::TaskHandlerClient()
{}
TaskHandlerClient::~TaskHandlerClient()
{}
bool TaskHandlerClient::PostTask(std::function<void()> task, long delayTime)
{
APP_LOGI("TaskHandlerClient::PostTask called");
if (taskHandler_ == nullptr) {
if (!CreateRunner()) {
APP_LOGE("TaskHandlerClient::PostTask failed, CreateRunner failed");
return false;
}
}
bool ret = taskHandler_->PostTask(task, delayTime, EventQueue::Priority::LOW);
if (!ret) {
APP_LOGE("TaskHandlerClient::PostTask failed, taskHandler_ PostTask failed");
}
return ret;
}
bool TaskHandlerClient::CreateRunner()
{
if (taskHandler_ == nullptr) {
std::shared_ptr<EventRunner> runner = EventRunner::Create("TaskRunner");
if (runner == nullptr) {
APP_LOGE("TaskHandlerClient::CreateRunner failed, runner is nullptr");
return false;
}
taskHandler_ = std::make_shared<TaskHandler>(runner);
if (taskHandler_ == nullptr) {
APP_LOGE("TaskHandlerClient::CreateRunner failed, taskHandler_ is nullptr");
return false;
}
}
return true;
}
} // namespace AppExecFwk
} // namespace OHOS
+780
View File
@@ -0,0 +1,780 @@
# Copyright (c) 2021 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("//build/test.gni")
module_output_path = "aafwk_standard/ability_test"
INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content",
"//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include",
"//foundation/appexecfwk/standard/kits/appkit/native/test/mock/include",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/aafwk/standard/services/abilitymgr/include",
"//utils/system/safwk/native/include",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"AbilityUnitTest\"",
"LOG_DOMAIN = 0xD002201",
]
}
config("module_ability_context_config") {
visibility = [ ":*" ]
include_dirs = [
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content",
"//EOSP/communication/libsoftbus/../../../foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include",
"//foundation/appexecfwk/standard/kits/appkit/native/test/mock/include",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//third_party/googletest/googlemock/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"AbilityUnitTest\"",
"LOG_DOMAIN = 0xD002201",
]
}
ohos_unittest("ability_test") {
module_out_path = module_output_path
sources = [
"../src/ability.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ability_start_setting.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"unittest/ability_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_lifecycle_test") {
module_out_path = module_output_path
sources = [
"../src/ability_lifecycle.cpp",
"unittest/ability_lifecycle_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_lifecycle_executor_test") {
module_out_path = module_output_path
sources = [
"../src/ability_lifecycle_executor.cpp",
"unittest/ability_lifecycle_executor_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_context_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp",
"mock/include/mock_ability_manager_service.cpp",
"mock/include/mock_bundle_manager.cpp",
"mock/include/sys_mgr_client_mock.cpp",
"unittest/ability_context_test.cpp",
]
configs = [ ":module_ability_context_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("page_ability_impl_test") {
module_out_path = module_output_path
sources = [
"../src/page_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp",
"unittest/page_ability_impl_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("service_ability_impl_test") {
module_out_path = module_output_path
sources = [
"../src/page_ability_impl.cpp",
"unittest/service_ability_impl_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("data_ability_helper_test") {
module_out_path = module_output_path
sources = [
"mock/include/mock_ability_manager_client.cpp",
"unittest/data_ability_helper_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_impl_test") {
module_out_path = module_output_path
sources = [
"../src/ability_impl.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"unittest/ability_impl_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_thread_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_context.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_handler.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl_factory.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle_executor.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_loader.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_local_record.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_thread.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_window.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_helper.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_uri_utils.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_data_ability_predicates.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_values_bucket.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/page_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/service_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_data_ability_impl.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h",
"mock/include/mock_ability_manager_client.cpp",
"mock/include/sys_mgr_client_mock.cpp",
"unittest/ability_thread_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("data_ability_impl_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_context.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_handler.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl_factory.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle_executor.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_loader.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_local_record.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_thread.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_window.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_helper.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_uri_utils.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_data_ability_predicates.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_values_bucket.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/page_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/service_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h",
"unittest/data_ability_impl_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("data_ability_impl_file_secondpart_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_context.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_handler.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl_factory.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle_executor.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_loader.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_local_record.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_thread.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_window.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_helper.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_uri_utils.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_data_ability_predicates.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_values_bucket.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/page_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/service_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h",
"unittest/data_ability_impl_file_secondpart_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("data_ability_impl_file_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_context.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_handler.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl_factory.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle_executor.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_loader.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_local_record.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_thread.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_window.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_helper.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_uri_utils.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_data_ability_predicates.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_values_bucket.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/page_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/service_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h",
"unittest/data_ability_impl_file_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_thread_dataability_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_context.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_handler.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_impl_factory.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_lifecycle_executor.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_loader.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_local_record.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_thread.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/ability_window.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_helper.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_uri_utils.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_data_ability_predicates.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/dummy_values_bucket.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/page_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/service_ability_impl.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_data_ability_impl.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_deal.cpp",
"//foundation/appexecfwk/standard/kits/appkit/native/app/src/ohos_application.cpp",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h",
"mock/include/mock_ability_manager_client.cpp",
"mock/include/sys_mgr_client_mock.cpp",
"unittest/ability_thread_dataability_test.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
config("data_uri_utils_test_config") {
visibility = [ ":*" ]
include_dirs =
[ "//foundation/aafwk/standard/frameworks/kits/ability/native/include/" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"AbilityUnitTest\"",
"LOG_DOMAIN = 0xD002201",
]
}
ohos_unittest("data_uri_utils_test") {
module_out_path = module_output_path
configs = [
":module_private_config",
":data_uri_utils_test_config",
]
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_uri_utils.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/data_uri_utils_test.cpp",
"//foundation/distributedschedule/dmsfwk/utils/native/source/uri.cpp",
]
deps = [
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("pac_map_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp",
"//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node.cpp",
"//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_array.cpp",
"//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_base.cpp",
"//foundation/aafwk/standard/frameworks/kits/base/cpp/src/ohos/aafwk/base/pac_map_node_user_object.cpp",
"//foundation/aafwk/standard/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp",
]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("ability_permission_test") {
module_out_path = module_output_path
sources = [
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/ability_permission_test.cpp",
"//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp",
"mock/include/mock_ability_manager_service.cpp",
"mock/include/mock_bundle_manager.cpp",
"mock/include/sys_mgr_client_mock.cpp",
]
configs = [ ":module_ability_context_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//base/global/resmgr_standard/frameworks/resmgr:global_resmgr",
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("task_handler_client_test") {
module_out_path = module_output_path
sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/task_handler_client_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [
"${INNERKITS_PATH}/want:want",
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
#"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
}
###############################################################################
group("unittest") {
testonly = true
deps = []
deps += [
":ability_context_test",
":ability_impl_test",
":ability_lifecycle_executor_test",
":ability_lifecycle_test",
":ability_permission_test",
":ability_test",
":ability_thread_dataability_test",
":ability_thread_test",
":data_ability_helper_test",
":data_ability_impl_file_secondpart_test",
":data_ability_impl_file_test",
":data_ability_impl_test",
":data_uri_utils_test",
":pac_map_test",
":page_ability_impl_test",
":service_ability_impl_test",
":task_handler_client_test",
]
}
###############################################################################
@@ -0,0 +1,193 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H
#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H
#include "ability_info.h"
#include "application_info.h"
#include "iremote_broker.h"
#include "iremote_object.h"
#include "bundle_info.h"
#include "hap_module_info.h"
#include "ohos/aafwk/content/want.h"
#include "permission_def.h"
using OHOS::AAFwk::Want;
namespace OHOS {
namespace AppExecFwk {
enum class DumpFlag {
DUMP_BUNDLE_LIST = 1,
DUMP_ALL_BUNDLE_INFO,
DUMP_BUNDLE_INFO,
};
enum class InstallFlag {
NORMAL = 0,
// Allow to replace the existing bundle when the new version isn't lower than the old one.
// If the bundle does not exist, just like normal flag.
REPLACE_EXISTING = 1,
};
enum class InstallLocation {
INTERNAL_ONLY = 1,
PREFER_EXTERNAL = 2,
};
struct InstallParam : public Parcelable {
InstallFlag installFlag = InstallFlag::NORMAL;
InstallLocation installLocation = InstallLocation::INTERNAL_ONLY;
int userId = -1;
// Is keep user data while uninstall.
bool isKeepData = false;
// the parcel object function is not const.
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static InstallParam *Unmarshalling(Parcel &parcel);
};
class IBundleStatusCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleStatusCallback");
virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg,
const std::string &bundleName) = 0;
enum class Message {
ON_BUNDLE_STATE_CHANGED,
};
};
class ICleanCacheCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.CleanCacheCallback");
virtual void OnCleanCacheFinished(bool succeeded) = 0;
enum class Message {
ON_CLEAN_CACHE_CALLBACK,
};
};
class IStatusReceiver : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.StatusReceiver");
virtual void OnStatusNotify(const int progress) = 0;
virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) = 0;
enum class Message {
ON_STATUS_NOTIFY,
ON_FINISHED,
};
enum {
SUCCESS = 0,
ERR_INSTALL_INTERNAL_ERROR,
ERR_INSTALL_PARSE_FAILED,
ERR_INSTALL_VERSION_DOWNGRADE,
ERR_INSTALL_VERIFICATION_FAILED,
ERR_INSTALL_NO_SIGNATURE_INFO,
ERR_INSTALL_UPDATE_INCOMPATIBLE,
ERR_INSTALL_INVALID_BUNDLE_FILE,
ERR_INSTALL_MISSING_INSTALLED_BUNDLE,
ERR_INSTALL_ALREADY_EXIST,
ERR_INSTALL_PARSE_UNEXPECTED,
ERR_INSTALL_PARSE_MISSING_BUNDLE,
ERR_INSTALL_PARSE_MISSING_ABILITY,
ERR_INSTALL_PARSE_NO_PROFILE,
ERR_INSTALL_PARSE_BAD_PROFILE,
ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR,
ERR_INSTALL_PARSE_PROFILE_MISSING_PROP,
ERR_UNINSTALL_INVALID_NAME,
ERR_UNKNOW,
};
};
class IBundleInstaller : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleInstaller");
virtual bool Install(const std::string &bundleFilePath, const InstallParam &installParam,
const sptr<IStatusReceiver> &statusReceiver) = 0;
virtual bool Uninstall(const std::string &bundleName, const InstallParam &installParam,
const sptr<IStatusReceiver> &statusReceiver) = 0;
enum class Message {
INSTALL,
UNINSTALL,
};
};
class IBundleMgr : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.BundleMgr");
virtual bool GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) = 0;
virtual bool GetApplicationInfos(
const ApplicationFlag flag, const int userId, std::vector<ApplicationInfo> &appInfos) = 0;
virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) = 0;
virtual bool GetBundleInfos(const BundleFlag flag, std::vector<BundleInfo> &bundleInfos) = 0;
virtual int GetUidByBundleName(const std::string &bundleName, const int userId) = 0;
virtual bool GetBundleNamesForUid(const int uid, std::vector<std::string> &bundleNames) = 0;
virtual bool GetBundleGids(const std::string &bundleName, std::vector<int> &gids) = 0;
virtual std::string GetAppType(const std::string &bundleName) = 0;
virtual bool CheckIsSystemAppByUid(const int uid) = 0;
virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector<BundleInfo> &bundleInfos) = 0;
virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) = 0;
virtual bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) = 0;
virtual bool QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos) = 0;
virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) = 0;
// obtains information about an application bundle contained in an OHOS Ability Package (HAP).
virtual bool GetBundleArchiveInfo(
const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) = 0;
virtual bool GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo) = 0;
// obtains the Want for starting the main ability of an application based on the given bundle name.
virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) = 0;
// checks whether the publickeys of two bundles are the same.
virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) = 0;
// checks whether a specified bundle has been granted a specific permission.
virtual int CheckPermission(const std::string &bundleName, const std::string &permission) = 0;
virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) = 0;
virtual bool GetAllPermissionGroupDefs(std::vector<PermissionDef> &permissionDefs) = 0;
virtual bool GetAppsGrantedPermissions(
const std::vector<std::string> &permissions, std::vector<std::string> &appNames) = 0;
virtual bool HasSystemCapability(const std::string &capName) = 0;
virtual bool GetSystemAvailableCapabilities(std::vector<std::string> &systemCaps) = 0;
virtual bool IsSafeMode() = 0;
// clears cache data of a specified application.
virtual bool CleanBundleCacheFiles(
const std::string &bundleName, const sptr<ICleanCacheCallback> &cleanCacheCallback) = 0;
virtual bool CleanBundleDataFiles(const std::string &bundleName) = 0;
virtual bool RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) = 0;
virtual bool ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) = 0;
// unregister callback of all application
virtual bool UnregisterBundleStatusCallback() = 0;
virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) = 0;
virtual sptr<IBundleInstaller> GetBundleInstaller() = 0;
virtual bool CanRequestPermission(
const std::string &bundleName, const std::string &permissionName, const int userId) = 0;
virtual bool RequestPermissionFromUser(
const std::string &bundleName, const std::string &permission, const int userId) = 0;
enum class Message {
QUERY_ABILITY_INFO,
GET_APPLICATION_INFO,
};
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H
@@ -0,0 +1,445 @@
/*
* Copyright (c) 2021 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 "ability.h"
#include <gtest/gtest.h>
#include "ability_loader.h"
#include "app_log_wrapper.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace AppExecFwk {
REGISTER_AA(Ability)
void Ability::Init(std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token)
{
APP_LOGI("Ability::Init called.");
abilityInfo_ = abilityInfo;
handler_ = handler;
AbilityContext::token_ = token;
// page ability only.
if (abilityInfo_->type == AbilityType::PAGE) {
abilityWindow_ = std::make_shared<AbilityWindow>();
}
lifecycle_ = std::make_shared<LifeCycle>();
abilityLifecycleExecutor_ = std::make_shared<AbilityLifecycleExecutor>();
application_ = application;
}
std::shared_ptr<Global::Resource::ResourceManager> Ability::GetResourceManager() const
{
std::shared_ptr<Global::Resource::ResourceManager> remoteObject(Global::CreateResourceManager());
return remoteObject;
}
void Ability::OnStart(const Want &want)
{
return;
}
void Ability::OnStop()
{
return;
}
void Ability::OnActive()
{
return;
}
void Ability::OnInactive()
{}
void Ability::OnForeground(const Want &want)
{
return;
}
void Ability::OnBackground()
{
return;
}
sptr<IRemoteObject> Ability::OnConnect(const Want &want)
{
return nullptr;
}
void Ability::OnDisconnect(const Want &want)
{}
void Ability::StartAbilityForResult(const Want &want, int requestCode)
{
return;
}
void Ability::StartAbilityForResult(const Want &want, int requestCode, AbilityStartSetting abilityStartSetting)
{
return;
}
void Ability::StartAbility(const Want &want, AbilityStartSetting abilityStartSetting)
{
return;
}
bool Ability::OnKeyDown(int keyCode, const KeyEvent &keyEvent)
{
return false;
}
bool Ability::OnKeyUp(int keyCode, const KeyEvent &keyEvent)
{
return false;
}
bool Ability::OnTouchEvent(const TouchEvent &touchEvent)
{
return false;
}
void Ability::SetUIContent(const ComponentContainer &componentContainer)
{
return;
}
void Ability::SetUIContent(int layoutRes)
{
return;
} // namespace AppExecFwk
void Ability::SetUIContent(
const ComponentContainer &componentContainer, std::shared_ptr<Context> &context, int typeFlag)
{
return;
}
void Ability::SetUIContent(int layoutRes, std::shared_ptr<Context> &context, int typeFlag)
{
return;
}
#ifdef WMS_COMPILE
/**
* @brief Inflates UI controls by using WindowConfig.
*
* @param config Indicates the window config defined by the user.
*/
void Ability::SetUIContent(const WindowConfig &config)
{
if (abilityWindow_ == nullptr) {
APP_LOGE("Ability::SetUIContent abilityWindow_ is nullptr");
return;
}
APP_LOGI("Ability::SetUIContent called");
abilityWindow_->SetWindowConfig(config);
}
/**
* @brief Get the window belong to the ability.
*
* @return Returns a IWindowsManager object pointer.
*/
std::unique_ptr<Window> &Ability::GetWindow(int windowID)
{
APP_LOGI("Ability::GetWindow called windowID = %d.", windowID);
return abilityWindow_->GetWindow(windowID);
}
#endif // WMS_COMPILE
int Ability::GetVolumeTypeAdjustedByKey()
{
return 0;
}
bool Ability::HasWindowFocus()
{
return false;
}
bool Ability::OnKeyPressAndHold(int keyCode, const std::shared_ptr<KeyEvent> &keyEvent)
{
return false;
}
void Ability::OnRequestPermissionsFromUserResult(
int requestCode, const std::vector<std::string> &permissions, const std::vector<int> &grantResults)
{
return;
}
void Ability::OnLeaveForeground()
{
return;
}
std::string Ability::GetType(const Uri &uri)
{
std::string value("\nullptr");
return value;
}
int Ability::Insert(const Uri &uri, const ValuesBucket &value)
{
GTEST_LOG_(INFO) << "Mock Ability::Insert called";
return 1;
}
void Ability::OnConfigurationUpdated(const Configuration &configuration)
{
return;
}
void Ability::OnMemoryLevel(int level)
{
return;
}
std::shared_ptr<RawFileDescriptor> Ability::OpenRawFile(const Uri &uri, const std::string &mode)
{
return nullptr;
}
int Ability::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock Ability::Update called";
return 1;
}
std::shared_ptr<OHOSApplication> Ability::GetApplication()
{
return application_;
}
std::string Ability::GetAbilityName()
{
return abilityInfo_->name;
}
bool Ability::IsTerminating()
{
return false;
}
void Ability::OnAbilityResult(int requestCode, int resultCode, const Want &want)
{}
void Ability::OnBackPressed()
{
return;
}
void Ability::OnNewWant(const Want &want)
{
APP_LOGI("Ability::OnNewWant called");
}
void Ability::OnRestoreAbilityState(const PacMap &inState)
{
APP_LOGI("Ability::OnRestoreAbilityState called");
}
void Ability::OnSaveAbilityState(const PacMap &outState)
{
APP_LOGI("Ability::OnSaveAbilityState called");
}
void Ability::OnEventDispatch()
{
return;
}
void Ability::OnWindowFocusChanged(bool hasFocus)
{
return;
}
void Ability::SetWant(const AAFwk::Want &want)
{
setWant_ = std::make_shared<AAFwk::Want>(want);
}
std::shared_ptr<AAFwk::Want> Ability::GetWant()
{
return setWant_;
}
void Ability::SetResult(int resultCode, const Want &resultData)
{
if (abilityInfo_ == nullptr) {
APP_LOGI("Ability::SetResult nullptr == abilityInfo_");
return;
}
APP_LOGI("Ability::SetResult called type = %{public}d", abilityInfo_->type);
if (abilityInfo_->type == AppExecFwk::AbilityType::PAGE) {
AbilityContext::resultWant_ = resultData;
AbilityContext::resultCode_ = resultCode;
}
}
void Ability::SetVolumeTypeAdjustedByKey(int volumeType)
{
return;
}
void Ability::OnCommand(const AAFwk::Want &want, bool restart, int startId)
{
return;
}
void Ability::Dump(const std::string &extra)
{
return;
}
void Ability::KeepBackgroundRunning(int id, const NotificationRequest &notificationRequest)
{
return;
}
void Ability::CancelBackgroundRunning()
{
return;
}
const std::shared_ptr<Uri> Ability::NormalizeUri(const Uri &uri)
{
return nullptr;
}
int Ability::Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock Ability::Delete called";
return 1;
}
std::vector<std::string> Ability::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
std::vector<std::string> value;
value.push_back(mimeTypeFilter);
GTEST_LOG_(INFO) << "Mock Ability::GetFileTypes called";
return value;
}
int Ability::OpenFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "Mock Ability::OpenFile called";
return 1;
}
std::shared_ptr<ResultSet> Ability::Query(
const Uri &uri, const std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock Ability::Query called";
return nullptr;
}
bool Ability::Reload(const Uri &uri, const PacMap &extras)
{
return true;
}
void Ability::ContinueAbilityReversibly(const std::string &deviceId)
{
return;
}
void Ability::ContinueAbilityReversibly()
{
return;
}
std::string Ability::GetOriginalDeviceId()
{
return "";
}
std::shared_ptr<ContinuationState> Ability::GetContinuationState()
{
return nullptr;
}
bool Ability::ReverseContinueAbility()
{
return false;
}
std::shared_ptr<AbilityPackage> Ability::GetAbilityPackage()
{
return nullptr;
}
std::shared_ptr<Uri> Ability::DenormalizeUri(const Uri &uri)
{
return nullptr;
}
std::shared_ptr<LifeCycle> Ability::GetLifecycle()
{
APP_LOGI("Ability::GetLifecycle called");
return lifecycle_;
}
AbilityLifecycleExecutor::LifecycleState Ability::GetState()
{
APP_LOGI("Ability::GetState called");
if (abilityLifecycleExecutor_ == nullptr) {
APP_LOGI("Ability::GetState error. abilityLifecycleExecutor_ == nullptr.");
return AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED;
}
return (AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
}
void Ability::StartAbility(const Want &want)
{
APP_LOGI("Ability::StartAbility called");
AbilityContext::StartAbility(want, -1);
}
void Ability::TerminateAbility()
{
APP_LOGI("Ability::TerminateAbility called");
AbilityContext::TerminateAbility();
}
int Ability::TerminateAbility(Want &want)
{
return -1;
}
void Ability::SetMainRoute(const std::string &entry)
{
return;
}
void Ability::AddActionRoute(const std::string &action, const std::string &entry)
{
return;
}
int Ability::SetWindowBackgroundColor(int red, int green, int blue)
{
return -1;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_INHERITANCE_IMPL_H
#define FOUNDATION_APPEXECFWK_OHOS_MOCK_INHERITANCE_IMPL_H
#include "ability.h"
#include "ability_impl.h"
#include <gtest/gtest.h>
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class MockAbilityimpl : public AbilityImpl {
public:
MockAbilityimpl() = default;
virtual ~MockAbilityimpl() = default;
void ImplStart(const Want &want)
{
this->Start(want);
}
void ImplStop()
{
this->Stop();
}
void ImplActive()
{
this->Active();
}
void ImplInactive()
{
this->Inactive();
}
void ImplForeground(const Want &want)
{
this->Foreground(want);
}
void ImplBackground()
{
this->Background();
}
void SetlifecycleState(int state)
{
this->lifecycleState_ = state;
}
int MockGetCurrentState()
{
int value;
value = GetCurrentState();
return value;
}
sptr<IRemoteObject> GetToken()
{
return token_;
}
std::shared_ptr<Ability> GetAbility()
{
return ability_;
}
private:
AbilityImpl AbilityImpl_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_PAGE_ABILITY_H
@@ -0,0 +1,144 @@
/*
* Copyright (c) 2021 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 "mock_ability_manager_client.h"
#include <gtest/gtest.h>
#include "ability_manager_client.h"
namespace OHOS {
namespace AAFwk {
std::shared_ptr<AbilityManagerClient> AbilityManagerClient::instance_ = nullptr;
std::mutex AbilityManagerClient::mutex_;
std::shared_ptr<AbilityManagerClient> AbilityManagerClient::GetInstance()
{
if (instance_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mutex_);
if (instance_ == nullptr) {
instance_ = std::make_shared<AbilityManagerClient>();
}
}
return instance_;
}
AbilityManagerClient::AbilityManagerClient()
{
// log
}
AbilityManagerClient::~AbilityManagerClient()
{}
ErrCode AbilityManagerClient::AttachAbilityThread(
const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
{
GTEST_LOG_(INFO) << "Mock AbilityManagerClient::AttachAbilityThread called";
return -1;
}
ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state)
{
return -1;
}
ErrCode AbilityManagerClient::ScheduleConnectAbilityDone(
const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
{
return -1;
}
ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
{
return -1;
}
ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
{
return -1;
}
void AbilityManagerClient::AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken)
{
return;
}
ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode)
{
return -1;
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
{
return -1;
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &callerToken, int requestCode)
{
GTEST_LOG_(INFO) << "Mock AbilityManagerClient::TerminateAbility called";
return -1;
}
ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId)
{
return -1;
}
ErrCode AbilityManagerClient::ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
return -1;
}
ErrCode AbilityManagerClient::DisconnectAbility(const sptr<IAbilityConnection> &connect)
{
return -1;
}
sptr<IAbilityScheduler> AbilityManagerClient::AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
{
GTEST_LOG_(INFO) << "Mock AcquireDataAbility called";
sptr<IAbilityScheduler> dataScheduler = new (std::nothrow) OHOS::AppExecFwk::MockAbilityThread();
return dataScheduler;
}
ErrCode AbilityManagerClient::ReleaseDataAbility(
sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
{
GTEST_LOG_(INFO) << "Mock ReleaseDataAbility called";
return ERR_OK;
}
ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector<std::string> &state)
{
return -1;
}
ErrCode AbilityManagerClient::Connect()
{
return -1;
}
ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo)
{
return -1;
}
ErrCode AbilityManagerClient::StopServiceAbility(const Want &want)
{
return -1;
}
} // namespace AAFwk
} // namespace OHOS
@@ -0,0 +1,139 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H
#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H
#include <gtest/gtest.h>
#include <mutex>
#include "ability_connect_callback_interface.h"
#include "ability_manager_errors.h"
#include "ability_context.h"
#include "ability_manager_interface.h"
#include "ability_scheduler_interface.h"
#include "app_log_wrapper.h"
#include "iremote_object.h"
#include "iremote_stub.h"
#include "want.h"
#define OPENFILENUM (1246)
#define INSERTNUM (2345)
#define UPDATENUM (3456)
#define OPENRAWFILENUM (5678)
#define DELETENUM (6789)
#define BATCHINSERTNUM (789)
namespace OHOS {
namespace AppExecFwk {
class MockAbility : public AbilityContext {
public:
MockAbility() = default;
virtual ~MockAbility() = default;
};
class MockAbilityThread : public IRemoteStub<AAFwk::IAbilityScheduler> {
public:
void ScheduleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{}
void SendResult(int requestCode, int resultCode, const Want &resultWant)
{}
void ScheduleConnectAbility(const Want &want)
{}
void ScheduleDisconnectAbility()
{}
void ScheduleSaveAbilityState(PacMap &outState)
{}
void ScheduleRestoreAbilityState(const PacMap &inState)
{}
void ScheduleDisconnectAbility(const Want &want)
{}
void ScheduleCommandAbility(const Want &want, bool restart, int startId)
{}
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
GTEST_LOG_(INFO) << "MockAbilityThread::GetFileTypes called";
std::vector<std::string> types;
types.push_back("Types1");
types.push_back("Types2");
types.push_back("Types3");
return types;
}
int OpenFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "MockAbilityThread::OpenFile called";
return OPENFILENUM;
}
int Insert(const Uri &uri, const ValuesBucket &value)
{
GTEST_LOG_(INFO) << "MockAbilityThread::Insert called";
return INSERTNUM;
}
int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockAbilityThread::Update called";
return UPDATENUM;
}
int Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockAbilityThread::Delete called";
return DELETENUM;
}
int OpenRawFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "MockAbilityThread::OpenRawFile called";
return OPENRAWFILENUM;
}
bool Reload(const Uri &uri, const PacMap &extras)
{
GTEST_LOG_(INFO) << "MockAbilityThread::Reload called";
return true;
}
int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values)
{
GTEST_LOG_(INFO) << "MockAbilityThread::BatchInsert called";
return BATCHINSERTNUM;
}
std::shared_ptr<ResultSet> Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockAbilityThread::Query called";
std::shared_ptr<ResultSet> set = std::make_shared<ResultSet>("resultset");
return set;
}
std::string GetType(const Uri &uri)
{
return "Type1";
}
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H
@@ -0,0 +1,176 @@
/*
* Copyright (c) 2021 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 "mock_ability_manager_service.h"
#include <gtest/gtest.h>
#include <functional>
#include <memory>
#include <string>
#include <unistd.h>
using OHOS::AppExecFwk::ElementName;
namespace OHOS {
namespace AAFwk {
MockAbilityManagerService::MockAbilityManagerService() : abilityScheduler_(nullptr)
{
abilityScheduler_ = nullptr;
}
MockAbilityManagerService::~MockAbilityManagerService()
{}
int MockAbilityManagerService::StartAbility(const Want &want, int requestCode)
{
AbilityLifeCycleState state = AbilityLifeCycleState::ABILITY_STATE_INITIAL;
switch (requestCode) {
// Test code, representing the life cycle: Ability_ STATE_ INITIAL
case RequestCode::E_STATE_INITIAL:
state = AbilityLifeCycleState::ABILITY_STATE_INITIAL;
break;
// Test code, representing the life cycle: ABILITY_STATE_INACTIVE
case RequestCode::E_STATE_INACTIVE:
state = AbilityLifeCycleState::ABILITY_STATE_INACTIVE;
break;
// Test code, representing the life cycle: ABILITY_STATE_ACTIVE
case RequestCode::E_STATE_ACTIVE:
state = AbilityLifeCycleState::ABILITY_STATE_ACTIVE;
break;
// Test code, representing the life cycle: ABILITY_STATE_BACKGROUND
case RequestCode::E_STATE_BACKGROUND:
state = AbilityLifeCycleState::ABILITY_STATE_BACKGROUND;
break;
// Test code, representing the life cycle: ABILITY_STATE_SUSPENDED
case RequestCode::E_STATE_SUSPENDED:
state = AbilityLifeCycleState::ABILITY_STATE_SUSPENDED;
break;
default:
break;
}
if (abilityScheduler_ != nullptr) {
want_ = want;
want_.SetElementName("BundleName", "abilityName");
LifeCycleStateInfo stateInfo;
stateInfo.state = state;
abilityScheduler_->ScheduleAbilityTransaction(want_, stateInfo);
}
return 0;
}
int MockAbilityManagerService::TerminateAbility(
const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
{
GTEST_LOG_(INFO) << "MockAbilityManagerService::TerminateAbility";
if (abilityScheduler_ != nullptr) {
LifeCycleStateInfo stateInfo;
stateInfo.state = AbilityLifeCycleState::ABILITY_STATE_INITIAL;
abilityScheduler_->ScheduleAbilityTransaction(want_, stateInfo);
int ceode = 250;
abilityScheduler_->SendResult(ceode, resultCode, *resultWant);
}
return 0;
}
int MockAbilityManagerService::ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
GTEST_LOG_(INFO) << "MockAbilityManagerService::ConnectAbility";
return ERR_OK;
}
int MockAbilityManagerService::DisconnectAbility(const sptr<IAbilityConnection> &connect)
{
GTEST_LOG_(INFO) << "MockAbilityManagerService::DisconnectAbility";
return ERR_OK;
}
int MockAbilityManagerService::AttachAbilityThread(
const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
{
abilityScheduler_ = scheduler;
EXPECT_NE(nullptr, token);
return 0;
}
void MockAbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
{}
int MockAbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state)
{
return 0;
}
int MockAbilityManagerService::ScheduleConnectAbilityDone(
const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
{
return 0;
}
int MockAbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
{
return 0;
}
int MockAbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
{
return 0;
}
void MockAbilityManagerService::AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken)
{}
int MockAbilityManagerService::TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId)
{
GTEST_LOG_(INFO) << "MockAbilityManagerService::TerminateAbilityResult";
return ERR_OK;
}
int MockAbilityManagerService::StopServiceAbility(const Want &want)
{
GTEST_LOG_(INFO) << "MockAbilityManagerService::StopServiceAbility";
return ERR_OK;
}
int MockAbilityManagerService::RemoveMission(int id)
{
return 0;
}
int MockAbilityManagerService::RemoveStack(int id)
{
return 0;
}
int MockAbilityManagerService::MoveMissionToTop(int32_t missionId)
{
return 0;
}
int MockAbilityManagerService::KillProcess(const std::string &bundleName)
{
return 0;
}
int MockAbilityManagerService::UninstallApp(const std::string &bundleName)
{
return 0;
}
} // namespace AAFwk
} // namespace OHOS
@@ -0,0 +1,114 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef OHOS_AAFWK_ABILITY_MOCK_MANAGER_SERVICE_H
#define OHOS_AAFWK_ABILITY_MOCK_MANAGER_SERVICE_H
#include <memory>
#include <singleton.h>
#include <thread_ex.h>
#include <unordered_map>
#include "ability_manager_stub.h"
#include "iremote_object.h"
#include "gmock/gmock.h"
namespace OHOS {
namespace AAFwk {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class MockAbilityManagerService : public AbilityManagerStub,
public std::enable_shared_from_this<MockAbilityManagerService> {
public:
MockAbilityManagerService();
~MockAbilityManagerService();
int StartAbility(const Want &want, int requestCode = -1) override;
int StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode = -1) override
{
return 0;
}
int TerminateAbility(
const sptr<IRemoteObject> &token, int resultCode = -1, const Want *resultWant = nullptr) override;
int ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken) override;
int DisconnectAbility(const sptr<IAbilityConnection> &connect) override;
void AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken) override;
int AttachAbilityThread(const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token) override;
int AbilityTransitionDone(const sptr<IRemoteObject> &token, int state) override;
int ScheduleConnectAbilityDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject) override;
int ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token) override;
int ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token) override;
void DumpState(const std::string &args, std::vector<std::string> &info) override;
int TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId) override;
int StopServiceAbility(const Want &want) override;
MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo));
int RemoveMission(int id) override;
int RemoveStack(int id) override;
sptr<IAbilityScheduler> AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken) override
{
return nullptr;
}
int ReleaseDataAbility(
sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken) override
{
return 0;
}
int GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList) override
{
return 0;
}
int GetMissionSnapshot(const int32_t missionId, MissionSnapshotInfo &snapshot)
{
return 0;
}
int MoveMissionToTop(int32_t missionId) override;
int KillProcess(const std::string &bundleName) override;
int UninstallApp(const std::string &bundleName) override;
int TerminateAbilityByCaller(const sptr<IRemoteObject> &callerToken, int requestCode) override
{
return 0;
}
enum RequestCode {
E_STATE_INITIAL = 0,
E_STATE_INACTIVE,
E_STATE_ACTIVE,
E_STATE_BACKGROUND,
E_STATE_SUSPENDED,
};
sptr<IAbilityScheduler> abilityScheduler_; // kit interface used to schedule ability life
Want want_;
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_ABILITY_MOCK_MANAGER_SERVICE_H
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_ABILITY_THREAD_H
#define FOUNDATION_APPEXECFWK_OHOS_MOCK_ABILITY_THREAD_H
#include "ability.h"
#include "ability_impl.h"
#include "ability_thread.h"
#include <gtest/gtest.h>
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class MockAbilityThread : public AbilityThread {
public:
MockAbilityThread() = default;
virtual ~MockAbilityThread() = default;
private:
AbilityThread AbilityThread_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_PAGE_ABILITY_H
@@ -0,0 +1,60 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_ABILITY_TOKEN_H
#define FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_ABILITY_TOKEN_H
#include "nocopyable.h"
#include "iremote_broker.h"
#include "iremote_object.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace AppExecFwk {
class IAbilityToken : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AbilityToken");
};
class MockAbilityToken : public IRemoteStub<IAbilityToken> {
public:
MockAbilityToken() = default;
virtual ~MockAbilityToken() = default;
virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
return 0;
}
private:
DISALLOW_COPY_AND_MOVE(MockAbilityToken);
};
class AbilityTokenProxy : public IRemoteProxy<IAbilityToken> {
public:
explicit AbilityTokenProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IAbilityToken>(impl)
{}
virtual ~AbilityTokenProxy() = default;
private:
DISALLOW_COPY_AND_MOVE(AbilityTokenProxy);
};
DECLARE_INTERFACE_DESCRIPTOR(u"IAbilityToken");
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_INCLUDE_MOCK_ABILITY_TOKEN_H
@@ -0,0 +1,112 @@
/*
* Copyright (c) 2021 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 "mock_bundle_manager.h"
#include <gtest/gtest.h>
#include "ability_info.h"
#include "application_info.h"
namespace OHOS {
namespace AppExecFwk {
bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo)
{
ElementName eleName = want.GetElement();
if (eleName.GetBundleName().empty()) {
return false;
}
abilityInfo.name = eleName.GetAbilityName();
abilityInfo.bundleName = eleName.GetBundleName();
abilityInfo.applicationName = "Helloworld";
return true;
}
bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo)
{
return false;
}
bool BundleMgrProxy::GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo)
{
if (appName.empty()) {
return false;
}
appInfo.name = "Helloworld";
appInfo.bundleName = "com.ohos.hiworld";
return true;
}
std::string BundleMgrProxy::GetAppType(const std::string &bundleName)
{
GTEST_LOG_(INFO) << " BundleMgrProxy::GetAppTyp";
return "system";
}
int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
return 0;
}
bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo)
{
ElementName elementName = want.GetElement();
if (elementName.GetBundleName().empty()) {
return false;
}
if (std::string::npos != elementName.GetBundleName().find("service")) {
abilityInfo.type = AppExecFwk::AbilityType::SERVICE;
}
abilityInfo.name = elementName.GetAbilityName();
abilityInfo.bundleName = elementName.GetBundleName();
abilityInfo.applicationName = elementName.GetBundleName();
if (want.HasEntity(Want::ENTITY_HOME) && want.GetAction() == Want::ACTION_HOME) {
abilityInfo.applicationInfo.isLauncherApp = true;
} else {
abilityInfo.applicationInfo.isLauncherApp = false;
}
return true;
}
bool BundleMgrService::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo)
{
return false;
}
bool BundleMgrService::GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo)
{
if (appName.empty()) {
return false;
}
appInfo.name = "Helloworld";
appInfo.bundleName = "com.foobar.hiworld";
return true;
}
std::string BundleMgrService::GetAppType(const std::string &bundleName)
{
GTEST_LOG_(INFO) << " BundleMgrService::GetAppType";
return "system";
}
bool BundleMgrService::GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo)
{
GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo";
hapModuleInfo.name = "Captain";
return true;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,324 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H
#define OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H
#include <vector>
#include "ability_info.h"
#include "application_info.h"
#include "bundle_mgr_interface.h"
#include "ohos/aafwk/content/want.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace AppExecFwk {
class BundleMgrProxy : public IRemoteProxy<IBundleMgr> {
public:
explicit BundleMgrProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IBundleMgr>(impl)
{}
~BundleMgrProxy() = default;
bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) override;
bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override;
std::string GetAppType(const std::string &bundleName) override;
virtual bool GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override;
virtual bool GetApplicationInfos(
const ApplicationFlag flag, const int userId, std::vector<ApplicationInfo> &appInfos) override
{
return true;
};
bool CheckIsSystemAppByUid(const int uid) override
{
return true;
};
virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override
{
return true;
};
virtual bool GetBundleInfos(const BundleFlag flag, std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override
{
return 0;
};
virtual bool GetBundleNamesForUid(const int uid, std::vector<std::string> &bundleNames) override
{
return true;
};
virtual bool GetBundleGids(const std::string &bundleName, std::vector<int> &gids) override
{
return true;
};
virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
virtual bool QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override
{
return "";
};
// obtains information about an application bundle contained in a OHOS Ability Package (HAP).
virtual bool GetBundleArchiveInfo(
const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override
{
return true;
};
virtual bool GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo) override;
// obtains the Want for starting the main ability of an application based on the given bundle name.
virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override
{
return true;
};
// checks whether the publickeys of two bundles are the same.
virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override
{
return 0;
};
// checks whether a specified bundle has been granted a specific permission.
virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override
{
return 0;
};
virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override
{
return true;
};
virtual bool GetAllPermissionGroupDefs(std::vector<PermissionDef> &permissionDefs) override
{
return true;
};
virtual bool GetAppsGrantedPermissions(
const std::vector<std::string> &permissions, std::vector<std::string> &appNames) override
{
return true;
};
virtual bool HasSystemCapability(const std::string &capName) override
{
return true;
};
virtual bool GetSystemAvailableCapabilities(std::vector<std::string> &systemCaps) override
{
return true;
};
virtual bool IsSafeMode() override
{
return true;
};
// clears cache data of a specified application.
virtual bool CleanBundleCacheFiles(
const std::string &bundleName, const sptr<ICleanCacheCallback> &cleanCacheCallback) override
{
return true;
};
virtual bool CleanBundleDataFiles(const std::string &bundleName) override
{
return true;
};
virtual bool RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) override
{
return true;
};
virtual bool ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) override
{
return true;
};
// unregister callback of all application
virtual bool UnregisterBundleStatusCallback() override
{
return true;
};
virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override
{
return true;
};
virtual sptr<IBundleInstaller> GetBundleInstaller() override
{
return nullptr;
};
virtual bool CanRequestPermission(
const std::string &bundleName, const std::string &permissionName, const int userId) override
{
printf("===================22222222===========\n");
return false;
}
virtual bool RequestPermissionFromUser(
const std::string &bundleName, const std::string &permission, const int userId) override
{
return true;
}
};
class BundleMgrStub : public IRemoteStub<IBundleMgr> {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr");
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
};
class BundleMgrService : public BundleMgrStub {
public:
bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override;
bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override;
std::string GetAppType(const std::string &bundleName) override;
virtual bool GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override;
virtual bool GetApplicationInfos(
const ApplicationFlag flag, const int userId, std::vector<ApplicationInfo> &appInfos) override
{
return true;
};
bool CheckIsSystemAppByUid(const int uid) override
{
return true;
};
virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override
{
return true;
};
virtual bool GetBundleInfos(const BundleFlag flag, std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override
{
return 0;
};
virtual bool GetBundleNamesForUid(const int uid, std::vector<std::string> &bundleNames) override
{
return true;
};
virtual bool GetBundleGids(const std::string &bundleName, std::vector<int> &gids) override
{
return true;
};
virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
virtual bool QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override
{
return "";
};
// obtains information about an application bundle contained in a OHOS Ability Package (HAP).
virtual bool GetBundleArchiveInfo(
const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override
{
return true;
};
virtual bool GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo) override;
// obtains the Want for starting the main ability of an application based on the given bundle name.
virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override
{
return true;
};
// checks whether the publickeys of two bundles are the same.
virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override
{
return 0;
};
// checks whether a specified bundle has been granted a specific permission.
virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override
{
return 0;
};
virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override
{
return true;
};
virtual bool GetAllPermissionGroupDefs(std::vector<PermissionDef> &permissionDefs) override
{
return true;
};
virtual bool GetAppsGrantedPermissions(
const std::vector<std::string> &permissions, std::vector<std::string> &appNames) override
{
return true;
};
virtual bool HasSystemCapability(const std::string &capName) override
{
return true;
};
virtual bool GetSystemAvailableCapabilities(std::vector<std::string> &systemCaps) override
{
return true;
};
virtual bool IsSafeMode() override
{
return true;
};
// clears cache data of a specified application.
virtual bool CleanBundleCacheFiles(
const std::string &bundleName, const sptr<ICleanCacheCallback> &cleanCacheCallback) override
{
return true;
};
virtual bool CleanBundleDataFiles(const std::string &bundleName) override
{
return true;
};
virtual bool RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) override
{
return true;
};
virtual bool ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) override
{
return true;
};
// unregister callback of all application
virtual bool UnregisterBundleStatusCallback() override
{
return true;
};
virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override
{
return true;
};
virtual sptr<IBundleInstaller> GetBundleInstaller() override
{
return nullptr;
};
virtual bool CanRequestPermission(
const std::string &bundleName, const std::string &permissionName, const int userId) override
{
printf("===================333333333333333333===========\n");
return false;
}
virtual bool RequestPermissionFromUser(
const std::string &bundleName, const std::string &permission, const int userId) override
{
return true;
}
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H
@@ -0,0 +1,110 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_DATA_ABILITY_H
#define FOUNDATION_APPEXECFWK_OHOS_MOCK_DATA_ABILITY_H
#include "ability.h"
#include <gtest/gtest.h>
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class MockDataAbility : public Ability {
public:
MockDataAbility() = default;
virtual ~MockDataAbility() = default;
enum Event { ON_ACTIVE = 0, ON_BACKGROUND, ON_FOREGROUND, ON_INACTIVE, ON_START, ON_STOP, UNDEFINED };
int OpenFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "MockDataAbility::OpenFile called";
return 1;
}
int Insert(const Uri &uri, const ValuesBucket &value)
{
GTEST_LOG_(INFO) << "MockDataAbility::Insert called";
return 1;
}
int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockDataAbility::Update called";
return 1;
}
int Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockDataAbility::Delete called";
return 1;
}
int OpenRawFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "MockDataAbility::OpenRawFile called";
return 1;
}
bool Reload(const Uri &uri, const PacMap &extras)
{
GTEST_LOG_(INFO) << "MockDataAbility::Reload called";
return 1;
}
int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values)
{
GTEST_LOG_(INFO) << "MockDataAbility::BatchInsert called";
return 1;
}
std::shared_ptr<ResultSet> Query(
const Uri &uri, const std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockDataAbility::Query called";
std::shared_ptr<ResultSet> set = std::make_shared<ResultSet>("QueryTest");
return set;
}
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
GTEST_LOG_(INFO) << "MockDataAbility::GetFileTypes called";
value.push_back(mimeTypeFilter);
return value;
}
std::string GetType(const Uri &uri)
{
GTEST_LOG_(INFO) << "MockDataAbility::GetType called";
std::string value("Type1");
return value;
}
int datatest = 0;
MockDataAbility::Event state_ = UNDEFINED;
std::vector<std::string> value;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_PAGE_ABILITY_H
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2021 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 "data_ability_impl.h"
#include <gtest/gtest.h>
#include "app_log_wrapper.h"
const int returnValueOpenfile = 11;
const int returnValueInsert = 22;
const int returnValueUpdate = 33;
const int returnValueDelete = 44;
namespace OHOS {
namespace AppExecFwk {
void DataAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::HandleAbilityTransaction called";
}
std::vector<std::string> DataAbilityImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::GetFileTypes called";
std::vector<std::string> types;
types.push_back("Type1");
types.push_back("Type2");
types.push_back("Type3");
return types;
}
int DataAbilityImpl::OpenFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::OpenFile called";
return returnValueOpenfile;
}
int DataAbilityImpl::Insert(const Uri &uri, const ValuesBucket &value)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::Insert called";
return returnValueInsert;
}
int DataAbilityImpl::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::Update called";
return returnValueUpdate;
}
int DataAbilityImpl::Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::Delete called";
return returnValueDelete;
}
std::shared_ptr<ResultSet> DataAbilityImpl::Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::Query called";
std::shared_ptr<ResultSet> resultSet = std::make_shared<ResultSet>("TestResultSet");
return resultSet;
}
std::string DataAbilityImpl::GetType(const Uri &uri)
{
GTEST_LOG_(INFO) << "Mock DataAbilityImpl::GetType called";
std::string type("type");
return type;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,133 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_LIFECYCLE_OBSERVER_INTERFACE_H
#define FOUNDATION_APPEXECFWK_OHOS_MOCK_LIFECYCLE_OBSERVER_INTERFACE_H
#include "want.h"
#include "ability_lifecycle_observer_interface.h"
#include <gtest/gtest.h>
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class MockLifecycleObserver : public ILifecycleObserver {
public:
MockLifecycleObserver() = default;
virtual ~MockLifecycleObserver() = default;
/**
* Called back in response to an ON_ACTIVE event.
* When an ON_ACTIVE event is received, the ability or ability slice is in the foreground and is interactive.
*/
virtual void OnActive()
{
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnActive called";
}
/**
* Called back in response to an ON_BACKGROUND event.
* When an ON_BACKGROUND event is received, the ability or ability slice is invisible. You are advised to
* suspend the threads related to this ability or ability slice and clear resources for more system memory.
*
*/
virtual void OnBackground()
{
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnBackground called";
}
/**
* Called back in response to an ON_FOREGROUND event, where information for the
* ability or ability slice to go back to the ACTIVE state is carried in the want parameter.
* When an ON_FOREGROUND event is received, the ability or ability slice returns to the foreground. You can use
* this method to implement re-initialization or adjust the UI display by using the want parameter.
*
* @param want Indicates the information for the ability or ability slice to go back to the ACTIVE state.
*/
virtual void OnForeground(const Want &want)
{
(void)want;
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnForeground called";
}
/**
* Called back in response to an ON_INACTIVE event.
* When an ON_INACTIVE event is received, the ability or ability slice is in the INACTIVE state. INACTIVE is an
* intermediate state before the state changes to ACTIVE or BACKGROUND. In this state, the UI may be visible but is
* not interactive. You are advised not to use this method to invoke complex service logic.
*
*/
virtual void OnInactive()
{
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnInactive called";
}
/**
* Called back in response to an ON_START event, where the startup information
* is carried in the want parameter.
* This method initializes an Ability or AbilitySlice and is called back only once during the entire lifecycle.
* You are advised to implement some initialization logic using this method, for example, you can initialize a
* timer or define some global objects.
*
* @param want Indicates the startup information.
*/
virtual void OnStart(const Want &want)
{
(void)want;
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStart called";
}
/**
* Called back in response to an ON_STOP event.
* This method is called back when the lifecycle of the ability or ability slice is destroyed. You can reclaim
* resources using this method.
*
*/
virtual void OnStop()
{
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStop called";
}
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
* @param want Indicates the state change information.
*/
virtual void OnStateChanged(LifeCycle::Event event, const Want &want)
{
(void)event;
(void)want;
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStateChanged called";
}
/**
* @brief Called back in response to a lifecycle change. This method is triggered by a registered LifecycleObserver
* each time the lifecycle state changes.
*
* @param event Indicates the lifecycle event.
*/
virtual void OnStateChanged(LifeCycle::Event event)
{
(void)event;
GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStateChanged called";
}
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_LIFECYCLE_OBSERVER_INTERFACE_H
@@ -0,0 +1,172 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_PAGE_ABILITY_H
#define FOUNDATION_APPEXECFWK_OHOS_MOCK_PAGE_ABILITY_H
#include "ability.h"
#include <gtest/gtest.h>
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class MockPageAbility : public Ability {
public:
MockPageAbility() = default;
virtual ~MockPageAbility() = default;
enum Event { ON_ACTIVE = 0, ON_BACKGROUND, ON_FOREGROUND, ON_INACTIVE, ON_START, ON_STOP, UNDEFINED };
bool OnKeyDown(int keyCode, const KeyEvent &keyEvent)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnKeyDown called";
return true;
}
bool OnKeyUp(int keyCode, const KeyEvent &keyEvent)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnKeyUp called";
return true;
}
bool OnTouchEvent(const TouchEvent &touchEvent)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnTouchEvent called";
return true;
}
void OnAbilityResult(int requestCode, int resultCode, const AAFwk::Want &resultData)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnAbilityResult called";
state_ = ON_ACTIVE;
}
void OnNewWant(const Want &want)
{
onNewWantCalled_ = true;
GTEST_LOG_(INFO) << "MockPageAbility::OnNewWant called";
}
void OnStart(const Want &want)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnStart called";
state_ = ON_START;
}
void OnStop()
{
GTEST_LOG_(INFO) << "MockPageAbility::OnStop called";
state_ = ON_STOP;
}
void OnActive()
{
GTEST_LOG_(INFO) << "MockPageAbility::OnActive called";
state_ = ON_ACTIVE;
}
void OnInactive()
{
GTEST_LOG_(INFO) << "MockPageAbility::OnInactive called";
state_ = ON_INACTIVE;
}
void OnForeground(const Want &want)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnForeground called";
state_ = ON_FOREGROUND;
}
void OnBackground()
{
GTEST_LOG_(INFO) << "MockPageAbility::OnBackground called";
state_ = ON_BACKGROUND;
}
sptr<IRemoteObject> OnConnect(const Want &want)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnConnect called";
state_ = ON_ACTIVE;
return nullptr;
}
void OnCommand(const AAFwk::Want &want, bool restart, int startId)
{
GTEST_LOG_(INFO) << "MockPageAbility::OnBackground called";
state_ = ON_ACTIVE;
}
int OpenFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "MockPageAbility::OpenFile called";
state_ = ON_ACTIVE;
return 1;
}
int Insert(const Uri &uri, const ValuesBucket &value)
{
GTEST_LOG_(INFO) << "MockPageAbility::Insert called";
state_ = ON_ACTIVE;
return -1;
}
int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockPageAbility::Update called";
state_ = ON_ACTIVE;
return -1;
}
int Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockPageAbility::Delete called";
state_ = ON_ACTIVE;
return -1;
}
std::shared_ptr<ResultSet> Query(
const Uri &uri, const std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "MockPageAbility::Query called";
state_ = ON_ACTIVE;
return nullptr;
}
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
GTEST_LOG_(INFO) << "MockPageAbility::GetFileTypes called";
value.push_back(mimeTypeFilter);
return value;
}
void OnRestoreAbilityState(const PacMap &inState)
{
GTEST_LOG_(INFO) << "Mock Ability::OnRestoreAbilityState called";
}
void OnSaveAbilityState(PacMap &outState)
{
GTEST_LOG_(INFO) << "Mock Ability::OnSaveAbilityState called";
}
MockPageAbility::Event state_ = UNDEFINED;
bool onNewWantCalled_ = false;
std::vector<std::string> value;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_PAGE_ABILITY_H
@@ -0,0 +1,203 @@
/*
* Copyright (c) 2021 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 "ability_impl.h"
#include <gtest/gtest.h>
#include "ability_local_record.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
void AbilityImpl::Init(std::shared_ptr<OHOSApplication> &application, const std::shared_ptr<AbilityLocalRecord> &record,
std::shared_ptr<Ability> &ability, std::shared_ptr<AbilityHandler> &handler, const sptr<IRemoteObject> &token,
std::shared_ptr<ContextDeal> &contextDeal)
{
APP_LOGI("AbilityImpl::init begin");
if (token == nullptr) {
APP_LOGE("AbilityImpl::init failed, token is nullptr");
return;
}
if (application == nullptr) {
APP_LOGE("AbilityImpl::init failed, application is nullptr");
return;
}
if (record == nullptr) {
APP_LOGE("AbilityImpl::init failed, record is nullptr");
return;
}
if (ability == nullptr) {
APP_LOGE("AbilityImpl::init failed, ability is nullptr");
return;
}
if (token == nullptr) {
APP_LOGE("AbilityImpl::init failed, token is nullptr");
return;
}
if (contextDeal == nullptr) {
APP_LOGE("AbilityImpl::init failed, contextDeal is nullptr");
return;
}
token_ = record->GetToken();
record->SetAbilityImpl(shared_from_this());
ability_ = ability;
ability_->Init(record->GetAbilityInfo(), application, handler, token);
lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL;
abilityLifecycleCallbacks_ = application;
contextDeal_ = contextDeal;
APP_LOGI("AbilityImpl::init end");
}
void AbilityImpl::Start(const Want &want)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Start called";
}
void AbilityImpl::Stop()
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Stop called";
}
void AbilityImpl::Active()
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Active called";
}
void AbilityImpl::Inactive()
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Inactive called";
}
void AbilityImpl::Foreground(const Want &want)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Foreground called";
}
void AbilityImpl::Background()
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Background called";
}
void AbilityImpl::DispatchSaveAbilityState(PacMap &outState)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::DispatchSaveAbilityState called";
}
void AbilityImpl::DispatchRestoreAbilityState(const PacMap &inState)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::DispatchRestoreAbilityState called";
}
void AbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::HandleAbilityTransaction called";
}
sptr<IRemoteObject> AbilityImpl::ConnectAbility(const Want &want)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::ConnectAbility called";
return nullptr;
}
void AbilityImpl::DisconnectAbility(const Want &want)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::DisconnectAbility called";
}
void AbilityImpl::CommandAbility(const Want &want, bool restart, int startId)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::CommandAbility called";
}
int AbilityImpl::GetCurrentState()
{
return lifecycleState_;
}
bool AbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent)
{
return false;
}
bool AbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent)
{
return false;
}
bool AbilityImpl::DoTouchEvent(const TouchEvent &touchEvent)
{
return false;
}
void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &resultData)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::SendResult called";
}
void AbilityImpl::NewWant(const Want &want)
{}
std::vector<std::string> AbilityImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
std::vector<std::string> value;
value.push_back(mimeTypeFilter);
GTEST_LOG_(INFO) << "Mock AbilityImpl::GetFileTypes called";
return value;
}
int AbilityImpl::OpenFile(const Uri &uri, const std::string &mode)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::OpenFile called";
return 1;
}
int AbilityImpl::Insert(const Uri &uri, const ValuesBucket &value)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Insert called";
return 1;
}
int AbilityImpl::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Update called";
return 1;
}
int AbilityImpl::Delete(const Uri &uri, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Delete called";
return 1;
}
std::shared_ptr<ResultSet> AbilityImpl::Query(
const Uri &uri, std::vector<std::string> &columns, const DataAbilityPredicates &predicates)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::Query called";
return nullptr;
}
std::string AbilityImpl::GetType(const Uri &uri)
{
GTEST_LOG_(INFO) << "Mock AbilityImpl::GetType called";
return "";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,76 @@
/*
* Copyright (c) 2021 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.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_SERVICE_ABILITY_H
#define FOUNDATION_APPEXECFWK_OHOS_MOCK_SERVICE_ABILITY_H
#include "ability.h"
#include <gtest/gtest.h>
namespace OHOS {
namespace AppExecFwk {
using Want = OHOS::AAFwk::Want;
class MockServiceAbility : public Ability {
public:
MockServiceAbility() = default;
virtual ~MockServiceAbility() = default;
bool OnKeyDown(int keyCode, const KeyEvent &keyEvent)
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnKeyDown called";
return true;
}
bool OnKeyUp(int keyCode, const KeyEvent &keyEvent)
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnKeyUp called";
return true;
}
bool OnTouchEvent(const TouchEvent &touchEvent)
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnTouchEvent called";
return true;
}
void OnAbilityResult(int requestCode, int resultCode, const AAFwk::Want &resultData)
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnAbilityResult called";
}
void OnNewWant(const Want &want)
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnNewWant called";
}
void OnBackground()
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnBackground called";
}
void OnStop()
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnStop called";
}
void OnStart(const Want &want)
{
GTEST_LOG_(INFO) << "MockServiceAbility::OnStart called";
}
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_MOCK_SERVICE_ABILITY_H
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2021 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 "sys_mgr_client.h"
#include "hilog_wrapper.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "string_ex.h"
namespace OHOS {
namespace AppExecFwk {
SysMrgClient::SysMrgClient() : abilityManager_(nullptr)
{}
SysMrgClient::~SysMrgClient()
{}
sptr<IRemoteObject> SysMrgClient::GetSystemAbility(const int32_t systemAbilityId)
{
if (servicesMap_[systemAbilityId] == nullptr) {
OHOS::sptr<ISystemAbilityManager> abilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (abilityManager == nullptr) {
HILOG_ERROR("%s:fail to get Registry", __func__);
return nullptr;
}
OHOS::sptr<OHOS::IRemoteObject> object = abilityManager->GetSystemAbility(systemAbilityId);
servicesMap_[systemAbilityId] = object;
}
return servicesMap_[systemAbilityId];
}
void SysMrgClient::RegisterSystemAbility(const int32_t systemAbilityId, sptr<IRemoteObject> broker)
{
servicesMap_[systemAbilityId] = broker;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,578 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include <singleton.h>
#include "ability_context.h"
#include "ohos_application.h"
#include "ability_info.h"
#include "ability.h"
#include "context_deal.h"
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "mock_ability_manager_service.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
#include "sa_mgr_client.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class AbilityContextTest : public testing::Test {
public:
AbilityContextTest() : context_(nullptr)
{}
~AbilityContextTest()
{}
std::unique_ptr<AbilityContext> context_ = nullptr;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityContextTest::SetUpTestCase(void)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase start";
OHOS::sptr<OHOS::IRemoteObject> bundleObject = new (std::nothrow) BundleMgrService();
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new (std::nothrow) OHOS::AAFwk::MockAbilityManagerService();
auto sysMgr = OHOS::DelayedSingleton<SysMrgClient>::GetInstance();
if (sysMgr == NULL) {
GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager";
return;
}
sysMgr->RegisterSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject);
sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject);
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUpTestCase end";
}
void AbilityContextTest::TearDownTestCase(void)
{}
void AbilityContextTest::SetUp(void)
{
context_ = std::make_unique<AbilityContext>();
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_SetUp end";
}
void AbilityContextTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_AbilityContext_StartAbility_0100
* @tc.name: StartAbility
* @tc.desc: Test whether startability is called normally.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_StartAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_StartAbility_0100 start";
AAFwk::Want want;
int requestCode = 0;
context_->StartAbility(want, requestCode);
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_StartAbility_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_TerminateAbility_0100
* @tc.name: TerminateAbility
* @tc.desc: Test whether TerminateAbility is called normally.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_TerminateAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_TerminateAbility_0100 start";
context_->TerminateAbility();
GTEST_LOG_(INFO) << "AppExecFwk_AbilityContext_TerminateAbility_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetCallingAbility_0100
* @tc.name: GetCallingAbility
* @tc.desc: Test whether the return value of getcallingability is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetCallingAbility_0100, Function | MediumTest | Level1)
{
// init
AAFwk::Want want;
OHOS::AppExecFwk::ElementName elementName;
elementName.SetBundleName(std::string("App.System.Test.bundleName_0127"));
elementName.SetAbilityName(std::string("App.System.Test.AbilityName_0127"));
want.SetElement(elementName);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
// start
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::PAGE;
std::shared_ptr<AbilityHandler> handler = nullptr;
ability->Init(abilityInfo, nullptr, handler, nullptr);
ability->StartAbilityForResult(want, -1);
ability->SetCallingContext("", "", std::string("App.System.Test.AbilityName_0127"));
std::shared_ptr<ElementName> elementNameTest = ability->GetCallingAbility();
std::string abilityName;
if (elementNameTest != nullptr) {
abilityName = elementNameTest->GetAbilityName();
}
// Test
EXPECT_EQ(abilityName, std::string("App.System.Test.AbilityName_0127"));
}
/**
* @tc.number: AaFwk_AbilityContext_GetApplicationInfo_0100
* @tc.name: GetApplicationInfo
* @tc.desc: Test whether the getapplicationinfo return value is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetApplicationInfo_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationInfo> info = std::make_shared<ApplicationInfo>();
std::string name = "WeChat";
info->name = name;
deal->SetApplicationInfo(info);
context_->AttachBaseContext(deal);
EXPECT_STREQ(name.c_str(), context_->GetApplicationInfo()->name.c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetCacheDir_0100
* @tc.name: GetCacheDir
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getcachedir is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetCacheDir_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationInfo> info = std::make_shared<ApplicationInfo>();
std::string dir = "CacheDir";
info->cacheDir = dir;
deal->SetApplicationInfo(info);
context_->AttachBaseContext(deal);
EXPECT_STREQ(dir.c_str(), context_->GetCacheDir().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetCodeCacheDir_0100
* @tc.name: GetCodeCacheDir
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getcodechedir is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetCodeCacheDir_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationInfo> info = std::make_shared<ApplicationInfo>();
std::string dir = "CacheDir";
info->dataDir = dir;
deal->SetApplicationInfo(info);
context_->AttachBaseContext(deal);
std::string dirCompare = "CacheDir/code_cache";
EXPECT_STREQ(dirCompare.c_str(), context_->GetCodeCacheDir().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetDatabaseDir_0100
* @tc.name: GetDatabaseDir
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getdatabasedir is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetDatabaseDir_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationInfo> info = std::make_shared<ApplicationInfo>();
std::string dir = "dataBaseDir";
info->dataBaseDir = dir;
deal->SetApplicationInfo(info);
context_->AttachBaseContext(deal);
EXPECT_STREQ(dir.c_str(), context_->GetDatabaseDir().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetDataDir_0100
* @tc.name: GetDataDir
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getdatadir is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetDataDir_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationInfo> info = std::make_shared<ApplicationInfo>();
std::string dir = "dataDir";
info->dataDir = dir;
deal->SetApplicationInfo(info);
context_->AttachBaseContext(deal);
EXPECT_STREQ(dir.c_str(), context_->GetDataDir().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetBundleManager_0100
* @tc.name: GetBundleManager
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getbundlemanager is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetBundleManager_0100, Function | MediumTest | Level3)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
context_->AttachBaseContext(deal);
sptr<IBundleMgr> ptr = context_->GetBundleManager();
EXPECT_NE(nullptr, ptr);
}
/**
* @tc.number: AaFwk_AbilityContext_GetBundleCodePath_0100
* @tc.name: GetBundleCodePath
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getbundlecodepath is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetBundleCodePath_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string codePath = "hello";
appInfo->codePath = codePath;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_STREQ(codePath.c_str(), context_->GetBundleCodePath().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetBundleName_0100
* @tc.name: GetBundleName
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getbundlename is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetBundleName_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string name = "hello";
appInfo->bundleName = name;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_STREQ(name.c_str(), context_->GetBundleName().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetBundleResourcePath_0100
* @tc.name: GetBundleResourcePath
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getbundleresourcepath is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetBundleResourcePath_0100, Function | MediumTest | Level1)
{
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::string resourcePath = "hello";
abilityInfo->resourcePath = resourcePath;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(deal);
EXPECT_STREQ(resourcePath.c_str(), context_->GetBundleResourcePath().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetApplicationContext_0100
* @tc.name: GetApplicationContext
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getapplicationcontext is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetApplicationContext_0100, Function | MediumTest | Level3)
{
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationContext(application);
context_->AttachBaseContext(deal);
EXPECT_NE(nullptr, context_->GetApplicationContext());
}
/**
* @tc.number: AaFwk_AbilityContext_GetContext_0100
* @tc.name: GetContext
* @tc.desc: Test the attachbasecontext call to verify whether the getcontext return value is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetContext_0100, Function | MediumTest | Level1)
{
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::string name = "hello";
abilityInfo->name = name;
deal->SetAbilityInfo(abilityInfo);
std::shared_ptr<Context> context(ability);
deal->SetContext(context);
ability->AttachBaseContext(deal);
EXPECT_STREQ(name.c_str(), ability->GetContext()->GetAbilityInfo()->name.c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetAbilityManager_0100
* @tc.name: GetAbilityManager
* @tc.desc: Test the attachbasecontext call to verify whether the return value of getabilitymanager is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetAbilityManager_0100, Function | MediumTest | Level3)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
context_->AttachBaseContext(deal);
sptr<AAFwk::IAbilityManager> ptr = context_->GetAbilityManager();
EXPECT_NE(nullptr, ptr);
}
/**
* @tc.number: AaFwk_AbilityContext_GetProcessInfo_0100
* @tc.name: GetProcessInfo
* @tc.desc: Test the attachbasecontext call to verify that the getprocessinfo return value is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetProcessInfo_0100, Function | MediumTest | Level1)
{
std::string name = "OHOS";
pid_t id = 0;
ProcessInfo info(name, id);
std::shared_ptr<ProcessInfo> processInfo = std::make_shared<ProcessInfo>(info);
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetProcessInfo(processInfo);
context_->AttachBaseContext(deal);
EXPECT_STREQ(name.c_str(), context_->GetProcessInfo()->GetProcessName().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetAppType_0100
* @tc.name: GetAppType
* @tc.desc: Test the attachbasecontext call to verify that the getapptype return value is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetAppType_0100, Function | MediumTest | Level1)
{
std::string empty = "system";
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationInfo> info = std::make_shared<ApplicationInfo>();
info->bundleName = "hello";
deal->SetApplicationInfo(info);
context_->AttachBaseContext(deal);
EXPECT_STREQ(empty.c_str(), context_->GetAppType().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetAbilityInfo_0100
* @tc.name: GetAbilityInfo
* @tc.desc: Test the attachbasecontext call to verify that the getabilityinfo return value is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetAbilityInfo_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::string name = "hello";
abilityInfo->name = name;
deal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(deal);
EXPECT_STREQ(name.c_str(), context_->GetAbilityInfo()->name.c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetElementName_0100
* @tc.name: GetElementName
* @tc.desc: Verify that the getelementname return value is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetElementName_0100, Function | MediumTest | Level3)
{
EXPECT_EQ(nullptr, context_->GetElementName());
}
/**
* @tc.number: AaFwk_AbilityContext_GetElementName_0200
* @tc.name: GetElementName
* @tc.desc: Test getelementname exception status.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetElementName_0200, Function | MediumTest | Level3)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::string name = "abilityName";
abilityInfo->name = name;
deal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(deal);
EXPECT_STREQ(name.c_str(), context_->GetElementName()->GetAbilityName().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetCallingBundle_0100
* @tc.name: GetCallingBundle
* @tc.desc: Test getcallingbundle exception state.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetCallingBundle_0100, Function | MediumTest | Level3)
{
std::string empty = "";
EXPECT_STREQ(empty.c_str(), context_->GetCallingBundle().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetCallingBundle_0200
* @tc.name: GetCallingBundle
* @tc.desc: Test whether the return value of getcallingbundle is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetCallingBundle_0200, Function | MediumTest | Level1)
{
Want want;
std::string bundleName = "BundleName";
std::string abilityName = "abilityName";
want.SetElementName(bundleName, abilityName);
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::PAGE;
std::shared_ptr<AbilityHandler> handler = nullptr;
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ability->Init(abilityInfo, nullptr, handler, nullptr);
ability->StartAbilityForResult(want, -1);
ability->SetCallingContext("", "BundleName", "");
EXPECT_STREQ(bundleName.c_str(), ability->GetCallingBundle().c_str());
}
/**
* @tc.number: AaFwk_AbilityContext_GetCallingAbility_0200
* @tc.name: GetCallingAbility
* @tc.desc: Test getcallingability exception status.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_GetCallingAbility_0200, Function | MediumTest | Level3)
{
EXPECT_NE(nullptr, context_->GetCallingAbility());
}
/**
* @tc.number: AaFwk_AbilityContext_ConnectAbility_0100
* @tc.name: ConnectAbility
* @tc.desc: Test the attachbasecontext call to verify that the return value of connectability is true.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_ConnectAbility_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::SERVICE;
deal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(deal);
Want want;
bool ret = context_->ConnectAbility(want, nullptr);
EXPECT_TRUE(ret);
}
/**
* @tc.number: AaFwk_AbilityContext_ConnectAbility_0200
* @tc.name: ConnectAbility
* @tc.desc: Test the attachbasecontext call to verify that the return value of connectability is false.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_ConnectAbility_0200, Function | MediumTest | Level3)
{
Want want;
bool ret = context_->ConnectAbility(want, nullptr);
EXPECT_FALSE(ret);
}
/**
* @tc.number: AaFwk_AbilityContext_DisconnectAbility_0100
* @tc.name: DisconnectAbility
* @tc.desc: Test whether the disconnectability is called normally.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_DisconnectAbility_0100, Function | MediumTest | Level1)
{
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::SERVICE;
deal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(deal);
context_->DisconnectAbility(nullptr);
}
/**
* @tc.number: AaFwk_AbilityContext_StopAbility_0100
* @tc.name: StopAbility
* @tc.desc: Test the attachbasecontext call to verify that the return value of stopability is true.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_StopAbility_0100, Function | MediumTest | Level1)
{
Want want;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::SERVICE;
deal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(deal);
bool ret = context_->StopAbility(want);
EXPECT_TRUE(ret);
}
/**
* @tc.number: AaFwk_AbilityContext_StopAbility_0200
* @tc.name: StopAbility
* @tc.desc: Test the attachbasecontext call to verify that the return value of stopability is false.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_StopAbility_0200, Function | MediumTest | Level3)
{
Want want;
bool ret = context_->StopAbility(want);
EXPECT_FALSE(ret);
}
/**
* @tc.number: AaFwk_AbilityContext_TerminateAbility_0200
* @tc.name: TerminateAbility
* @tc.desc: Test whether terminateability is called normally.
*/
HWTEST_F(AbilityContextTest, AaFwk_AbilityContext_TerminateAbility_0200, Function | MediumTest | Level1)
{
int code = 1992;
context_->TerminateAbility(code);
}
/**
* @tc.number: AaFwk_Ability_GetHapModuleInfo_0100
* @tc.name: GetHapModuleInfo
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextTest, AaFwk_Ability_GetHapModuleInfo_0100, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetHapModuleInfo_0100 start";
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::string name = "Captain";
abilityInfo->name = name;
contextDeal->SetAbilityInfo(abilityInfo);
context_->AttachBaseContext(contextDeal);
Want want;
std::shared_ptr<HapModuleInfo> info = context_->GetHapModuleInfo();
EXPECT_STREQ(info->name.c_str(), name.c_str());
GTEST_LOG_(INFO) << "AaFwk_Ability_GetHapModuleInfo_0100 end";
}
} // namespace AppExecFwk
} // namespace OHOS
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,166 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include "ability_lifecycle_executor.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class AbilityLifecycleExecutorTest : public testing::Test {
public:
AbilityLifecycleExecutorTest() : abilityLifecycleExecutor_(nullptr)
{}
~AbilityLifecycleExecutorTest()
{}
std::shared_ptr<AbilityLifecycleExecutor> abilityLifecycleExecutor_;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityLifecycleExecutorTest::SetUpTestCase(void)
{}
void AbilityLifecycleExecutorTest::TearDownTestCase(void)
{}
void AbilityLifecycleExecutorTest::SetUp(void)
{
abilityLifecycleExecutor_ = std::make_shared<AbilityLifecycleExecutor>();
}
void AbilityLifecycleExecutorTest::TearDown(void)
{}
// AaFwk_AbilityLifecycleExecutor_GetState
/**
* @tc.number: AaFwk_AbilityLifecycleExecutor_GetState_0100
* @tc.name: GetState
* @tc.desc: Verify that the return value of getstate is UNINITIALIZED.
*/
HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_GetState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_GetState_0100 start";
AbilityLifecycleExecutor::LifecycleState state =
(AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_GetState_0100 end";
}
/**
* @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0100
* @tc.name: DispatchLifecycleState
* @tc.desc: Test whether attachbasecontext is called normally,
* and verify whether the return value of getdatabasedir is ACTIVE.
*/
HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0100 start";
AbilityLifecycleExecutor::LifecycleState targetState = AbilityLifecycleExecutor::LifecycleState::ACTIVE;
abilityLifecycleExecutor_->DispatchLifecycleState(targetState);
AbilityLifecycleExecutor::LifecycleState state =
(AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
EXPECT_EQ(targetState, state);
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0100 end";
}
/**
* @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0200
* @tc.name: DispatchLifecycleState
* @tc.desc: Test whether attachbasecontext is called normally,
* and verify whether the return value of getdatabasedir is BACKGROUND.
*/
HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0200 start";
AbilityLifecycleExecutor::LifecycleState targetState = AbilityLifecycleExecutor::LifecycleState::BACKGROUND;
abilityLifecycleExecutor_->DispatchLifecycleState(targetState);
AbilityLifecycleExecutor::LifecycleState state =
(AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
EXPECT_EQ(targetState, state);
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0200 end";
}
/**
* @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0300
* @tc.name: DispatchLifecycleState
* @tc.desc: Test whether attachbasecontext is called normally,
* and verify whether the return value of getdatabasedir is INACTIVE.
*/
HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0300, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0300 start";
AbilityLifecycleExecutor::LifecycleState targetState = AbilityLifecycleExecutor::LifecycleState::INACTIVE;
abilityLifecycleExecutor_->DispatchLifecycleState(targetState);
AbilityLifecycleExecutor::LifecycleState state =
(AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
EXPECT_EQ(targetState, state);
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0300 end";
}
/**
* @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0400
* @tc.name: DispatchLifecycleState
* @tc.desc: Test whether attachbasecontext is called normally,
* and verify whether the return value of getdatabasedir is INITIAL.
*/
HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0400, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0400 start";
AbilityLifecycleExecutor::LifecycleState targetState = AbilityLifecycleExecutor::LifecycleState::INITIAL;
abilityLifecycleExecutor_->DispatchLifecycleState(targetState);
AbilityLifecycleExecutor::LifecycleState state =
(AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
EXPECT_EQ(targetState, state);
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0400 end";
}
/**
* @tc.number: AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0500
* @tc.name: DispatchLifecycleState
* @tc.desc: Test whether attachbasecontext is called normally,
* and verify whether the return value of getdatabasedir is UNINITIALIZED.
*/
HWTEST_F(AbilityLifecycleExecutorTest, AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0500, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0500 start";
AbilityLifecycleExecutor::LifecycleState targetState = AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED;
abilityLifecycleExecutor_->DispatchLifecycleState(targetState);
AbilityLifecycleExecutor::LifecycleState state =
(AbilityLifecycleExecutor::LifecycleState)abilityLifecycleExecutor_->GetState();
EXPECT_EQ(targetState, state);
GTEST_LOG_(INFO) << "AaFwk_AbilityLifecycleExecutor_DispatchLifecycleState_0500 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,368 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include "ability_lifecycle.h"
#include "mock_lifecycle_observer.h"
#include "want.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
using Want = OHOS::AAFwk::Want;
class LifeCycleTest : public testing::Test {
public:
LifeCycleTest() : lifeCycle_(nullptr)
{}
~LifeCycleTest()
{}
std::shared_ptr<LifeCycle> lifeCycle_;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void LifeCycleTest::SetUpTestCase(void)
{}
void LifeCycleTest::TearDownTestCase(void)
{}
void LifeCycleTest::SetUp(void)
{
lifeCycle_ = std::make_shared<LifeCycle>();
}
void LifeCycleTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_LifeCycle_GetLifecycleState_0100
* @tc.name: GetLifecycleState
* @tc.desc: Determine whether the return value of getlifecycle state is equal to undefined.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_GetLifecycleState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_GetLifecycleState_0100 start";
LifeCycle::Event state = lifeCycle_->GetLifecycleState();
EXPECT_EQ(LifeCycle::Event::UNDEFINED, state);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_GetLifecycleState_0100 end";
}
/**
* @tc.number: AaFwk_LifeCycle_AddObserver_0100
* @tc.name: AddObserver
* @tc.desc: Determine whether the return value of getlifecycle state is equal to undefined.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_AddObserver_0100, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_AddObserver_0100 start";
lifeCycle_->AddObserver(nullptr);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_AddObserver_0100 end";
}
/**
* @tc.number: AaFwk_LifeCycle_AddObserver_0200
* @tc.name: AddObserver
* @tc.desc: Determine whether the return value of getlifecycle state is equal to undefined.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_AddObserver_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_AddObserver_0200 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_AddObserver_0200 end";
}
/**
* @tc.number: AaFwk_LifeCycle_RemoveObserver_0100
* @tc.name: RemoveObserver
* @tc.desc: Test the removeobserver exception state.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_RemoveObserver_0100, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_RemoveObserver_0100 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
lifeCycle_->RemoveObserver(nullptr);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_RemoveObserver_0100 end";
}
/**
* @tc.number: AaFwk_LifeCycle_RemoveObserver_0200
* @tc.name: RemoveObserver
* @tc.desc: Test whether addobserver is added and confirm whether removeobserver is deleted.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_RemoveObserver_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_RemoveObserver_0200 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
lifeCycle_->RemoveObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_RemoveObserver_0200 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0100
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0100 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::UNDEFINED, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0100 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0200
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0200 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0200 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0300
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0300, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0300 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0300 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0400
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0400, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0400 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0400 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0500
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0500, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0500 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0500 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0600
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0600, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0600 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_START, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_006 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_want_0700
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_want_0700, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0700 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
Want want;
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_STOP, want);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_want_0700 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0100
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0100 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::UNDEFINED);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0100 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0200
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0200 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_ACTIVE);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0200 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0300
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0300, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0300 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_BACKGROUND);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0300 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0400
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0400, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0400 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_FOREGROUND);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0400 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0500
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0500, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0500 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_INACTIVE);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0500 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0600
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0600, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0600 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_START);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0600 end";
}
/**
* @tc.number: AaFwk_LifeCycle_DispatchLifecycle_event_0700
* @tc.name: DispatchLifecycle
* @tc.desc: Determine whether the current action is correct through dispatchlifecycle.
*/
HWTEST_F(LifeCycleTest, AaFwk_LifeCycle_DispatchLifecycle_event_0700, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0700 start";
std::shared_ptr<MockLifecycleObserver> observer = std::make_shared<MockLifecycleObserver>();
lifeCycle_->AddObserver(observer);
lifeCycle_->DispatchLifecycle(LifeCycle::Event::ON_STOP);
GTEST_LOG_(INFO) << "AaFwk_LifeCycle_DispatchLifecycle_event_0700 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,200 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include "ability_context.h"
#include "context_deal.h"
#include "ability_info.h"
#include "ability.h"
#include "mock_bundle_manager.h"
#include "sys_mgr_client.h"
#include "sa_mgr_client.h"
#include "mock_ability_manager_service.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class AbilityPermissionTest : public testing::Test {
public:
AbilityPermissionTest() : context_(nullptr)
{}
~AbilityPermissionTest()
{}
std::shared_ptr<AbilityContext> context_;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityPermissionTest::SetUpTestCase(void)
{
OHOS::sptr<OHOS::IRemoteObject> bundleObject = new BundleMgrService();
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new OHOS::AAFwk::MockAbilityManagerService();
auto sysMgr = OHOS::DelayedSingleton<SysMrgClient>::GetInstance();
if (sysMgr == NULL) {
GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager";
return;
}
sysMgr->RegisterSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject);
sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject);
}
void AbilityPermissionTest::TearDownTestCase(void)
{}
void AbilityPermissionTest::SetUp(void)
{
context_ = std::make_shared<AbilityContext>();
}
void AbilityPermissionTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_AbilityPermissionTest_VerifySelfPermission_0100
* @tc.name: VerifySelfPermission
* @tc.desc: Verify that the verifyselfpermission return value is correct.
*/
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifySelfPermission_0100, Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
return;
}
std::string permission_name("permission_VerifySelfPermission");
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string name = "hello";
appInfo->bundleName = name;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_EQ(0, context_->VerifySelfPermission(permission_name));
}
/**
* @tc.number: AaFwk_AbilityPermissionTest_VerifyCallingOrSelfPermission_0100
* @tc.name: VerifyCallingOrSelfPermission
* @tc.desc: Verify that the VerifyCallingOrSelfPermission return value is correct.
*/
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifyCallingOrSelfPermission_0100, Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
return;
}
std::string permission_name("permission_VerifyCallingOrSelfPermission");
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string name = "hello";
appInfo->bundleName = name;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_EQ(0, context_->VerifyCallingOrSelfPermission(permission_name));
}
/**
* @tc.number: AaFwk_AbilityPermissionTest_VerifyPermission_0100
* @tc.name: VerifyPermission
* @tc.desc: Verify that the VerifyPermission return value is correct.
*/
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifyPermission_0100, Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
return;
}
std::string permission_name("permission_VerifyPermission");
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string name = "hello";
appInfo->bundleName = name;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_EQ(0, context_->VerifyPermission(permission_name, 0, 10));
}
/**
* @tc.number: AaFwk_AbilityPermissionTest_CanRequestPermission_0100
* @tc.name: CanRequestPermission
* @tc.desc: Verify that the CanRequestPermission return value is correct.
*/
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_CanRequestPermission_0100, Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
return;
}
std::string permission_name("permission_CanRequestPermission");
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string name = "hello";
appInfo->bundleName = name;
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_EQ(true, context_->CanRequestPermission(permission_name));
}
/**
* @tc.number: AaFwk_AbilityPermissionTest_RequestPermissionsFromUser_0100
* @tc.name: RequestPermissionsFromUser
* @tc.desc: Verify that requestpermissionsfromuser is called.
*/
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_RequestPermissionsFromUser_0100, Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
return;
}
std::shared_ptr<ApplicationInfo> appInfo = std::make_shared<ApplicationInfo>();
std::string name = "hello";
appInfo->bundleName = name;
std::vector<std::string> permissions;
permissions.emplace_back("permission_1");
permissions.emplace_back("permission_2");
permissions.emplace_back("permission_3");
std::shared_ptr<ContextDeal> deal = std::make_shared<ContextDeal>();
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
context_->RequestPermissionsFromUser(permissions, 1004);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,854 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include "ability.h"
#include "ability_local_record.h"
#include "ability_handler.h"
#include "ability_info.h"
#include "ability_start_setting.h"
#include "context_deal.h"
#include "mock_page_ability.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
using OHOS::Parcel;
class AbilityBaseTest : public testing::Test {
public:
AbilityBaseTest() : ability_(nullptr)
{}
~AbilityBaseTest()
{}
std::shared_ptr<Ability> ability_;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityBaseTest::SetUpTestCase(void)
{}
void AbilityBaseTest::TearDownTestCase(void)
{}
void AbilityBaseTest::SetUp(void)
{
ability_ = std::make_shared<Ability>();
}
void AbilityBaseTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_Ability_Name_0100
* @tc.name: GetAbilityName
* @tc.desc: Verify that the return value of getabilityname is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_Name_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_Name_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "ability";
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
EXPECT_STREQ(abilityInfo->name.c_str(), ability_->GetAbilityName().c_str());
GTEST_LOG_(INFO) << "AaFwk_Ability_Name_0100 end";
}
/**
* @tc.number: AaFwk_Ability_GetLifecycle_0100
* @tc.name: GetLifecycle
* @tc.desc: Verify that the return value of getlifecycle is not empty.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetLifecycle_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetLifecycle_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_NE(lifeCycle, nullptr);
GTEST_LOG_(INFO) << "AaFwk_Ability_GetLifecycle_0100 end";
}
/**
* @tc.number: AaFwk_Ability_GetState_0100
* @tc.name: GetState
* @tc.desc: Verify that the return value of getstate is equal to active.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetState_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->OnActive();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::ACTIVE, state);
GTEST_LOG_(INFO) << "AaFwk_Ability_GetState_0100 end";
}
/**
* @tc.number: AaFwk_Ability_GetState_0200
* @tc.name: GetState
* @tc.desc: Getstate exception test.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetState_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetState_0200 start";
ability_->OnActive();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
GTEST_LOG_(INFO) << "AaFwk_Ability_GetState_0200 end";
}
/**
* @tc.number: AaFwk_Ability_Dump_0100
* @tc.name: Dump
* @tc.desc: Test dump normal flow.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_Dump_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_Dump_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
std::string extra = "";
ability_->Dump(extra);
GTEST_LOG_(INFO) << "AaFwk_Ability_Dump_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnNewWant_0100
* @tc.name: OnNewWant
* @tc.desc: Test whether onnewwant can be called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnNewWant_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnNewWant_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
Want want;
ability_->OnNewWant(want);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnNewWant_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnRestoreAbilityState_0100
* @tc.name: OnRestoreAbilityState
* @tc.desc: Test whether onnewwant can be called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnRestoreAbilityState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnRestoreAbilityState_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
PacMap inState;
ability_->OnRestoreAbilityState(inState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnRestoreAbilityState_0100 end";
}
/**
* @tc.number: AaFwk_Ability_GetAbilityName_0100
* @tc.name: GetAbilityName
* @tc.desc: Verify that the getabilityname return value is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetAbilityName_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetAbilityName_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
std::string name = "LOL";
abilityInfo->name = name;
ability_->Init(abilityInfo, application, handler, token);
EXPECT_STREQ(ability_->GetAbilityName().c_str(), name.c_str());
GTEST_LOG_(INFO) << "AaFwk_Ability_GetAbilityName_0100 end";
}
/**
* @tc.number: AaFwk_Ability_GetApplication_0100
* @tc.name: GetApplication
* @tc.desc: Verify that the getapplication return value is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetApplication_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetApplication_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
std::shared_ptr<OHOSApplication> applicationRet = ability_->GetApplication();
EXPECT_EQ(application, applicationRet);
GTEST_LOG_(INFO) << "AaFwk_Ability_GetApplication_0100 end";
}
/**
* @tc.number: AaFwk_Ability_GetApplication_0200
* @tc.name: GetApplication
* @tc.desc: Test getapplication exception status.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetApplication_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_GetApplication_0200 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, nullptr, handler, token);
std::shared_ptr<OHOSApplication> application = ability_->GetApplication();
EXPECT_EQ(application, nullptr);
GTEST_LOG_(INFO) << "AaFwk_Ability_GetApplication_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnSaveAbilityState_0100
* @tc.name: OnSaveAbilityState
* @tc.desc: Test whether onsaveabilitystate is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnSaveAbilityState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnSaveAbilityState_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
PacMap outState;
ability_->OnSaveAbilityState(outState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnSaveAbilityState_0100 end";
}
/**
* @tc.number: AaFwk_Ability_SetWant_GetWant_0100
* @tc.name: OnSaveAbilityState
* @tc.desc: Verify that setwant creates the object normally,
* and judge whether the return value of getwant is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_SetWant_GetWant_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_SetWant_GetWant_0100 start";
std::string abilityName = "Ability";
std::string bundleName = "Bundle";
AAFwk::Want want;
want.SetElementName(bundleName, abilityName);
ability_->SetWant(want);
EXPECT_STREQ(ability_->GetWant()->GetElement().GetBundleName().c_str(), bundleName.c_str());
EXPECT_STREQ(ability_->GetWant()->GetElement().GetAbilityName().c_str(), abilityName.c_str());
GTEST_LOG_(INFO) << "AaFwk_Ability_SetWant_GetWant_0100 end";
}
/**
* @tc.number: AaFwk_Ability_SetResult_0100
* @tc.name: SetResult
* @tc.desc: Test whether setresult is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_SetResult_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_SetResult_0100 start";
int resultCode = 0;
Want want;
std::string action = "Action";
want.SetAction(action);
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->SetResult(resultCode, want);
GTEST_LOG_(INFO) << "AaFwk_Ability_SetResult_0100 end";
}
/**
* @tc.number: AaFwk_Ability_StartAbilityForResult_0100
* @tc.name: StartAbilityForResult
* @tc.desc: Test whether startabilityforesult is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_StartAbilityForResult_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbilityForResult_0100 start";
int resultCode = 0;
Want want;
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->StartAbilityForResult(want, resultCode);
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbilityForResult_0100 end";
}
/**
* @tc.number: AaFwk_Ability_StartAbility_0100
* @tc.name: StartAbility
* @tc.desc: Test whether startability is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_StartAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbility_0100 start";
Want want;
ability_->StartAbility(want);
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbility_0100 end";
}
/**
* @tc.number: AaFwk_Ability_TerminateAbility_0100
* @tc.name: TerminateAbility
* @tc.desc: Test whether terminateability is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_TerminateAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAbility_0100 start";
ability_->TerminateAbility();
GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAbility_0100 end";
}
#ifdef WMS_COMPILE
HWTEST_F(AbilityBaseTest, AaFwk_Ability_GetWindow_001, Function | MediumTest | Level1)
{
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
}
#endif // WMS_COMPILE
/**
* @tc.number: AaFwk_Ability_OnStart_0100
* @tc.name: OnStart
* @tc.desc: Test whether OnStart is called normally and verify whether the members are correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStart_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStart_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
Want want;
ability_->OnStart(want);
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INACTIVE, state);
EXPECT_EQ(LifeCycle::Event::ON_START, lifeCycleState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStart_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnStart_0200
* @tc.name: OnStart
* @tc.desc: Test the OnStart exception.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStart_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStart_0200 start";
Want want;
ability_->OnStart(want);
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
EXPECT_EQ(nullptr, lifeCycle);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStart_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnStop_0100
* @tc.name: OnStop
* @tc.desc: Test whether onstop is called normally and verify whether the members are correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStop_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStop_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->OnStop();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INITIAL, state);
EXPECT_EQ(LifeCycle::Event::ON_STOP, lifeCycleState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStop_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnStop_0200
* @tc.name: OnStop
* @tc.desc: Test the OnStop exception.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStop_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStop_0200 start";
ability_->OnStop();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
EXPECT_EQ(nullptr, lifeCycle);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStop_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnActive_0100
* @tc.name: OnActive
* @tc.desc: Test whether onactive is called normally and verify whether the member is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnActive_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnActive_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->OnActive();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::ACTIVE, state);
EXPECT_EQ(LifeCycle::Event::ON_ACTIVE, lifeCycleState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnActive_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnActive_0200
* @tc.name: OnActive
* @tc.desc: Test the OnActive exception.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnActive_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnActive_0200 start";
ability_->OnActive();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
EXPECT_EQ(nullptr, lifeCycle);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnActive_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnInactive_0100
* @tc.name: OnInactive
* @tc.desc: Test whether oninactive is called normally and verify whether the member is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnInactive_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnInactive_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->OnInactive();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INACTIVE, state);
EXPECT_EQ(LifeCycle::Event::ON_INACTIVE, lifeCycleState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnInactive_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnInactive_0200
* @tc.name: OnInactive
* @tc.desc: Test the OnInactive exception.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnInactive_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnInactive_0200 start";
ability_->OnInactive();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
EXPECT_EQ(nullptr, lifeCycle);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnInactive_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnForeground_0100
* @tc.name: OnForeground
* @tc.desc: Test whether onforegroup is called normally, and verify whether the member is correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnForeground_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnForeground_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
Want want;
ability_->OnForeground(want);
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INACTIVE, state);
EXPECT_EQ(LifeCycle::Event::ON_FOREGROUND, lifeCycleState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnForeground_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnForeground_0200
* @tc.name: OnForeground
* @tc.desc: Test the OnInactive exception.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnForeground_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnForeground_0200 start";
Want want;
ability_->OnForeground(want);
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
EXPECT_EQ(nullptr, lifeCycle);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnForeground_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnBackground_0100
* @tc.name: OnBackground
* @tc.desc: Test whether onbackground is called normally and verify whether the members are correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackground_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
ability_->OnBackground();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::BACKGROUND, state);
EXPECT_EQ(LifeCycle::Event::ON_BACKGROUND, lifeCycleState);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackground_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnBackground_0200
* @tc.name: OnBackground
* @tc.desc: Test the OnBackground exception.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackground_0200 start";
ability_->OnBackground();
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
std::shared_ptr<LifeCycle> lifeCycle = ability_->GetLifecycle();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state);
EXPECT_EQ(nullptr, lifeCycle);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackground_0200 end";
}
/**
* @tc.number: AaFwk_Ability_OnConnect_0100
* @tc.name: OnConnect
* @tc.desc: Test whether onconnect is called normally and verify whether the members are correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnConnect_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnConnect_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
Want want;
ability_->OnConnect(want);
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::ACTIVE, state);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnConnect_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnCommond_0100
* @tc.name: OnCommand
* @tc.desc: Test whether oncommand is called normally and verify whether the members are correct.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnCommond_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnCommond_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
AbilityType type = AbilityType::PAGE;
abilityInfo->type = type;
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityHandler> handler = nullptr;
sptr<IRemoteObject> token = nullptr;
ability_->Init(abilityInfo, application, handler, token);
Want want;
ability_->OnCommand(want, false, 0);
AbilityLifecycleExecutor::LifecycleState state = ability_->GetState();
EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::ACTIVE, state);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnCommond_0100 end";
}
/**
* @tc.number: AaFwk_Ability_OnDisconnect_0100
* @tc.name: OnDisconnect
* @tc.desc: Test whether ondisconnect is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnDisconnect_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_OnDisconnect_0100 start";
Want want;
ability_->OnDisconnect(want);
GTEST_LOG_(INFO) << "AaFwk_Ability_OnDisconnect_0100 end";
}
/**
* @tc.number: AaFwk_Ability_StartAbilitySetting_0100
* @tc.name: StartAbility
* @tc.desc: Test whether startability is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_StartAbilitySetting_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbilitySetting_0100 start";
Want want;
std::shared_ptr<AbilityStartSetting> setting = AbilityStartSetting::GetEmptySetting();
ability_->StartAbility(want, *setting.get());
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbilitySetting_0100 end";
}
/**
* @tc.number: AaFwk_Ability_StartAbilitySetting_0200
* @tc.name: StartAbility
* @tc.desc: Test startability exception status.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_StartAbilitySetting_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbilitySetting_0200 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AbilityType::PAGE;
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
ability_->Init(abilityInfo, nullptr, handler, nullptr);
Want want;
std::shared_ptr<AbilityStartSetting> setting = AbilityStartSetting::GetEmptySetting();
ability_->StartAbility(want, *setting.get());
GTEST_LOG_(INFO) << "AaFwk_Ability_StartAbilitySetting_0200 end";
}
/**
* @tc.number: AaFwk_Ability_PostTask_0100
* @tc.name: PostTask
* @tc.desc: Test whether posttask is called normally.
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_PostTask_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_PostTask_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AbilityType::PAGE;
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
ability_->Init(abilityInfo, nullptr, handler, nullptr);
auto task = []() { GTEST_LOG_(INFO) << "AaFwk_Ability_PostTask_001 task called"; };
ability_->PostTask(task, 1000);
GTEST_LOG_(INFO) << "AaFwk_Ability_PostTask_0100 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,401 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include <functional>
#include "ability_thread.h"
#include "ability_state.h"
#include "ability_loader.h"
#include "app_log_wrapper.h"
#include "ability_impl_factory.h"
#include "ability_impl.h"
#include "ability.h"
#include "context_deal.h"
#include "mock_page_ability.h"
#include "mock_ability_token.h"
#include "mock_ability_lifecycle_callbacks.h"
#include "mock_ability_impl.h"
#include "mock_ability_thread.h"
#include "mock_data_ability.h"
#include "ohos_application.h"
#include "page_ability_impl.h"
#include "uri.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
REGISTER_AA(MockDataAbility)
REGISTER_AA(MockPageAbility)
class AbilityThreadTest : public testing::Test {
public:
AbilityThreadTest() : abilitythread_(nullptr)
{}
~AbilityThreadTest()
{
abilitythread_ = nullptr;
}
AbilityThread *abilitythread_;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityThreadTest::SetUpTestCase(void)
{}
void AbilityThreadTest::TearDownTestCase(void)
{}
void AbilityThreadTest::SetUp(void)
{
GTEST_LOG_(INFO) << "AbilityThreadTest SetUp";
}
void AbilityThreadTest::TearDown(void)
{
GTEST_LOG_(INFO) << "AbilityThreadTest TearDown";
}
/**
* @tc.number: AaFwk_AbilityThread_Query_0100
* @tc.name: Query
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Query_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Query_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
std::shared_ptr<MockDataAbility> mockdataability = std::make_shared<MockDataAbility>();
Uri uri("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::vector<std::string> columns;
columns.push_back("string1");
DataAbilityPredicates predicates("test");
std::shared_ptr<ResultSet> resultSet = abilitythread->Query(uri, columns, predicates);
EXPECT_STREQ(resultSet->testInf_.c_str(), "TestResultSet");
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Query_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Query_0200
* @tc.name: Query
* @tc.desc: Validate when normally entering a string.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Query_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Query_0200 start";
AbilityThread *abilitythread = new AbilityThread();
std::shared_ptr<AbilityImpl> abilityimpl = std::make_shared<AbilityImpl>();
int valuetest = -1;
int value = 0;
Uri uri("\nullptr");
std::vector<std::string> columns;
columns.push_back("string1");
DataAbilityPredicates predicates("test");
abilitythread->Query(uri, columns, predicates);
valuetest = abilityimpl->GetCurrentState();
EXPECT_EQ(value, valuetest);
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Query_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_GetFileTypes_0100
* @tc.name: GetFileTypes
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_GetFileTypes_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_GetFileTypes_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
std::shared_ptr<MockDataAbility> mockdataability = std::make_shared<MockDataAbility>();
Uri uri("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::string mimeTypeFilter("nullptr");
std::vector<std::string> types;
types = abilitythread->GetFileTypes(uri, mimeTypeFilter);
EXPECT_EQ((int)types.size(), 3);
if (types.size() == 3) {
EXPECT_STREQ("Type1", types.at(0).c_str());
EXPECT_STREQ("Type2", types.at(1).c_str());
EXPECT_STREQ("Type3", types.at(2).c_str());
}
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_GetFileTypes_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_GetFileTypes_0200
* @tc.name: GetFileTypes
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_GetFileTypes_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_GetFileTypes_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
Uri uri("\nullptr");
std::string mimeTypeFilter("nullptr");
std::vector<std::string> types;
int number = 0;
int types_size;
types = abilitythread->GetFileTypes(uri, mimeTypeFilter);
types_size = types.size();
EXPECT_EQ(number, types_size);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_GetFileTypes_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_OpenFile_0100
* @tc.name: OpenFile
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_OpenFile_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_OpenFile_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
std::shared_ptr<MockDataAbility> mockdataability = std::make_shared<MockDataAbility>();
Uri uri("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::string mode;
int fd = abilitythread->OpenFile(uri, mode);
EXPECT_EQ(fd, 11);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_OpenFile_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_OpenFile_0200
* @tc.name: OpenFile
* @tc.desc: Validate when normally entering a string.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_OpenFile_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_OpenFile_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
int fd = -1;
int value;
Uri uri("nullptr");
std::string mode;
value = abilitythread->OpenFile(uri, mode);
EXPECT_EQ(fd, value);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_OpenFile_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Insert_0100
* @tc.name: Insert
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Insert_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Insert_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
std::shared_ptr<MockDataAbility> mockdataability = std::make_shared<MockDataAbility>();
Uri uri("dataabilitytest://com.example.myapplication5.DataAbilityTest");
ValuesBucket value;
EXPECT_EQ(22, abilitythread->Insert(uri, value));
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Insert_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Insert_0200
* @tc.name: Insert
* @tc.desc: Validate when normally entering a string.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Insert_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Insert_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
Uri uri("\nullptr");
int number = -1;
ValuesBucket value;
EXPECT_EQ(number, abilitythread->Insert(uri, value));
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Insert_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Update_0100
* @tc.name: Update
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Update_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Update_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
std::shared_ptr<MockDataAbility> mockdataability = std::make_shared<MockDataAbility>();
Uri uri("dataabilitytest://com.example.myapplication5.DataAbilityTest");
ValuesBucket value;
DataAbilityPredicates predicates("test");
EXPECT_EQ(33, abilitythread->Update(uri, value, predicates));
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Update_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Update_0200
* @tc.name: Update
* @tc.desc: Validate when normally entering a string.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Update_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Update_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
Uri uri("\nullptr");
int number = -1;
ValuesBucket value;
DataAbilityPredicates predicates("test");
EXPECT_EQ(number, abilitythread->Update(uri, value, predicates));
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Update_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Delete_0100
* @tc.name: Delete
* @tc.desc: Validate when normally entering a string.
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Delete_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Delete_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
Uri uri("\nullptr");
int number = -1;
DataAbilityPredicates predicates("test");
EXPECT_EQ(number, abilitythread->Delete(uri, predicates));
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Delete_0100 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,691 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include <functional>
#include "ability_thread.h"
#include "ability_state.h"
#include "ability_loader.h"
#include "app_log_wrapper.h"
#include "ability_impl_factory.h"
#include "ability.h"
#include "ability_impl.h"
#include "context_deal.h"
#include "mock_page_ability.h"
#include "mock_service_ability.h"
#include "mock_ability_token.h"
#include "mock_ability_lifecycle_callbacks.h"
#include "mock_ability_impl.h"
#include "mock_ability_thread.h"
#include "mock_data_ability.h"
#include "ohos_application.h"
#include "page_ability_impl.h"
#include "uri.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
REGISTER_AA(MockDataAbility)
REGISTER_AA(MockPageAbility)
REGISTER_AA(MockServiceAbility)
class AbilityThreadTest : public testing::Test {
public:
AbilityThreadTest() : abilitythread_(nullptr)
{}
~AbilityThreadTest()
{
abilitythread_ = nullptr;
}
AbilityThread *abilitythread_;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityThreadTest::SetUpTestCase(void)
{}
void AbilityThreadTest::TearDownTestCase(void)
{}
void AbilityThreadTest::SetUp(void)
{
GTEST_LOG_(INFO) << "AbilityThreadTest SetUp";
}
void AbilityThreadTest::TearDown(void)
{
GTEST_LOG_(INFO) << "AbilityThreadTest TearDown";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleSaveAbilityState_0100
* @tc.name: ScheduleSaveAbilityState
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleSaveAbilityState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleSaveAbilityState_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
PacMap state;
abilitythread->ScheduleSaveAbilityState(state);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleSaveAbilityState_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleSaveAbilityState_0200
* @tc.name: ScheduleSaveAbilityState
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleSaveAbilityState_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleSaveAbilityState_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
PacMap state;
abilitythread->ScheduleSaveAbilityState(state);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleSaveAbilityState_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleRestoreAbilityState_0100
* @tc.name: ScheduleRestoreAbilityState
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleRestoreAbilityState_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleRestoreAbilityState_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
PacMap state;
abilitythread->ScheduleRestoreAbilityState(state);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleRestoreAbilityState_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleRestoreAbilityState_0200
* @tc.name: ScheduleRestoreAbilityState
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleRestoreAbilityState_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleRestoreAbilityState_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
PacMap state;
abilitythread->ScheduleSaveAbilityState(state);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleRestoreAbilityState_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Attach_3_Param_0100
* @tc.name: Attach
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Attach_3_Param_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_3_Param_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_3_Param_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Attach_3_Param_0200
* @tc.name: Attach
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Attach_3_Param_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_3_Param_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_3_Param_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Attach_2_Param_0100
* @tc.name: Attach
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Attach_2_Param_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_2_Param_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
abilitythread->Attach(application, abilityRecord);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_2_Param_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_Attach_2_Param_0200
* @tc.name: Attach
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Attach_2_Param_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_2_Param_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_Attach_2_Param_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleAbilityTransaction_0100
* @tc.name: ScheduleAbilityTransaction
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleAbilityTransaction_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleAbilityTransaction_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
Want want;
LifeCycleStateInfo lifeCycleStateInfo;
abilitythread->ScheduleAbilityTransaction(want, lifeCycleStateInfo);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleAbilityTransaction_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleAbilityTransaction_0200
* @tc.name: ScheduleAbilityTransaction
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleAbilityTransaction_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleAbilityTransaction_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
abilitythread->Attach(application, abilityRecord, nullptr);
Want want;
LifeCycleStateInfo lifeCycleStateInfo;
abilitythread->ScheduleAbilityTransaction(want, lifeCycleStateInfo);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleAbilityTransaction_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleConnectAbility_0100
* @tc.name: ScheduleConnectAbility
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleConnectAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleConnectAbility_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
Want want;
abilitythread->ScheduleConnectAbility(want);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleConnectAbility_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleConnectAbility_0200
* @tc.name: ScheduleConnectAbility
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleConnectAbility_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleConnectAbility_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
Want want;
abilitythread->ScheduleConnectAbility(want);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleConnectAbility_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleDisconnectAbility_0100
* @tc.name: ScheduleDisconnectAbility
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleDisconnectAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleDisconnectAbility_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->Attach(application, abilityRecord, mainRunner);
Want want;
abilitythread->ScheduleDisconnectAbility(want);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleDisconnectAbility_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleDisconnectAbility_0200
* @tc.name: ScheduleDisconnectAbility
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleDisconnectAbility_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleDisconnectAbility_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityImpl> abilityimpl = std::make_shared<AbilityImpl>();
Want want;
abilitythread->ScheduleDisconnectAbility(want);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleDisconnectAbility_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleCommandAbility_0100
* @tc.name: ScheduleCommandAbility
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleCommandAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleCommandAbility_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockServiceAbility";
abilityInfo->type = AbilityType::SERVICE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
std::shared_ptr<AbilityImpl> abilityimpl = std::make_shared<AbilityImpl>();
abilitythread->Attach(application, abilityRecord, mainRunner);
Want want;
bool restart = true;
int startId = 0;
abilitythread->ScheduleCommandAbility(want, restart, startId);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleCommandAbility_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_ScheduleCommandAbility_0200
* @tc.name: ScheduleCommandAbility
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleCommandAbility_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleCommandAbility_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
Want want;
bool restart = true;
int startId = 0;
abilitythread->ScheduleCommandAbility(want, restart, startId);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleCommandAbility_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_SendResult_0100
* @tc.name: SendResult
* @tc.desc: Simulate successful test cases
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_SendResult_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SendResult_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
std::shared_ptr<AbilityImpl> abilityimpl = std::make_shared<AbilityImpl>();
abilitythread->Attach(application, abilityRecord, mainRunner);
int requestCode = 0;
int resultCode = 0;
Want want;
abilitythread->SendResult(requestCode, resultCode, want);
sleep(1);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SendResult_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_SendResult_0200
* @tc.name: SendResult
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_SendResult_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SendResult_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityImpl> abilityimpl = std::make_shared<AbilityImpl>();
int requestCode = 0;
int resultCode = 0;
Want want;
abilitythread->SendResult(requestCode, resultCode, want);
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SendResult_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_AbilityThreadMain_0100
* @tc.name: AbilityThreadMain
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AbilityThreadMain_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0100 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->AbilityThreadMain(application, abilityRecord, mainRunner);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0100 end";
}
/**
* @tc.number: AaFwk_AbilityThread_AbilityThreadMain_0200
* @tc.name: AbilityThreadMain
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AbilityThreadMain_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0200 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->AbilityThreadMain(application, abilityRecord, mainRunner);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0200 end";
}
/**
* @tc.number: AaFwk_AbilityThread_AbilityThreadMain_0300
* @tc.name: AbilityThreadMain
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AbilityThreadMain_0300, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0300 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->AbilityThreadMain(application, abilityRecord);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0300 end";
}
/**
* @tc.number: AaFwk_AbilityThread_AbilityThreadMain_0400
* @tc.name: AbilityThreadMain
* @tc.desc: Validate when normally entering a string
*/
HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AbilityThreadMain_0400, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0400 start";
AbilityThread *abilitythread = new (std::nothrow) AbilityThread();
EXPECT_NE(abilitythread, nullptr);
if (abilitythread != nullptr) {
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockPageAbility";
abilityInfo->type = AbilityType::PAGE;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
EXPECT_NE(token, nullptr);
if (token != nullptr) {
std::shared_ptr<OHOSApplication> application = nullptr;
std::shared_ptr<AbilityLocalRecord> abilityRecord =
std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> mainRunner = EventRunner::Create(abilityInfo->name);
abilitythread->AbilityThreadMain(application, abilityRecord);
}
}
GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AbilityThreadMain_0400 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,654 @@
/*
* Copyright (c) 2021 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 "data_ability_helper.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <gmock/gmock-more-actions.h>
#include "mock_ability_manager_client.h"
#include "mock_ability_token.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
using testing::_;
using testing::Invoke;
using testing::Return;
class DataAbilityHelperTest : public testing::Test {
public:
DataAbilityHelperTest()
{}
~DataAbilityHelperTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void DataAbilityHelperTest::SetUpTestCase(void)
{}
void DataAbilityHelperTest::TearDownTestCase(void)
{}
void DataAbilityHelperTest::SetUp(void)
{}
void DataAbilityHelperTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_DataAbilityHelper_Create_0100
* @tc.name: DataAbilityHelper
* @tc.desc: Test the dataabilityhelper object.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Create_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Create_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper1 = DataAbilityHelper::Creator(nullptr);
EXPECT_EQ(helper1, nullptr);
std::shared_ptr<DataAbilityHelper> helper2 = DataAbilityHelper::Creator(context);
EXPECT_NE(helper2, nullptr);
std::shared_ptr<DataAbilityHelper> helper3 = DataAbilityHelper::Creator(nullptr, uri);
EXPECT_EQ(helper3, nullptr);
std::shared_ptr<DataAbilityHelper> helper4 = DataAbilityHelper::Creator(nullptr, nullptr);
EXPECT_EQ(helper4, nullptr);
std::shared_ptr<DataAbilityHelper> helper5 = DataAbilityHelper::Creator(context, nullptr);
EXPECT_EQ(helper5, nullptr);
std::shared_ptr<DataAbilityHelper> helper6 = DataAbilityHelper::Creator(context, uri);
EXPECT_NE(helper6, nullptr);
std::shared_ptr<DataAbilityHelper> helper7 = DataAbilityHelper::Creator(nullptr, nullptr, false);
EXPECT_EQ(helper7, nullptr);
std::shared_ptr<DataAbilityHelper> helper8 = DataAbilityHelper::Creator(context, nullptr, false);
EXPECT_EQ(helper8, nullptr);
std::shared_ptr<DataAbilityHelper> helper9 = DataAbilityHelper::Creator(nullptr, uri, false);
EXPECT_EQ(helper9, nullptr);
std::shared_ptr<DataAbilityHelper> helper10 = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper10, nullptr);
std::shared_ptr<DataAbilityHelper> helper11 = DataAbilityHelper::Creator(nullptr, nullptr, true);
EXPECT_EQ(helper11, nullptr);
std::shared_ptr<DataAbilityHelper> helper12 = DataAbilityHelper::Creator(context, nullptr, true);
EXPECT_EQ(helper12, nullptr);
std::shared_ptr<DataAbilityHelper> helper13 = DataAbilityHelper::Creator(nullptr, uri, true);
EXPECT_EQ(helper13, nullptr);
std::shared_ptr<DataAbilityHelper> helper14 = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper14, nullptr);
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Create_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Release_0100
* @tc.name: Release
* @tc.desc: Test whether the return value of release is true when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Release_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
EXPECT_EQ(true, helper->Release());
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Release_0200
* @tc.name: Release
* @tc.desc: Test whether the return value of release is false when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Release_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
EXPECT_EQ(false, helper->Release());
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Release_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_GetFileTypes_0100
* @tc.name: GetFileTypes
* @tc.desc: When the parameter passed by Creator is true, test whether the return value of getfiletypes is correct.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
std::string mimeTypeFilter("mimeTypeFiltertest");
std::vector<std::string> result = helper->GetFileTypes(uri2, mimeTypeFilter);
int count = result.size();
EXPECT_EQ(count, 3);
std::vector<std::string> list;
list.push_back("Types1");
list.push_back("Types2");
list.push_back("Types3");
for (int i = 0; i < count; i++) {
EXPECT_STREQ(result.at(i).c_str(), list.at(i).c_str());
}
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_GetFileTypes_0200
* @tc.name: GetFileTypes
* @tc.desc: Test whether the return value of GetFileTypes is 0 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetFileTypes_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::string mimeTypeFilter("mimeTypeFiltertest");
std::vector<std::string> result = helper->GetFileTypes(uri2, mimeTypeFilter);
int count = result.size();
EXPECT_EQ(count, 0);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetFileTypes_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_OpenFile_0100
* @tc.name: OpenFile
* @tc.desc: Test whether the return value of OpenFile is 1246 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
std::string mode("modetest");
int fd = helper->OpenFile(uri2, mode);
EXPECT_EQ(fd, 1246);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_OpenFile_0200
* @tc.name: OpenFile
* @tc.desc: Test whether the return value of OpenFile is -1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::string mode("modetest");
int fd = helper->OpenFile(uri2, mode);
EXPECT_EQ(fd, -1);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Insert_0100
* @tc.name: Insert
* @tc.desc: Test whether the return value of Insert is 2345 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
ValuesBucket val("valtest");
int index = helper->Insert(uri2, val);
EXPECT_EQ(index, 2345);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Insert_0200
* @tc.name: Insert
* @tc.desc: Test whether the return value of Insert is -1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Insert_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
ValuesBucket val("valtest");
int index = helper->Insert(uri2, val);
EXPECT_EQ(index, -1);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Insert_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Update_0100
* @tc.name: Update
* @tc.desc: Test whether the return value of Update is 3456 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
ValuesBucket val("valtest");
DataAbilityPredicates predicates("predicatestest");
int index = helper->Update(uri2, val, predicates);
EXPECT_EQ(index, 3456);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Update_0200
* @tc.name: Update
* @tc.desc: Test whether the return value of Update is -1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Update_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
ValuesBucket val("valtest");
DataAbilityPredicates predicates("predicatestest");
int index = helper->Update(uri2, val, predicates);
EXPECT_EQ(index, -1);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Update_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Delete_0100
* @tc.name: Delete
* @tc.desc: Test whether the return value of Delete is 6789 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
DataAbilityPredicates predicates("predicatestest");
int index = helper->Delete(uri2, predicates);
EXPECT_EQ(index, 6789);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Delete_0200
* @tc.name: Delete
* @tc.desc: Test whether the return value of Delete is -1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Delete_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
DataAbilityPredicates predicates("predicatestest");
int index = helper->Delete(uri2, predicates);
EXPECT_EQ(index, -1);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Delete_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Query_0100
* @tc.name: Query
* @tc.desc: Test whether the return value of Query is null when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
std::vector<std::string> columns;
DataAbilityPredicates predicates("predicatestest");
std::shared_ptr<ResultSet> set = helper->Query(uri2, columns, predicates);
EXPECT_NE(set, nullptr);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Query_0200
* @tc.name: Query
* @tc.desc: Test whether the return value of Query is null when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Query_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::vector<std::string> columns;
DataAbilityPredicates predicates("predicatestest");
std::shared_ptr<ResultSet> set = helper->Query(uri2, columns, predicates);
EXPECT_EQ(set, nullptr);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Query_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_GetType_0100
* @tc.name: GetType
* @tc.desc: Test whether the return value of GetType is Type1 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
std::string type = helper->GetType(uri2);
EXPECT_STREQ(type.c_str(), "Type1");
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_GetType_0200
* @tc.name: GetType
* @tc.desc: Test whether the return value of GetType is Type1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_GetType_0200, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::string type = helper->GetType(uri2);
EXPECT_STRNE(type.c_str(), "Type1");
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_GetType_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_OpenRawFile_0100
* @tc.name: OpenRawFile
* @tc.desc: Test whether the return value of OpenRawFile is 5678 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
std::string mode("modetest");
int fd = helper->OpenRawFile(uri2, mode);
EXPECT_EQ(fd, 5678);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_OpenRawFile_0200
* @tc.name: OpenRawFile
* @tc.desc: Test whether the return value of OpenRawFile is -1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenRawFile_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::string mode("modetest");
int fd = helper->OpenRawFile(uri2, mode);
EXPECT_EQ(fd, -1);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenRawFile_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Reload_0100
* @tc.name: Reload
* @tc.desc: Test whether the return value of Reload is true when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
PacMap extras;
bool ret = helper->Reload(uri2, extras);
EXPECT_EQ(ret, true);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_Reload_0200
* @tc.name: Reload
* @tc.desc: Test whether the return value of Reload is false when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_Reload_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
PacMap extras;
bool ret = helper->Reload(uri2, extras);
EXPECT_EQ(ret, false);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_Reload_0200 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_BatchInsert_0100
* @tc.name: BatchInsert
* @tc.desc: Test whether the return value of BatchInsert is 789 when the parameter passed by Creator is true.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0100 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, true);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataability://com.example.myapplication5.DataAbilityTest");
std::vector<ValuesBucket> values;
int ret = helper->BatchInsert(uri2, values);
EXPECT_EQ(ret, 789);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0100 end";
}
/**
* @tc.number: AaFwk_DataAbilityHelper_BatchInsert_0200
* @tc.name: BatchInsert
* @tc.desc: Test whether the return value of BatchInsert is -1 when the parameter passed by Creator is false.
*/
HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_BatchInsert_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0200 start";
std::shared_ptr<MockAbility> context = std::make_shared<MockAbility>();
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability://com.example.myapplication5.DataAbilityTest");
std::shared_ptr<DataAbilityHelper> helper = DataAbilityHelper::Creator(context, uri, false);
EXPECT_NE(helper, nullptr);
if (helper != nullptr) {
Uri uri2("dataabilitytest://com.example.myapplication5.DataAbilityTest");
std::vector<ValuesBucket> values;
int ret = helper->BatchInsert(uri2, values);
EXPECT_EQ(ret, -1);
}
GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_BatchInsert_0200 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,177 @@
/*
* Copyright (c) 2021 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 <gtest/gtest.h>
#include "ability_loader.h"
#include "app_log_wrapper.h"
#include "data_ability_impl.h"
#include "mock_ability_token.h"
#include "mock_data_ability.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
REGISTER_AA(MockDataAbility)
class DataAbilityImplTest : public testing::Test {
public:
DataAbilityImplTest() : dataabilityimpl(nullptr)
{}
~DataAbilityImplTest()
{
dataabilityimpl = nullptr;
}
DataAbilityImpl *dataabilityimpl;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void DataAbilityImplTest::SetUpTestCase(void)
{}
void DataAbilityImplTest::TearDownTestCase(void)
{}
void DataAbilityImplTest::SetUp(void)
{}
void DataAbilityImplTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_DataAbilityImplTest_BatchInsert_0100
* @tc.name: BatchInsert
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(DataAbilityImplTest, AaFwk_DataAbilityImplTest_BatchInsert_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_BatchInsert_001 start";
std::shared_ptr<DataAbilityImpl> dataabilityimpl = std::make_shared<DataAbilityImpl>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
std::shared_ptr<MockDataAbility> dataAbility = std::make_shared<MockDataAbility>();
std::shared_ptr<Ability> ability;
ability.reset(dataAbility.get());
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
dataabilityimpl->Init(application, record, ability, handler, token, contextDeal);
int ret;
Uri uri("nullptr");
std::vector<ValuesBucket> values;
ret = dataabilityimpl->BatchInsert(uri, values);
EXPECT_EQ(1, ret);
sleep(1);
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_BatchInsert_001 end";
}
/**
* @tc.number: AaFwk_DataAbilityImplTest_BatchInsert_0200
* @tc.name: BatchInsert
* @tc.desc: Validate when normally entering a string.
*/
HWTEST_F(DataAbilityImplTest, AaFwk_DataAbilityImplTest_BatchInsert_002, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_BatchInsert_002 start";
std::shared_ptr<DataAbilityImpl> dataabilityimpl = std::make_shared<DataAbilityImpl>();
int ret;
Uri uri("nullptr");
std::vector<ValuesBucket> values;
ret = dataabilityimpl->BatchInsert(uri, values);
EXPECT_EQ(-1, ret);
sleep(1);
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_BatchInsert_002 end";
}
/**
* @tc.number: AaFwk_DataAbilityImplTest_HandleAbilityTransaction_0100
* @tc.name: GetFileTypes
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(DataAbilityImplTest, AaFwk_DataAbilityImplTest_HandleAbilityTransaction_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_HandleAbilityTransaction_001 start";
std::shared_ptr<DataAbilityImpl> dataabilityimpl = std::make_shared<DataAbilityImpl>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
std::shared_ptr<MockDataAbility> dataAbility = std::make_shared<MockDataAbility>();
std::shared_ptr<Ability> ability;
ability.reset(dataAbility.get());
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
dataabilityimpl->Init(application, record, ability, handler, token, contextDeal);
Want want;
LifeCycleStateInfo targetState;
dataabilityimpl->HandleAbilityTransaction(want, targetState);
sleep(1);
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_HandleAbilityTransaction_001 end";
}
/**
* @tc.number: AaFwk_DataAbilityImplTest_HandleAbilityTransaction_0200
* @tc.name: GetFileTypes
* @tc.desc: Simulate successful test cases.
*/
HWTEST_F(DataAbilityImplTest, AaFwk_DataAbilityImplTest_HandleAbilityTransaction_002, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_HandleAbilityTransaction_002 start";
std::shared_ptr<DataAbilityImpl> dataabilityimpl = std::make_shared<DataAbilityImpl>();
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "MockDataAbility";
abilityInfo->type = AbilityType::DATA;
sptr<IRemoteObject> token = sptr<IRemoteObject>(new (std::nothrow) MockAbilityToken());
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<EventRunner> eventRunner = EventRunner::Create(abilityInfo->name);
sptr<AbilityThread> abilityThread = sptr<AbilityThread>(new (std::nothrow) AbilityThread());
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
std::shared_ptr<MockDataAbility> dataAbility = std::make_shared<MockDataAbility>();
std::shared_ptr<Ability> ability;
ability.reset(dataAbility.get());
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
dataabilityimpl->Init(application, record, ability, handler, token, contextDeal);
Want want;
LifeCycleStateInfo targetState;
dataabilityimpl->HandleAbilityTransaction(want, targetState);
sleep(1);
GTEST_LOG_(INFO) << "AaFwk_DataAbilityImplTest_HandleAbilityTransaction_002 end";
}
} // namespace AppExecFwk
} // namespace OHOS

Some files were not shown because too many files have changed in this diff Show More